Twitter Api仅在包含它的活动是主要活动时才有效

时间:2013-08-02 17:41:34

标签: android twitter android-activity main

现在这是我的清单文件:

    <activity
        android:name="com.pyr.Activity_Login"
        android:label="@string/manifest_label_login"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity 
        android:name="com.pyr.Activity_LinkSocialNetwork"
        android:label="@string/manifest_label_linkSocialNetwork"
        android:screenOrientation="portrait" 
        android:launchMode="singleInstance">
        <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="mgl" android:host="mamor" />
        </intent-filter>
    </activity>

这就是我的logcat陷入困境的地方:

 08-02 19:30:50.429: I/MGL(29080): Retrieving request token from twitter servers
 08-02 19:30:50.749: D/dalvikvm(29080): GC_CONCURRENT freed 249K, 4% free 9020K/9351K,     paused 9ms+3ms
 08-02 19:30:51.789: I/MGL(29080): Popping a browser with the authorize URL: https://api.twitter.com/oauth/authorize?oauth_token='valid token'
 08-02 19:30:51.919: D/OpenGLRenderer(29080): Flushing caches (mode 1)
 08-02 19:30:52.019: D/OpenGLRenderer(29080): Flushing caches (mode 0)

当我更改清单文件时,我写了Activity_LinkSocialNetwork是主要和启动器活动:

    <activity
        android:name="com.pyr.Activity_Login"
        android:label="@string/manifest_label_login"
        android:screenOrientation="portrait">
    </activity>

    <activity 
        android:name="com.pyr.Activity_LinkSocialNetwork"
        android:label="@string/manifest_label_linkSocialNetwork"
        android:screenOrientation="portrait" 
        android:launchMode="singleInstance" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <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="mgl" android:host="mamor" />
        </intent-filter>
    </activity>

Logcat说:

 08-02 19:30:05.359: I/MGL(28609): Retrieving request token from twitter servers
 08-02 19:30:07.749: D/dalvikvm(28609): GC_CONCURRENT freed 291K, 4% free 8980K/9351K, paused 2ms+3ms
 08-02 19:30:07.829: I/MGL(28609): Popping a browser with the authorize URL : https://api.twitter.com/oauth/authorize?oauth_token='valid token'
 08-02 19:30:08.079: D/OpenGLRenderer(28609): Flushing caches (mode 1)
 08-02 19:30:08.249: D/OpenGLRenderer(28609): Flushing caches (mode 0)
 08-02 19:30:18.579: I/MGL(28609): Callback received : mgl://mamor?oauth_token='valid token'&oauth_verifier='valid token'
 08-02 19:30:18.779: I/MGL(28609): Obtained oAuth Verifier: 'valid token'
 08-02 19:30:20.419: D/dalvikvm(28609): GC_CONCURRENT freed 374K, 6% free 9050K/9543K, paused 3ms+2ms
 08-02 19:30:20.429: I/MGL(28609): OAuth - Access Token Retrieved

一切正常。我不明白twitter API和主要活动之间的关系。也许我做错了什么,所以我需要有人来解释我。

编辑 - &gt;活动代码

Activity_LinkSocialNetwork

public class Activity_LinkSocialNetwork extends Activity{

private static CommonsHttpOAuthConsumer httpOauthConsumer;
private static OAuthProvider httpOauthprovider;
private Button btnOAuth;

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linksocialnetwork);

        this.btnOAuth = (Button)findViewById(R.id.btnOAuth);

        this.btnOAuth.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        autorizarApp();
                Log.i("MGL", "depues de mandar");
                }
        });
}


/**
 * 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);
        final Uri uri = intent.getData();
        SharedPreferences preferencias = this.getSharedPreferences("TwitterPrefs", MODE_PRIVATE);

        if (uri != null && uri.toString().indexOf(TwitterData.CALLBACK_URL) != -1) {
                Log.i("MGL", "Callback received : " + uri);

                new RetrieveAccessTokenTask(this, getConsumer(), getProvider(),
                                preferencias).execute(uri);
        }
}

protected void autorizarApp() {
        try {

                getProvider().setOAuth10a(true);
                // retrieve the request token
                new OAuthRequestTokenTask(this, getConsumer(), getProvider()).execute();

        } catch (Exception e) {

        }               
}


/**
 * @return the provider (initialize on the first call)
 */
