简体   繁体   English

onNewIntent(intent)无法正常工作

[英]onNewIntent(intent) not working as it should

I am building this twitter app where browser is called to authenticate from my main activity.. running the following code in a thread(AsyncTask) 我正在构建这个Twitter应用程序,其中调用浏览器以从我的主要活动进行身份验证..在线程中运行以下代码(AsyncTask)

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
context.startActivity(intent);

here 这里

context is the context of main activity..the uri is returned through `intent`..

After authentication what it to do is to come back to my main activity,to its present state.. What happens now is,it create another instance of main activity.. 在认证之后,它要做的是回到我的主要活动,到现在的状态。现在发生的是,它创建了另一个主要活动的实例。

I am using 我在用

@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent); 
    SharedPreferences prefs = getSharedPreferences("twitter", 0);
    final Uri uri = intent.getData();
    if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {

        setLoggedIn(true, tlogout);
        tstatus=true;

        new RetrieveAccessTokenTask(this,consumer,provider,prefs,tstring).execute(uri);

    }
}

but still,the problem persist..another thing is,everything works fine in emulator(2.3).. Not working in my device..its Android 2.3.6 但仍然,问题仍然存在..另一件事是,一切正常模拟器(2.3)..不能在我的设备工作.. Android 2.3.6

my manifest is 我的清单是

<activity
    android:name=".mainActivity"

    android:launchMode="singleTask"

    android:label="@string/title_activity_main" >
    <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="x-oauthflow-twitter" android:host="callback" />

    </intent-filter>
</activity>

I'm not familiar with Twitter athentication process, but you can try FLAG_ACTIVITY_CLEAR_TOP instead of Intent.FLAG_ACTIVITY_SINGLE_TOP . 我不熟悉与Twitter athentication过程,但你可以尝试FLAG_ACTIVITY_CLEAR_TOP代替Intent.FLAG_ACTIVITY_SINGLE_TOP

The later only works for you if your main activity in on top of stack, the other clears the stack and ensures that your activity in on top. 如果您的主要活动位于堆栈顶部,另一个清除堆栈并确保您的活动位于顶部,则后者仅适用于您。

OAuthRequestTokenTask.java OAuthRequestTokenTask.java

package com.android.twit;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {

final String TAG = getClass().getName();
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;

/**
 * 
 * We pass the OAuth consumer and provider.
 * 
 * @param context
 *            Required to be able to start the intent to launch the browser.
 * @param provider
 *            The OAuthProvider object
 * @param consumer
 *            The OAuthConsumer object
 */
public OAuthRequestTokenTask(Context context, OAuthConsumer consumer,
        OAuthProvider provider) {
    this.context = context;
    this.consumer = consumer;
    this.provider = provider;
}

/**
 * 
 * Retrieve the OAuth Request Token and present a browser to the user to
 * authorize the token.
 * 
 */
@Override
protected Void doInBackground(Void... params) {

    try {
        Log.i(TAG, "Retrieving request token from Google servers");
        final String url = provider.retrieveRequestToken(consumer,
                ConstantsTwit.OAUTH_CALLBACK_URL);
        Log.i(TAG, "Popping a browser with the authorize URL : " + url);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url))
                .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                        | Intent.FLAG_ACTIVITY_NO_HISTORY
                        | Intent.FLAG_FROM_BACKGROUND);
        context.startActivity(intent);
    } catch (Exception e) {
        Log.e(TAG, "Error during OAUth retrieve request token", e);
    }

    return null;
}

}

PrepareRequestTokenActivity.java PrepareRequestTokenActivity.java

package com.android.twit;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import android.app.Activity;
import android.content.Context;
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.preference.PreferenceManager;
import android.util.Log;


