我希望使用Twitter4J连接到Twitter。在MainActivity
中调用TwitterLoginActivity
,然后在TwitterLoginActivity中显示一个WebView,并通过OnNewIntent()获取accessToken。问题是,在我“登录”Twitter之后,WebView显示“网页不可用”。这是我的代码。
MainActivity调用TwitterLoginActivity:
final Intent intent = new Intent(MainActivity.this, TwitterLoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(intent, Constant.LOGIN_REQUEST);
TwitterLoginActivity显示一个WebView。
final WebView twitterSite = new WebView(this);
final ViewGroup viewGroup = (ViewGroup)findViewById(R.id.twitterLoginRoot);
viewGroup.addView(twitterSite);
// Open keyboard when focusing on Twitter login form.
twitterSite.requestFocus(View.FOCUS_DOWN);
twitterSite.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(final View v, final MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
}
break;
}
return false;
}
});
twitterSite.setWebViewClient(new CustomWebViewClient());
try {
final RequestToken requestToken = twitter.getOAuthRequestToken(Constant.CALLBACK_URL);
twitterSite.loadUrl(requestToken.getAuthenticationURL());
} catch (final TwitterException e) {
e.printStackTrace();
}
onNewIntent:
@Override
protected void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
System.out.println("HIEU=================================");
setResult(RESULT_OK);
finish();
}
我使用这个来防止默认浏览器加载。
private class CustomWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
view.loadUrl(url);
return true;
}
}
清单文件:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.twitterapitest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission
android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".TwitterLoginActivity"
android:label="@string/title_activity_main"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="test123"/>
</intent-filter>
</activity>
</application>
</manifest>
回调URI:
public static final String CALLBACK_URL = "test123:///";