我想使用 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:///";