无法连接到应用内的Twitter

时间:2014-11-19 23:06:00

标签: android twitter

我有一个启动页面,可以为用户提供社交登录。在设置活动中,如果用户使用他们的电子邮件地址登录,则用户可以连接到Twitter。

我正在使用以下代码在启动页面上记录用户,并且我在设置活动中使用相同的代码,如果用户点击“与Twitter连接”,则将用户登录到Twitter。

我的问题是,一旦我授权应用程序使用Twitter,它就会打开Splash页面而不是设置活动,因此无法对用户进行身份验证。我100%确定我没有启动应该打开启动活动的意图。

致电startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));后 Twitter认证网站出现,当我点击允许活动重新加载,但Splash活动重新加载。当我启动应用程序时,启动是打开的,但我可以解决这个问题吗? (登录启动页面时,它显然工作正常,问题是为什么一旦从内部活动验证用户,它就会打开启动页面?)

private static Twitter twitter;
    private static RequestToken requestToken;
    private static SharedPreferences mSharedPreferences;
    private AccessToken accessToken;
    User twuser;

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

settings_rl_twitter.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.i("Settings", "Clicked on Connect/Disconnect to Twitter");
                if (isTwitterLoggedInAlready()) {
                    new disconnectTwitter().execute();
                 } else {
                     connectTwitter();
                 }

            }
        });

        private boolean isTwitterLoggedInAlready() {
            return mSharedPreferences.getString(TwitterConst.PREF_KEY_TOKEN, null) != null;
        }

        private void connectTwitter() {
            Log.i("Twitter", "connectTwitter()");
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.setOAuthConsumerKey(TwitterConst.CONSUMER_KEY);
            configurationBuilder.setOAuthConsumerSecret(TwitterConst.CONSUMER_SECRET);
            Configuration configuration = configurationBuilder.build();
            twitter = new TwitterFactory(configuration).getInstance();

            Thread thread = new Thread(new Runnable(){
                @Override
                public void run() {
                    try {
                        requestToken = twitter.getOAuthRequestToken(TwitterConst.CALLBACK_URL);
                        Log.i("Twitter connectTwitter", "Please authorize this app!");
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
                    } catch (TwitterException e) {
                        e.printStackTrace();
                        Log.i("Twitter connectTwitter", e.getMessage() + "");
                    }
                }
             });
            thread.start();   
        }

        public class Connect_Twitter extends AsyncTask<String, Void, List<String>> {

            @Override
            protected void onPostExecute(List<String> result) {     
                Log.i("tw_userid", result.get(0) + "");
                Log.i("Lekerve name", result.get(1) + "");
                Log.i("photo", result.get(2) + "");


                new twitterSignupAsyncTask().execute(result.get(0), result.get(1), result.get(2), session_userid); 
            }

            @Override
            protected void onPreExecute() {
                LIST2.clear();
            }

            @Override
            protected List<String> doInBackground(String... params) {

                try {
                    accessToken = twitter.getOAuthAccessToken(requestToken, params[0]); 
                    Log.i("Settings Twitter OAuth Token1", "> " + accessToken.getToken());

                    Editor e = mSharedPreferences.edit();
                    e.putString(TwitterConst.PREF_KEY_TOKEN, accessToken.getToken()); 
                    e.putString(TwitterConst.PREF_KEY_SECRET, accessToken.getTokenSecret()); 
                    e.commit();

                    long userID = accessToken.getUserId();
                    Log.i("Settings Twitter userID", String.valueOf(userID) + "");
                    User user = twitter.showUser(userID);

                    Log.i("Settings User userid", String.valueOf(userID) + "");
                    Log.i("Settings User name", user.getName() + ""); 
                    Log.i("Settings User photo", user.getProfileImageURL() + "");
                    String country = "";
                    if (getUserCountry(SettingsActivity.this) != null && !getUserCountry(SettingsActivity.this).equals("")) {
                        Locale loc = new Locale("",getUserCountry(SettingsActivity.this));
                        country = loc.getDisplayCountry();
                    } else {
                        country = "";
                    }

                    Log.i("Settings  User country", country + ""); 
                    twitter_username = user.getName();

                    LIST2.add(String.valueOf(userID));
                    LIST2.add(user.getName());
                    //LIST2.add(user.getScreenName());
                    LIST2.add(user.getProfileImageURL());
                    LIST2.add(country);

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

                return LIST2;
            }
        }


        public class twitterSignupAsyncTask extends AsyncTask<String, Void, ArrayList<String>> {

            @Override
            protected void onPostExecute(ArrayList<String> result) {

                if (result.size() > 0) {

                    //mentsuk el a session_userid-t azert, hogy a kovetkezo app megnyitaskor ismerjuk
                    Editor e = mSharedPreferences.edit();
                    e.putString(TwitterConst.LASTID, result.get(0));
                    e.commit();

                    Log.i("TWITTER CONNECT RESULT POST", result.get(0));
                } else {
                    Log.i("TWITTER CONNECT RESULT POST", "FAIL");
                }

                settings_connecttw_text.setText("Connected to " + result.get(1));

            }

            @Override
            protected void onPreExecute() { 
                LIST.clear();
            }

            @Override
            protected ArrayList<String> doInBackground(String... params) {

                try {

                    Log.i("At tw_id", params[0].toString() + "");
                    Log.i("At name", params[1] + "");
                    Log.i("At photo", params[2] + "");
                    Log.i("At session_userid", params[3] + "");

                    array_user = new ArrayList<NameValuePair>();
                    array_user.add(new BasicNameValuePair("tw_userid", params[0]));
                    array_user.add(new BasicNameValuePair("name", params[1]));
                    array_user.add(new BasicNameValuePair("tw_photo", params[2]));
                    array_user.add(new BasicNameValuePair("userid", params[3]));

                    JSONParser jsonParser; jsonParser = new JSONParser();
                    JSONObject json = jsonParser.makeHttpRequest(connect_twitter, "POST", array_user);

                    try {
                        int success = json.getInt("success");
                        Log.d("success", "" + success);
                        if (success == 1) {
                            Log.d("SIGNUP", "success");
                        } else {
                            Log.d("SIGNUP", "fail");
                        }
                        LIST.add(String.valueOf(success));
                    }catch(JSONException e){
                        Log.e("log_tag", "Error parsing data "+e.toString());
                    }       
                    LIST.add(params[1]);

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

                return LIST;
            }

        }

}

1 个答案:

答案 0 :(得分:-1)

这就是我所做的。

  1. 在致电SettingsActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));之前,我将当前活动保存在Sharedpreferences
  2. 当启动启动活动时(每次打开应用程序时打开的主要活动)我在Sharedpreferences中检查此变量,如果它是真的,那么我打开SettingsActivity并发送带有intent的验证程序。
  3. 现在,在SettingsActivity中,您可以轻松使用此验证程序登录并获取用户数据。
  4. SplashActivity:

    if (!isTwitterLoggedInAlready()) {
    boolean fromSettingsActivity = mSharedPreferences2.getBoolean(TwitterConst.FROM_SETTINGS, false);
    Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(TwitterConst.CALLBACK_URL)) {
            final String verifier = uri.getQueryParameter(TwitterConst.IEXTRA_OAUTH_VERIFIER);
            if (fromSettingsActivity) {
               Intent intent = new Intent(Activity_Splash.this, SettingsActivity.class);
               intent.putExtra("verifier", verifier);
               startActivity(intent);
               finish();
               return;
            } else {    
               new Connect_Twitter().execute(verifier);
            }
        }
    }
    

    SettingsActivity:

    Intent iin = getIntent();
    Bundle extras = iin.getExtras();
    if(extras != null) {
        String verifier = extras.getString("verifier");
        new Connect_Twitter().execute(verifier);
    }
    

    点击BACK:

    时,不要忘记重置Sharedpreferences值
    @Override
    public void onBackPressed() {
        mSharedPreferences2 = getSharedPreferences(TwitterConst.FROM_SETTINGS, MODE_PRIVATE);
        SharedPreferences.Editor e = mSharedPreferences2.edit();
        e.remove(TwitterConst.FROM_SETTINGS);
        e.commit();
        super.onBackPressed();    
    }
    

    还有一件事

    使用当前意图,应用程序再次打开SettingsActivity,因此您需要单击BACK两次。这是Twitter登录的默认行为。要防止这种情况,请使用以下意图:

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(requestToken.getAuthenticationURL()));
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();