【发布时间】:2016-07-16 16:19:06
【问题描述】:
我正在尝试授权我的 GitHub 应用程序并返回我的应用程序。我使用 Intent 打开授权页面,但无法从浏览器返回我的应用程序。你能看看我的代码,告诉我哪里出错了吗?
LoginActivity.java
private final String clientId="myclientid";
private final String clientSecret="myclientsecret";
private final String redirectUri="http://localhost";
private final String state="randomshit";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button loginButton = (Button) findViewById(R.id.loginbutton);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://github.com/login/oauth/authorize?" +
"&client_id="+clientId+
"&redirect_uri="+redirectUri+
"&state="+state)
);
startActivity(intent);
}
});
}
@Override
protected void onResume() {
super.onResume();
// the intent filter defined in AndroidManifest will handle the return from ACTION_VIEW intent
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(redirectUri)) {
String code = uri.getQueryParameter("code");
if (code != null) {
Log.d("code",code);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.figengungor.retrogithub">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="localhost"
android:scheme="http" />
</intent-filter>
</activity>
</application>
</manifest>
我的 GitHub 应用和重定向 uri:
【问题讨论】:
-
can't go back to my app from browser是什么意思?你得到的回应是什么? -
按下手机中的“返回键”会发生什么?
-
授权后重定向到我的redirectUri,并且code参数附加到我的redirectUri,表示授权成功。据说如果 redirectUri 与我添加的意图过滤器中的重定向匹配,它应该返回到应用程序,然后我的 onResume 部分提取代码参数。不应该这样工作吗?
-
当按钮被点击时,首先会生成URL。网址是:“github.com/login/oauth/authorize?” + "&client_id="+clientId+ "&redirect_uri="+redirectUri+ "&state="+state;然后既然你用 Intent 说 startActivity(intent)。看法;它将打开浏览器并转到上述 URL。这就对了。之后代码中就没有什么可做的了。
标签: android api github authorization