使用Twitter4j Android进行身份验证

时间:2014-03-20 10:23:33

标签: java android authentication twitter4j

我试图在使用twitter4j进行身份验证并在this tutorial上行走后发布推文。问题是登录按钮在必须打开身份验证页面时没有做任何事情。我无法找到原因。谢谢你的帮助。

MainActivity:

public class MainActivity extends Activity {
    // Constants

    static String TWITTER_CONSUMER_KEY = "my_api_key";
    static String TWITTER_CONSUMER_SECRET = "my_api_secret";   

    // Preference Constants
    static String PREFERENCE_NAME = "twitter_oauth";
    static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
    static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
    static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

    static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

    // Twitter oauth urls
    static final String URL_TWITTER_AUTH = "auth_url";
    static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
    static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

    // Login button
    Button btnLoginTwitter;
    // Update status button
    Button btnUpdateStatus;
    // Logout button
    Button btnLogoutTwitter;
    // EditText for update
    EditText txtUpdate;
    // lbl update
    TextView lblUpdate;
    TextView lblUserName;

    // Progress dialog
    ProgressDialog pDialog;

    // Twitter
    private static Twitter twitter;
    private static RequestToken requestToken;

    // Shared Preferences
    private static SharedPreferences mSharedPreferences;

    // Internet Connection detector
    private ConnectionDetector cd;

    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        cd = new ConnectionDetector(getApplicationContext());

        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }

        // Check if twitter keys are set
        if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
            // Internet Connection is not present
            alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
            // stop executing code by return
            return;
        }

        // All UI elements
        btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
        btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
        btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
        txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
        lblUpdate = (TextView) findViewById(R.id.lblUpdate);
        lblUserName = (TextView) findViewById(R.id.lblUserName);

        // Shared Preferences
        mSharedPreferences = getApplicationContext().getSharedPreferences(
                "MyPref", 0);

        /**
         * Twitter login button click event will call loginToTwitter() function
         * */
        btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Call login twitter function
                loginToTwitter();
            }
        });

        /**
         * Button click event to Update Status, will call updateTwitterStatus()
         * function
         * */
        btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Call update status function
                // Get the status from EditText
                String status = txtUpdate.getText().toString();

                // Check for blank text
                if (status.trim().length() > 0) {
                    // update status
                    new updateTwitterStatus().execute(status);
                } else {
                    // EditText is empty
                    Toast.makeText(getApplicationContext(),
                            "Please enter status message", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });

        /**
         * Button click event for logout from twitter
         * */
        btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Call logout twitter function
                logoutFromTwitter();
            }
        });

        /** This if conditions is tested once is
         * redirected from twitter page. Parse the uri to get oAuth
         * Verifier
         * */
        if (!isTwitterLoggedInAlready()) {
            Uri uri = getIntent().getData();
            if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
                // oAuth verifier
                String verifier = uri
                        .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

                try {
                    // Get the access token
                    AccessToken accessToken = twitter.getOAuthAccessToken(
                            requestToken, verifier);

                    // Shared Preferences
                    Editor e = mSharedPreferences.edit();

                    // After getting access token, access token secret
                    // store them in application preferences
                    e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                    e.putString(PREF_KEY_OAUTH_SECRET,
                            accessToken.getTokenSecret());
                    // Store login status - true
                    e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                    e.commit(); // save changes

                    Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

                    // Hide login button
                    btnLoginTwitter.setVisibility(View.GONE);

                    // Show Update Twitter
                    lblUpdate.setVisibility(View.VISIBLE);
                    txtUpdate.setVisibility(View.VISIBLE);
                    btnUpdateStatus.setVisibility(View.VISIBLE);
                    btnLogoutTwitter.setVisibility(View.VISIBLE);

                    // Getting user details from twitter
                    // For now i am getting his name only
                    long userID = accessToken.getUserId();
                    User user = twitter.showUser(userID);
                    String username = user.getName();

                    // Displaying in xml ui
                    lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
                } catch (Exception e) {
                    // Check log for login errors
                    Log.e("Twitter Login Error", "> " + e.getMessage());
                }
            }
        }

    }

    /**
     * Function to login twitter
     * */
    private void loginToTwitter() {
        // Check if already logged in
        if (!isTwitterLoggedInAlready()) {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
            Configuration configuration = builder.build();

            TwitterFactory factory = new TwitterFactory(configuration);
            twitter = factory.getInstance();

            try {
                requestToken = twitter
                        .getOAuthRequestToken(TWITTER_CALLBACK_URL);
                this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                        .parse(requestToken.getAuthenticationURL())));
            } catch (TwitterException e) {
                e.printStackTrace();
            }
        } else {
            // user already logged into twitter
            Toast.makeText(getApplicationContext(),
                    "Already Logged into twitter", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Function to update status
     * */
    class updateTwitterStatus extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Updating to twitter...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting Places JSON
         * */
        protected String doInBackground(String... args) {
            Log.d("Tweet Text", "> " + args[0]);
            String status = args[0];
            try {
                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
                builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

                // Access Token 
                String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
                // Access Token Secret
                String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

                AccessToken accessToken = new AccessToken(access_token, access_token_secret);
                Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

                // Update status
                twitter4j.Status response = twitter.updateStatus(status);

                Log.d("Status", "> " + response.getText());
            } catch (TwitterException e) {
                // Error in updating status
                Log.d("Twitter Update Error", e.getMessage());
            }
            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog and show
         * the data in UI Always use runOnUiThread(new Runnable()) to update UI
         * from background thread, otherwise you will get error
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Status tweeted successfully", Toast.LENGTH_SHORT)
                            .show();
                    // Clearing EditText field
                    txtUpdate.setText("");
                }
            });
        }

    }

    /**
     * Function to logout from twitter
     * It will just clear the application shared preferences
     * */
    private void logoutFromTwitter() {
        // Clear the shared preferences
        Editor e = mSharedPreferences.edit();
        e.remove(PREF_KEY_OAUTH_TOKEN);
        e.remove(PREF_KEY_OAUTH_SECRET);
        e.remove(PREF_KEY_TWITTER_LOGIN);
        e.commit();

        // After this take the appropriate action
        // I am showing the hiding/showing buttons again
        // You might not needed this code
        btnLogoutTwitter.setVisibility(View.GONE);
        btnUpdateStatus.setVisibility(View.GONE);
        txtUpdate.setVisibility(View.GONE);
        lblUpdate.setVisibility(View.GONE);
        lblUserName.setText("");
        lblUserName.setVisibility(View.GONE);

        btnLoginTwitter.setVisibility(View.VISIBLE);
    }

    /**
     * Check user already logged in your application using twitter Login flag is
     * fetched from Shared Preferences
     * */
    private boolean isTwitterLoggedInAlready() {
        // return twitter login status from Shared Preferences
        return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
    }

    protected void onResume() {
        super.onResume();
    }

}

