我正在使用twitter4J在Twitter上发布推文
在这里,我根据您的建议更改代码。我做一些谷歌搜索。 问题是当我尝试从主要活动转移到推特活动时,显示强制关闭。 主要活动是=“MainActivity” twitter活动是=“twiti_backup” 我认为Manifestfile中存在问题,但我不知道它是什么。
public class twiti_backup extends Activity {
private static final String TAG = "Blundell.TweetToTwitterActivity";
private static final String PREF_ACCESS_TOKEN = "";
private static final String PREF_ACCESS_TOKEN_SECRET = "";
private static final String CONSUMER_KEY = "";
private static final String CONSUMER_SECRET = "";
private static final String CALLBACK_URL = "android:///";
private SharedPreferences mPrefs;
private Twitter mTwitter;
private RequestToken mReqToken;
private Button mLoginButton;
private Button mTweetButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Loading TweetToTwitterActivity");
setContentView(R.layout.twite);
mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);
mTwitter = new TwitterFactory().getInstance();
mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
mLoginButton = (Button) findViewById(R.id.login_button);
mTweetButton = (Button) findViewById(R.id.tweet_button);
}
public void buttonLogin(View v) {
Log.i(TAG, "Login Pressed");
if (mPrefs.contains(PREF_ACCESS_TOKEN)) {
Log.i(TAG, "Repeat User");
loginAuthorisedUser();
} else {
Log.i(TAG, "New User");
loginNewUser();
}
}
public void buttonTweet(View v) {
Log.i(TAG, "Tweet Pressed");
tweetMessage();
}
private void loginNewUser() {
try {
Log.i(TAG, "Request App Authentication");
mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
Log.i(TAG, "Starting Webview to login to twitter");
WebView twitterSite = new WebView(this);
twitterSite.loadUrl(mReqToken.getAuthenticationURL());
setContentView(twitterSite);
} catch (TwitterException e) {
Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
}
}
private void loginAuthorisedUser() {
String token = mPrefs.getString(PREF_ACCESS_TOKEN, null);
String secret = mPrefs.getString(PREF_ACCESS_TOKEN_SECRET, null);
// Create the twitter access token from the credentials we got previously
AccessToken at = new AccessToken(token, secret);
mTwitter.setOAuthAccessToken(at);
Toast.makeText(this, "Welcome back", Toast.LENGTH_SHORT).show();
enableTweetButton();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.i(TAG, "New Intent Arrived");
dealWithTwitterResponse(intent);
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "Arrived at onResume");
}
private void dealWithTwitterResponse(Intent intent) {
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) { // If the user has just logged in
String oauthVerifier = uri.getQueryParameter("oauth_verifier");
authoriseNewUser(oauthVerifier);
}
}
private void authoriseNewUser(String oauthVerifier) {
try {
AccessToken at = mTwitter.getOAuthAccessToken(mReqToken, oauthVerifier);
mTwitter.setOAuthAccessToken(at);
saveAccessToken(at);
// Set the content view back after we changed to a webview
setContentView(R.layout.twite);
enableTweetButton();
} catch (TwitterException e) {
Toast.makeText(this, "Twitter auth error x01, try again later", Toast.LENGTH_SHORT).show();
}
}
private void enableTweetButton() {
Log.i(TAG, "User logged in - allowing to tweet");
mLoginButton.setEnabled(false);
mTweetButton.setEnabled(true);
}
private void tweetMessage() {
try {
mTwitter.updateStatus("Test - Tweeting with @Blundell_apps #AndroidDev Tutorial using #Twitter4j http://blog.blundell-apps.com/sending-a-tweet/");
Toast.makeText(this, "Tweet Successful!", Toast.LENGTH_SHORT).show();
} catch (TwitterException e) {
Toast.makeText(this, "Tweet error, try again later", Toast.LENGTH_SHORT).show();
}
}
private void saveAccessToken(AccessToken at) {
String token = at.getToken();
String secret = at.getTokenSecret();
Editor editor = mPrefs.edit();
editor.putString(PREF_ACCESS_TOKEN, token);
editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
editor.commit();
}
}
这是Manifest
<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"
android:launchMode="singleInstance"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".twiti_backup"
android:launchMode="singleInstance">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="android" android:host="callback_main" /> </activity>
<activity android:name=".MyTwite"/>
<activity android:name=".mp3" />
<activity android:name=".myfbapp" />
</application>
当我尝试从主要活动
启动twiti_backup时,这是Log catW/dalvikvm(16357): threadid=1: thread exiting with uncaught exception (group=0x4001d5a0)
E/AndroidRuntime(16357): FATAL EXCEPTION: main E/AndroidRuntime(16357): java.lang.VerifyError: com.example.uitest.twiti_backup
E/AndroidRuntime(16357): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(16357): at java.lang.Class.newInstance(Class.java:1409)
E/AndroidRuntime(16357): at android.app.Instrumentation.newActivity(Instrumentation.java:1040)
E/AndroidRuntime(16357): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1735)
E/AndroidRuntime(16357): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1842)
E/AndroidRuntime(16357): at android.app.ActivityThread.access$1500(ActivityThread.java:132)
E/AndroidRuntime(16357): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1038)
E/AndroidRuntime(16357): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(16357): at android.os.Looper.loop(Looper.java:143)
E/AndroidRuntime(16357): at android.app.ActivityThread.main(ActivityThread.java:4263)
E/AndroidRuntime(16357): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(16357): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(16357): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime(16357): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime(16357): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
首先,与CALLBACKURL = "T4J_OAuth://callback_main"
相比,您的manifest
出错了,应该是:CALLBACKURL = "T4J_OAuth:///"
第二次:android:launchMode="singleTop"
应为android:launchMode="singleInstance"
也许还有一些错误,但是你应该把它解决掉!
已编辑:您应声明Provider
和Consumer
:
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRETE);
provider = new DefaultOAuthProvider(
"http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize");
provider.retrieveRequestToken(consumer, CALL_BACK);
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(result)));
此外,您应该创建一些AsyncTask
来调用这些语句:rovider.retrieveRequestToken(consumer, CALL_BACK);
和provider.retrieveAccessToken(consumer, verifier);
已修改请查看此tutorial,只需将CallBack_Url = "..."
更改为CallBack_URL = "callback:///"
,然后使用以下代码创建Twitter
对象:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY)
.setOAuthConsumerSecret(CONSUMER_SECRETE)
// accessTokenKey and accessTokenSecrete are what you get after redirecting
// back from your oauthentication
.setOAuthAccessToken(accessTokenKey)
.setOAuthAccessTokenSecret(accessTokenSecrete)
.setMediaProviderAPIKey(TWITPIC_API_KEY);
Configuration config = cb.build();
TwitterFactory tf = new TwitterFactory(config);
Twitter twitter = tf.getInstance();
注意:不要让call back url
中的twitter app
属性为null,将任何虚拟链接放入其中! (你的Twitter帐户的应用程序!!不是你的Android应用程序!)
对不起,如果有任何类型错误!
编辑由于您的验证程序错误,您收到Verifier
错误!我使用signpost
lib来获取verifier
:String verifier = data
.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
我认为您应该尝试使用signpost
lib!
答案 1 :(得分:2)
在setcontentview()行之后,将以下两行代码添加到主活动的onCreate方法中,它将解决您的问题。
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}