Android twitter登录无法正常工作

时间:2013-04-04 09:17:20

标签: android twitter

我打算开发一个Android应用程序,方便 Twitter集成来获取Twitter好友列表。当我尝试登录Twitter时,只需显示重定向页面一段时间,然后再打开Twitter登录页面。

这是我的代码:

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;


/**
 * Prepares a OAuthConsumer and OAuthProvider 
 * 
 * OAuthConsumer is configured with the consumer key & consumer secret.
 * OAuthProvider is configured with the 3 OAuth endpoints.
 * 
 * Execute the OAuthRequestTokenTask to retrieve the request, and authorize the request.
 * 
 * After the request is authorized, a callback is made here.
 * 
 */
public class PrepareRequestTokenActivity extends Activity {

    public static boolean isTweetCompleted = false;
    public static int  checkvalue=0;
    final String TAG = getClass().getName();

    private OAuthConsumer consumer; 
    private OAuthProvider provider;
    private boolean _isProcessCompleted;
    private TextView twitterTxt = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.twitter_dialog);
        checkvalue=this.getIntent().getIntExtra("check",0);
        @SuppressWarnings("unused")
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        try {
            this.consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
            this.provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,Constants.ACCESS_URL,Constants.AUTHORIZE_URL);
        } catch (Exception e) {
        }
        new OAuthRequestTokenTask(this,consumer,provider).execute();
        _isProcessCompleted = true;
    }

    /**
     * Called when the OAuthRequestTokenTask finishes (user has authorized the request token).
     * The callback URL will be intercepted here.
     */
    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        _isProcessCompleted = true;
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        final Uri uri = intent.getData();
        if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
            new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
        }
    }

    @Override
    protected void onResume() {
        if(!_isProcessCompleted)
            finish();
        else 
            _isProcessCompleted = false;
        super.onResume();
    }

    public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {

        private Context context;
        private OAuthProvider provider;
        private OAuthConsumer consumer;
        private SharedPreferences prefs;

        public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
            this.context = context;
            this.consumer = consumer;
            this.provider = provider;
            this.prefs=prefs;
        }

        /**
         * Retrieve the oauth_verifier, and store the oauth and oauth_token_secret 
         * for future API calls.
         */
        @Override
        protected Void doInBackground(Uri...params) {
            final Uri uri = params[0];
            final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
            try {
                provider.retrieveAccessToken(consumer, oauth_verifier);
                final Editor edit = prefs.edit();
                edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
                edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
                edit.commit();              
                String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
                String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

                consumer.setTokenWithSecret(token, secret);
                //------------------------------------------------------------------------
                //  context.startActivity(new Intent(context,WeddingRituals.class));            
                //------------------------------------------------------------------------
                //  executeAfterAccessTokenRetrieval(prefs);

                TwitterUtils.getFriendsList(prefs);

            } catch (Exception e) {
                System.out.println(e.toString());
            }

            finish();
            return null;
        }
    }   

    private void executeAfterAccessTokenRetrieval(SharedPreferences prefs) {
        String msg = getIntent().getExtras().getString("tweet_msg");
        int charLimit = 139;
        int _msgSize = msg.length();
        int i=0;
        int parts = _msgSize/139;
        String data = null;
        try {
            if(_msgSize > charLimit){
                int temp1=0,temp2=charLimit;
                while(i<parts+1){
                    if(i==parts){
                        data = msg.substring(temp1, _msgSize);
                    }else{
                        data = msg.substring(temp1, temp2);
                        temp1=temp2+1;
                        temp2=temp2+charLimit;
                    }
                    i++;
                    if(data!=null && !data.equalsIgnoreCase(""))
                        TwitterUtils.sendTweet(prefs, data);
                }
            }else{
                TwitterUtils.sendTweet(prefs, data);
            }

            Message message = new Message();
            message.arg1 = 0;
            saveHandler.sendMessage(message);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    private Handler saveHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.arg1 == 0){
                Toast.makeText(PrepareRequestTokenActivity.this, "Buzz posted successfully", Toast.LENGTH_LONG).show();
                //successAlert();
            }
        }
    };

    public void successAlert()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(PrepareRequestTokenActivity.this);
        builder.setMessage("Buzz posted successfully");
        builder.setCancelable(true);
        builder.setInverseBackgroundForced(true);
        builder.setNeutralButton("Ok",  new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }

}

0 个答案:

没有答案