错误日志:

03-20 12:12:56.779: E/AudioMTKHardware(8976): setParameters() still have param.size() = 1, remain param = "screen_state=off"
03-20 12:13:01.714: E/Looper(494): WARNING: The Looper class instance count has over a limit(100). There should be some leakage of Looper or HandlerThread.
03-20 12:13:01.715: E/Looper(494): Looper class instance count = 113
03-20 12:13:01.715: E/Looper(494): Current Thread Name: KeyguardWidgetPager Worker
03-20 12:13:05.991: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:13:05.991: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:13:05.997: E/CellLocation(976): create GsmCellLocation
03-20 12:13:06.014: E/CellLocation(976): create GsmCellLocation
03-20 12:13:06.468: E/wpa_supplicant(29010): Sorted scan results
03-20 12:13:06.468: E/wpa_supplicant(29010): 28:10:7b:94:c5:79 freq=2437 qual=0 noise=0 level=-78 flags=0x2b
03-20 12:13:06.468: E/wpa_supplicant(29010): IEs
03-20 12:13:06.468: E/wpa_supplicant(29010): 000854454e454b454349010882848b962430486c0301062a01042f010430140100000fac040100000fac040100000fac020c0032040c1218602d1a6c181bff000000000000000000000000000000000000000000003d1606000000000000000000000000000000000000000000dd7b0050f204104a00011010440001021041000100103b0001031047001076c42cdafbfc3780d3ea25f0dc470d6f1021000842726f6164636f6d1023000842726f6164636f6d1024000631323334353610420004313233341054000800060050f20400011011000a42726f6164636f6d4150100800020084103c000101dd090010180201f0040000dd180050f2020101800003a4000027a4000042435e0062322f00
03-20 12:13:06.468: E/wpa_supplicant(29010): Beacon IEs
03-20 12:13:06.468: E/wpa_supplicant(29010): 000854454e454b454349010882848b962430486c0301060504000100002a01002f010030140100000fac040100000fac040100000fac020c0032040c1218602d1a6c181bff000000000000000000000000000000000000000000003d1606000000000000000000000000000000000000000000dd0e0050f204104a0001101044000102dd090010180200f0040000dd180050f2020101800003a4000027a4000042435e0062322f00
03-20 12:13:06.468: E/wpa_supplicant(29010): f8:1a:67:b8:c4:be freq=2457 qual=0 noise=0 level=-87 flags=0xb
03-20 12:13:06.468: E/wpa_supplicant(29010): IEs
03-20 12:13:06.468: E/wpa_supplicant(29010): 001154544e45545f54504c494e4b5f43344245010882848b960c12182403010a2a010032043048606c2d1a6e181effff0000000000000000000000000000000000000000003d160a0000000000000000000000000000000000000000004a0e14000a00b400c8001400050019007f0101dd1a0050f20101000050f20202000050f2020050f20401000050f20230180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f00dd1e00904c336e181effff000000000000000000000000000000000000000000dd1a00904c340a000000000000000000000000000000000000000000dd0600e04c020160dda40050f204104a0001101044000102103b0001031047001063041253101920061228f81a67b8c4be1021001b5265616c74656b2053656d69636f6e647563746f7220436f72702e1023000752544c383637311024000d45562d323030362d30372d32371042000f3132333435363738393031323334371054000800060050f20400011011000f54502d4c494e4b2050726f647563741008000200061049000600372a000120
03-20 12:13:06.468: E/wpa_supplicant(29010): Beacon IEs
03-20 12:13:06.468: E/wpa_supplicant(29010): 001154544e45545f54504c494e4b5f43344245010882848b960c12182403010a0504000101002a010432043048606c2d1a6e181effff0000000000000000000000000000000000000000003d160a0000000000000000000000000000000000000000004a0e14000a00b400c8001400050019007f0101dd1a0050f20101000050f20202000050f2020050f20401000050f20230180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f00dd1e00904c336e181effff000000000000000000000000000000000000000000dd1a00904c340a000000000000000000000000000000000000000000dd0600e04c020160dd180050f204104a00011010440001021049000600372a000120
03-20 12:13:06.468: E/wpa_supplicant(29010): 64:66:b3:ed:de:26 freq=2472 qual=0 noise=0 level=-90 flags=0xb
03-20 12:13:06.468: E/wpa_supplicant(29010): IEs
03-20 12:13:06.469: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:13:06.469: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:13:06.470: E/wpa_supplicant(29010): 00074d757a65203335010882848b961224486c03010d2a010432040c1830602d1a6e1117ff000000010000000000000000000000000c00000000003d160d0700000000000000000000000000000000000000003e010030180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f004a0e14000a002c01c800140005001900dd07000c43040000000706545200010d10dd9d0050f204104a0001001044000102103b00010310470010bc329e001dd811b286016466b3edde261021001852616c696e6b20546563686e6f6c6f67792c20436f72702e1023001c52616c696e6b20576972656c6573732041636365737320506f696e74102400065254323836301042000831323334353637381054000800060050f20400011011000952616c696e6b415053100800020004103c000100
03-20 12:13:06.470: E/wpa_supplicant(29010): Beacon IEs
03-20 12:13:06.471: E/wpa_supplicant(29010): 00074d757a65203335010882848b961224486c03010d32040c1830600706545200010d143308200102030405060733082105060708090a0b050400010000dd270050f204104a000100104400010210470010bc329e001dd811b286016466b3edde26103c0001012a01042d1a6e1117ff000000010000000000000000000000000c00000000003d160d0700000000000000000000000000000000000000004a0e14000a002c01c80014000500190030180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f00dd07000c4304000000
03-20 12:13:06.483: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
03-20 12:13:06.483: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
03-20 12:13:06.483: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
03-20 12:14:06.019: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:14:06.019: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:14:06.026: E/CellLocation(976): create GsmCellLocation
03-20 12:14:06.042: E/CellLocation(976): create GsmCellLocation
03-20 12:14:06.506: E/wpa_supplicant(29010): Sorted scan results
03-20 12:14:06.506: E/wpa_supplicant(29010): 28:10:7b:94:c5:79 freq=2437 qual=0 noise=0 level=-84 flags=0x2b
03-20 12:14:06.506: E/wpa_supplicant(29010): IEs
03-20 12:14:06.506: E/wpa_supplicant(29010): 000854454e454b454349010882848b962430486c0301062a01042f010430140100000fac040100000fac040100000fac020c0032040c1218602d1a6c181bff000000000000000000000000000000000000000000003d1606000000000000000000000000000000000000000000dd7b0050f204104a00011010440001021041000100103b0001031047001076c42cdafbfc3780d3ea25f0dc470d6f1021000842726f6164636f6d1023000842726f6164636f6d1024000631323334353610420004313233341054000800060050f20400011011000a42726f6164636f6d4150100800020084103c000101dd090010180201f0040000dd180050f2020101800003a4000027a4000042435e0062322f00
03-20 12:14:06.506: E/wpa_supplicant(29010): Beacon IEs
03-20 12:14:06.506: E/wpa_supplicant(29010): 000854454e454b454349010882848b962430486c0301060504000100002a01002f010030140100000fac040100000fac040100000fac020c0032040c1218602d1a6c181bff000000000000000000000000000000000000000000003d1606000000000000000000000000000000000000000000dd0e0050f204104a0001101044000102dd090010180200f0040000dd180050f2020101800003a4000027a4000042435e0062322f00
03-20 12:14:06.506: E/wpa_supplicant(29010): 64:66:b3:ed:de:26 freq=2472 qual=0 noise=0 level=-89 flags=0xb
03-20 12:14:06.506: E/wpa_supplicant(29010): IEs
03-20 12:14:06.506: E/wpa_supplicant(29010): 00074d757a65203335010882848b961224486c03010d2a010432040c1830602d1a6e1117ff000000010000000000000000000000000c00000000003d160d0700000000000000000000000000000000000000003e010030180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f004a0e14000a002c01c800140005001900dd07000c43040000000706545200010d10dd9d0050f204104a0001001044000102103b00010310470010bc329e001dd811b286016466b3edde261021001852616c696e6b20546563686e6f6c6f67792c20436f72702e1023001c52616c696e6b20576972656c6573732041636365737320506f696e74102400065254323836301042000831323334353637381054000800060050f20400011011000952616c696e6b415053100800020004103c000100
03-20 12:14:06.506: E/wpa_supplicant(29010): Beacon IEs
03-20 12:14:06.506: E/wpa_supplicant(29010): 00074d757a65203335010882848b961224486c03010d32040c1830600706545200010d143308200102030405060733082105060708090a0b050400010000dd270050f204104a000100104400010210470010bc329e001dd811b286016466b3edde26103c0001012a01042d1a6e1117ff000000010000000000000000000000000c00000000003d160d0700000000000000000000000000000000000000004a0e14000a002c01c80014000500190030180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f00dd07000c4304000000
03-20 12:14:06.506: E/wpa_supplicant(29010): 00:27:22:82:e8:21 freq=2437 qual=0 noise=0 level=-93 flags=0xb
03-20 12:14:06.506: E/wpa_supplicant(29010): IEs
03-20 12:14:06.507: E/wpa_supplicant(29010): 00066b6174322d31010882848b960c1218240301060504000100002a0100dd26000c42000000011e000000001f660902ff0f55424e540000000000000000000000000000000032043048606cdd180050f202010182000364000027a4000041435e0061322f00dd1e00904c334c101bffff0000000000000000000000000000000000000000002d1a4c101bffff000000000000000000000000000000000000000000dd1a00904c3406001b000000000000000000000000000000000000003d1606001b00000000000000000000000000000000000000dd0900037f01010000ff7fdd0a00037f04010002004000dd0e00156d000000010212e002021200
03-20 12:14:06.507: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:14:06.507: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:14:06.518: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
03-20 12:14:06.518: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
03-20 12:14:06.518: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1

编辑:

将jar文件更新到最新版本(Twitter4j 4.0.1)之后,没有更多日志错误,但只有警告和按钮仍无法正常工作。 Here is new error log.

0 个答案:

没有答案