简体   繁体   中英

Log in with twitter4j callback

I try to write an application where an user can log in on twitter. I use twitter4j like library.My problem is that when I go in the page where I must put username and password, the program block because i don't know use callback to came in my application. Someone can me help?

public class MainActivity extends Activity {

private Twitter twitter;
RequestToken requestToken;
final public static String CALLBACK_SCHEME = "x-latify-oauth-twitter";
final public static String CALLBACK_URL = CALLBACK_SCHEME + "://callback";
private Uri uri;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new updateTwitterStatus().execute();

        }
    });

}

@Override
protected void onDestroy() {

    twitter.shutdown();
}

class updateTwitterStatus extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String testStatus = "prova tweet ";

        ConfigurationBuilder cb = new ConfigurationBuilder();

        // the following is set without accesstoken- desktop client
        cb.setDebugEnabled(true)
                .setOAuthConsumerKey("******")
                .setOAuthConsumerSecret(
                        "*****");

        try {
            TwitterFactory tf = new TwitterFactory(cb.build());
            twitter = tf.getInstance();
            Log.i("bauu", "miao");

            requestToken = twitter.getOAuthRequestToken();
            String authUrl = requestToken.getAuthenticationURL();
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse(requestToken.getAuthenticationURL())));
            uri = Uri.parse(requestToken.getAuthenticationURL());

            return authUrl;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {

        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(s)));    
    }

}

Make sure your callback URL in twitter dev app options are as follows,

http://YOUR-URL/app://YOUR-APP-HOST

and within your android manifest file, in between the of the actvitiy that takes you to twitter, make sure you define:

         <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:host="YOUR-APP-HOST"
              android:scheme="app" />
          </intent-filter>

lastly, make sure in your program,

final public static String CALLBACK_URL = "app://YOUR-APP-HOST";

Twitter login in 4 easy steps:

1- Add intent-filter for your activity (Based on @rennoDeniro response) AndroidManifest.xml

 <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:host="twitter"
              android:scheme="myapp" />
 </intent-filter>   

2- Define twitter key and secret in strings.xml

<string name="twitter_consumerKey">XXX</string>
<string name="twitter_consumerSecret">XXX</string>

3- Request twitter for signup page in MainActivity.java

public String CALLBACK_URL="myapp://twitter";
public Twitter twitter;
private static RequestToken rToken;


public void onLoginTwitter(View v) {
    (new RequestTwitterLoginTask()).execute();
}

class RequestTwitterLoginTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        twitter = new TwitterFactory().getInstance();
        try
        {
            twitter.setOAuthConsumer(R.string.twitter_consumerKey, R.string.twitter_consumerSecret);
            String callbackURL = CALLBACK_URL;
            rToken= twitter.getOAuthRequestToken(callbackURL);

        }
        catch(Exception e)
        {
               Toast.makeText(getApplicationContext(), "Exception: " + e.toString(),Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }            

        return null;
    }


    @Override
    protected void onPostExecute(String s) {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(rToken.getAuthenticationURL())));
    }
}    

4- Handle Callback in MainActivity.java

public void onResume(){
    super.onResume();

    if (this.getIntent()!=null && this.getIntent().getData()!=null){
        Uri uri = this.getIntent().getData();

        //handle returning from authenticating the user
        if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
            String token = uri.getQueryParameter("oauth_token");
            String verifier = uri.getQueryParameter("oauth_verifier");

            try {
                Twitter t = new TwitterFactory().getInstance();
                t.setOAuthConsumer(getResources().getString(R.string.twitter_consumerKey), getResources().getString(R.string.twitter_consumerSecret));

                AccessToken accessToken = t.getOAuthAccessToken(rToken,verifier);

                long userID = accessToken.getUserId();
                User user = t.showUser(userID);

                /* Do whatever you want */
            } catch (TwitterException e) {
                Toast.makeText(getApplicationContext(), "Twitter Exception: " + e.toString(),Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            return;
        }
    }    

    Toast.makeText(getApplicationContext(), "Resume",Toast.LENGTH_SHORT).show();

}

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