public static OAuthProvider getProvider() {
        if (httpOauthprovider == null) {
                httpOauthprovider = new DefaultOAuthProvider(
                                TwitterData.REQUEST_URL, TwitterData.ACCESS_URL,
                                TwitterData.AUTHORIZE_URL);
                httpOauthprovider.setOAuth10a(true);
        }
        return httpOauthprovider;
}

/**
 * @param context
 *            the context
 * @return the consumer (initialize on the first call)
 */
public static CommonsHttpOAuthConsumer getConsumer() {
        if (httpOauthConsumer == null) {
                httpOauthConsumer = new CommonsHttpOAuthConsumer(
                                TwitterData.CONSUMER_KEY, TwitterData.CONSUMER_SECRET);
        }
        return httpOauthConsumer;
}
}

Activity_Login

public class Activity_Login extends Activity{

private EditText txtEmailLogin;
private EditText txtPasswordLogin;
private Button btnLogin;
private ProgressBar progressLogin;
private Data_Access oData = new Data_Access();
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    txtEmailLogin = (EditText) findViewById(R.id.txtEmailLogin);
    txtPasswordLogin = (EditText) findViewById(R.id.txtPasswordLogin);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    progressLogin = (ProgressBar) findViewById(R.id.progressLogin); 
    context = this.getApplicationContext();

    btnLogin.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            new asyncLogin().execute();
        }
    });
}

 //AYNSC TASK CLASSES
private class asyncLogin extends AsyncTask<Void, Void, Boolean>{

    JSONArray jSONData;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        progressLogin.setVisibility(View.VISIBLE);
    }

    @Override
    protected Boolean doInBackground(Void... params) {

        try 
        {   
            //Params
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("emailUser", txtEmailLogin.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("passwordUser", txtPasswordLogin.getText().toString()));

            jSONData = new JSONArray(oData.getData("getUserLogin", nameValuePairs));
            return true;
        } 
        catch (JSONException e) 
        {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean result) {

        if(result){
            try 
            {   
                for (int i = 0; i < jSONData.length(); i++) { 

                    JSONObject row = jSONData.getJSONObject(i);

                    if(i == 0){

                        if(row.getString("error").equals("1")){
                            Log.v("Error", row.getString("msg"));
                            break;
                        }

                    }else{

                        SharedPreferences prefs = getSharedPreferences("userPrefs", MODE_PRIVATE);

                        final Editor edit = prefs.edit();
                        edit.putString("idUser", row.getString("idUser"));
                        edit.commit();

                        Intent intent = new Intent(context, Activity_LinkSocialNetwork.class)
                        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                | Intent.FLAG_ACTIVITY_NO_HISTORY
                                | Intent.FLAG_FROM_BACKGROUND);

                        context.startActivity(intent);
                    }
                }

                progressLogin.setVisibility(View.VISIBLE);

            } 
            catch (JSONException e) 
            {
                e.printStackTrace();
            }
        }
    }
}

}

编辑2 - &gt; OAUTH令牌请求类

AsyncTask OAuthRequestTokenTask

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

private static final String TAG = "MGL";
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 twitter servers");
                final String url = provider.retrieveRequestToken(consumer,
                                TwitterData.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;
}

}

AsyncTask RetrieveAccessTokenTask

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

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 Boolean doInBackground(Uri... params) {
        final Uri uri = params[0];
        final String oauth_verifier = uri
                        .getQueryParameter(OAuth.OAUTH_VERIFIER);

        try {
                Log.i("MGL","Obtained oAuth Verifier: " + oauth_verifier);

                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, "");
                if( secret == null || token == null || secret.equals("") || token.equals("") ) return false;
                consumer.setTokenWithSecret(token, secret);
                context.startActivity(new Intent(context, Activity_LinkSocialNetwork.class));

                Log.i("MGL", "OAuth - Access Token Retrieved");

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

        return true;
}

protected void onPostExecute(Boolean result) {

if(result){

    Toast.makeText(this.context,
                "Acceso a twitter conseguido!",
            Toast.LENGTH_SHORT).show();
}else{
        Toast.makeText(this.context,
                "Acceso a twitter NO conseguido! :(",
            Toast.LENGTH_SHORT).show();
}
}                       
}

0 个答案:

没有答案