public class PrepareRequestTokenActivity extends Activity {

final String TAG = getClass().getName();

private OAuthConsumer consumer;
private OAuthProvider provider;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        // CommonsHttpOAuthConsumer
        this.consumer = new CommonsHttpOAuthConsumer(
                ConstantsTwit.CONSUMER_KEY, ConstantsTwit.CONSUMER_SECRET);
        // this.provider = new
        // CommonsHttpOAuthProvider(Constants.REQUEST_URL,
        // Constants.ACCESS_URL, Constants.AUTHORIZE_URL);
        this.provider = new DefaultOAuthProvider(ConstantsTwit.REQUEST_URL,
                ConstantsTwit.ACCESS_URL, ConstantsTwit.AUTHORIZE_URL);
    } catch (Exception e) {
        Log.e(TAG, "Error creating consumer / provider", e);
    }

    Log.i(TAG, "Starting task to retrieve request token.");
    new OAuthRequestTokenTask(this, this.consumer, this.provider).execute();
}

/**
 * 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);
    Log.e("", "onNewIntent() is called...");
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    final Uri uri = intent.getData();
    if (uri != null
            && uri.getScheme().equals(ConstantsTwit.OAUTH_CALLBACK_SCHEME)) {
        Log.i(TAG, "Callback received : " + uri);
        Log.i(TAG, "Retrieving Access Token");
        new RetrieveAccessTokenTask(this, consumer, provider, prefs)
                .execute(uri);
        finish();
    }
}

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,
            // AndroidTwitterSample.class));

            executeAfterAccessTokenRetrieval();

            Log.e(TAG, "OAuth - Access Token Retrieved");

        } catch (Exception e) {
            Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
        }

        return null;
    }

    private void executeAfterAccessTokenRetrieval() {
        String msg = getIntent().getExtras().getString("tweet_msg");
        String path = getIntent().getExtras().getString("imagePath");
        try {
            TwitterUtils.sendTweet(prefs, msg, path);
        } catch (Exception e) {
            Log.e(TAG, "OAuth - Error sending to Twitter", e);
        }
    }
}

}

ConstantsTwit.java ConstantsTwit.java

package com.android.twit;

public class ConstantsTwit {

public static final String CONSUMER_KEY = "xxxxxxxxxxxxxxx";
public static final String CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

public static final String REQUEST_URL = "  https://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "https://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize";

public static final String OAUTH_CALLBACK_SCHEME = "x-test-oauth-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME
        + "://" + OAUTH_CALLBACK_HOST;

}

in AndroidManifest.xml 在AndroidManifest.xml中

<activity
        android:name="com.android.twit.PrepareRequestTokenActivity"
        android:configChanges="touchscreen|keyboard|keyboardHidden|navigation|orientation"
        android:excludeFromRecents="true"
        android:launchMode="singleTask"
        android:windowSoftInputMode="stateAlwaysHidden" >
        <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="callback"
                android:scheme="x-test-oauth-twitter" />
        </intent-filter>
    </activity>

TwitterUtils.java TwitterUtils.java

package com.android.twit;

import oauth.signpost.OAuth;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.app.Activity;
import android.content.SharedPreferences;
import android.widget.Toast;

public class TwitterUtils {

public static Activity tmp_Add_Daily_Mood;

public static boolean isAuthenticated(SharedPreferences prefs) {

    String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
    String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

    AccessToken a = new AccessToken(token, secret);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(ConstantsTwit.CONSUMER_KEY,
            ConstantsTwit.CONSUMER_SECRET);
    twitter.setOAuthAccessToken(a);

    try {
        twitter.getAccountSettings();
        return true;
    } catch (TwitterException e) {
        return false;
    }
}

public static void sendTweet(SharedPreferences prefs, String msg)
        throws Exception {
    String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
    String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

    AccessToken a = new AccessToken(token, secret);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(ConstantsTwit.CONSUMER_KEY,
            ConstantsTwit.CONSUMER_SECRET);
    twitter.setOAuthAccessToken(a);
    twitter.updateStatus(msg);
}


}

usage 用法

Intent i = new Intent(getApplicationContext(),
                    PrepareRequestTokenActivity.class);
i.putExtra("tweet_msg", getTweetMsg());         
startActivity(i);

Check out this...It may help you.. 看看这个...它可能对你有所帮助..

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

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