在Android中的Dialog Dismiss之后调用onActivityResult()

时间:2013-07-10 11:54:52

标签: android twitter

我正在尝试将FacebookTwitter集成到我的应用程序中。当用户点击按钮时,我正在显示一个包含Facebook和Twitter两个选项的对话框。当用户点击Twitter时,我正在关闭对话框并调用Twitter PrepareRequestToken activity

这是我的PrepareRequestToken课程:

public class PrepareRequestTokenActivity extends Activity {

    final String TAG = getClass().getName();
    private Twitter twitter;
    private CommonsHttpOAuthConsumer consumer;
    private OAuthProvider provider;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getConsumerProvider();
        try {
            consumer = new CommonsHttpOAuthConsumer(ConstantValues.CONSUMER_KEY, ConstantValues.CONSUMER_SECRET);
            provider = new DefaultOAuthProvider(
                    "https://api.twitter.com/oauth/request_token",
                    "https://api.twitter.com/oauth/access_token",
                    "https://api.twitter.com/oauth/authorize");
            String authUrl = provider.retrieveRequestToken(consumer, ConstantValues.CALLBACK_URL);
            Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
            setConsumerProvider();
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }


    @Override
    public void onNewIntent(Intent intent) {

        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        final Uri uri = intent.getData();
        if (uri != null && uri.getScheme().equals(ConstantValues.OAUTH_CALLBACK_SCHEME)) {
            new RetrieveAccessTokenTask(this, consumer, provider, prefs).execute(uri);
            //showMessage();
        }
//      finish();
        super.onNewIntent(intent);
    }

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

        private OAuthProvider provider;
        private OAuthConsumer consumer;

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

        /**
         * 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);

                AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
                storeAccessToken(a);

                // initialize Twitter4J
                twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(ConstantValues.CONSUMER_KEY, ConstantValues.CONSUMER_SECRET);
                twitter.setOAuthAccessToken(a);
                ((DogRescueApplication)getApplication()).setTwitter(twitter);

                //Log.e("Login", "Twitter Initialised");
                System.out.println("finishing...!!");
                Intent returnIntent = new Intent();
                returnIntent.putExtra("valid", "valid");
                setResult(RESULT_OK, returnIntent);
//              finish();
                Log.i(TAG, "OAuth - Access Token Retrieved");
            } catch (Exception e) {
                Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
                setResult(RESULT_CANCELED);
//              finish();
            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            System.out.println("onpostexecute...!!");
            finish();
        }

    }
    private void setConsumerProvider() {
        if (provider!=null){
            ((DogRescueApplication)getApplication()).setProvider(provider);
        }
        if (consumer!=null){
            ((DogRescueApplication)getApplication()).setConsumer(consumer);
        }
    }
    private void getConsumerProvider() {
        OAuthProvider p = ((DogRescueApplication)getApplication()).getProvider();
        if (p!=null){
            provider = p;
        }
        CommonsHttpOAuthConsumer c = ((DogRescueApplication)getApplication()).getConsumer();
        if (c!=null){
            consumer = c;
        }
    }
    private void storeAccessToken(AccessToken a) {
        System.out.println("Storing keys!!");
        SharedPreferences settings = getSharedPreferences(ConstantValues.PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("accessTokenToken", a.getToken());
        editor.putString("accessTokenSecret", a.getTokenSecret());
        editor.commit();
    }

}

我使用以下方式开始此活动:

give_twitter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                    Intent i = new Intent(CampaignActivity.this,PrepareRequestTokenActivity.class);
                    startActivityForResult(i, TWITTER_AUTH_REQ_CODE);
                dialog.dismiss();
            }
        });

并将响应处理为:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {

        case TWITTER_AUTH_REQ_CODE:
            if(resultCode == RESULT_OK){
                if(checkForSavedLogin()){
//                  String post_msg = "Hello.. Mobile APp";
//                  TwitterUtilities.postTweet(twitter, post_msg);
                    getTwitterProfileData();
                }
            }
            break;
        }
    }

但是onActivityResult()方法没有被回复调用.. 请帮帮我...

2 个答案:

答案 0 :(得分:0)

你试过在setResult(int,intent)之后调用finish()吗?因为在你的情况下它在doInBackground中被注释!

答案 1 :(得分:0)

问题已解决..从Web返回后,再次创建活动,因此我使用一个小条件来检查我的OnCreate中的意图数据是否为空。 通过使用此代码,我可以得到结果:

if (getIntent().getData()!=null) {
            Uri uri = getIntent().getData();
            if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
                String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
                try {
                    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
                    // Shared Preferences
                    Editor e = mSharedPreferences.edit();
                    e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                    e.putString(PREF_KEY_OAUTH_SECRET,accessToken.getTokenSecret());
                    e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                    e.commit();
                    Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
                    getTwitterProfileData();

                } catch (Exception e) {
                    Log.e("Twitter Login Error", "> " + e.getMessage());
                }
            }
        }

注意:我在PrepareRequestToken课程中更改了一点以匹配此内容。