简体   繁体   中英

Can't tweet with twitter4j

I'm facing a problem when a try to send a tweet (fixed message) from my Android app. I've tried it with 4 different code samples (all of them using twitter4j), taken from different forums, but always got the same result: I put my user and password, the authentication works fine, but after that I'm always redirected to the URL specified in "callback_url" (I've tested with existing urls and not existing as well) and the tweet is not published. As you can see, I have separated methods for authentication and for sending the tweet, but once the authentication is finished, the control is never returned to my app. I'm using android 2.1 (tested with 2.2 too). Any help will be really appreciated. Thanks in advance.

public void onCreate(Bundle savedInstanceState) {

   mTwitter = new TwitterFactory().getInstance();
   mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
   if (mPrefs.contains(PREF_ACCESS_TOKEN)) {
       loginAuthorisedUser();
   } else {
    loginNewUser();
   }
}

private void loginNewUser() {
    try {
        mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);

        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();

    buttonTweet(null);
}

/**
 * Catch when Twitter redirects back to our {@link CALLBACK_URL}</br> 
 * We use onNewIntent as in our manifest we have singleInstance="true" if we did not the
 * getOAuthAccessToken() call would fail
 */
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    dealWithTwitterResponse(intent);
}

/**
 * Twitter has sent us back into our app</br> 
 * Within the intent it set back we have a 'key' we can use to authenticate the user
 * 
 * @param intent
 */
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);
    }
}

/**
 * Create an access token for this new user</br> 
 * Fill out the Twitter4j helper</br> 
 * And save these credentials so we can log the user straight in next time
 * 
 * @param 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.main);

        tweetMessage();
    } catch (TwitterException e) {
        Toast.makeText(this, "Twitter auth error x01, try again later", Toast.LENGTH_SHORT).show();
    }
}

private void tweetMessage() {
    try {
        mTwitter.updateStatus("Test - Tweeting");

        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();
}

Declaration of activity in AndroidManifest:

<activity android:name=".share.twitter.TwitterActivity" 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="http://www.someurl.com" />
    </intent-filter>
</activity>

Here is a link to a one file solution that explains exactly how to integrate picture/text tweets into an android app.

I just got through dealing with this and rather than try to fix your code try using the code supplied. It should work without modification and can send a tweet with one call to a tweet() function.

The scheme and host in your android app should be something unique to the app so that android knows what app should handle the callback. What you have now makes android think your app can handle web browsing with the "http" scheme. Check out the answers to the post here. Specifically, frankenstein describes how to setup the scheme and hosts, and my code will show you how to handle the onResume().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM