简体   繁体   English

使用twitter4j回调登录

[英]Log in with twitter4j callback

I try to write an application where an user can log in on twitter. 我尝试编写一个用户可以在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. 我像库一样使用twitter4j。​​我的问题是,当我进入必须输入用户名和密码的页面时,程序块被阻止,因为我不知道在应用程序中使用回调函数。 Someone can me help? 有人可以帮忙吗?

public class MainActivity extends Activity { 公共类MainActivity扩展了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, 确保您在twitter dev应用程序选项中的回调URL如下,

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: 并在您的Android清单文件中,在将您带到Twitter的活动之间,请确保您定义:

         <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: Twitter登录只需4个简单步骤:

1- Add intent-filter for your activity (Based on @rennoDeniro response) AndroidManifest.xml 1-为您的活动添加意图过滤器 (基于@rennoDeniro响应) 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 2-在strings.xml定义Twitter密钥和秘密

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

3- Request twitter for signup page in MainActivity.java 3-在MainActivity.java请求Twitter申请注册页面

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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