将Twitter4j v3.0.3集成到Android应用程序 - 获取TimeLine和Post Tweet [Working]

时间:2013-07-02 12:29:48

标签: android twitter twitter4j

Android 2.3.3

重要提示:::我很擅长整合Twitter和facebook的东西。我需要将新的twitter4j集成到我的应用程序中,偶然发现了几个例子来解决问题。我的要求是从时间线上获取推文。但是,下面的示例还包含如何从应用程序更新推文。

Note 2 :::我使用了herehere中的示例。所有信用都归功于这些网站的人。我做了一些改动,但它确实有效。

代码几乎是自我解释,如果您需要任何其他说明,请访问上面的网站。


这就是我所做的:

  1. 在Twitter上注册了Dev帐户并获得了#34;消费者密钥"和#34;消费者秘密"。在代码中找到消费者密钥和消费者密钥的常量时替换它们。

  2. here下载twitter4j-3.0.3.zip

  3. 提取zip文件并从twitter-3.0.3-> lib添加库。我在测试集成时添加了所有库。您可能希望添加所需的库。

  4. 右键点击项目 - >属性 - > Java构建路径 - >库 - >添加Jars。转到项目中的lib文件夹并添加所有库。


  5. 请按照以下步骤操作,您将把应用程序与twitter集成。

    为了使用该应用程序在Twitter上发布推文,我使用了here中的示例。 为了从twitter获取时间表,我使用了here中的示例。


    代码:

    的AndroidManifest.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.twitt4jintegrationdemo"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />
    
        <!-- Permission - Internet Connect -->
        <uses-permission android:name="android.permission.INTERNET" />
    
        <!-- Network State Permissions -->
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.example.twitt4jintegrationdemo.MainActivity"
                android:label="@string/app_name" >
                <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:host="t4jsample"
                        android:scheme="oauth" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
    

    ConnectionDetector.java

    package com.example.twitt4jintegrationdemo;
    
    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    
    public class ConnectionDetector {
    
        private Context _context;
    
        public ConnectionDetector(Context context){
            this._context = context;
        }
    
        /**
         * Checking for all possible internet providers
         * **/
        public boolean isConnectingToInternet(){
            ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
              if (connectivity != null)
              {
                  NetworkInfo[] info = connectivity.getAllNetworkInfo();
                  if (info != null)
                      for (int i = 0; i < info.length; i++)
                          if (info[i].getState() == NetworkInfo.State.CONNECTED)
                          {
                              return true;
                          }
    
              }
              return false;
        }
    }
    

    AlertDialogManager.java

    package com.example.twitt4jintegrationdemo;
    
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    
    public class AlertDialogManager {
        /**
         * Function to display simple Alert Dialog
         * 
         * @param context
         *            - application context
         * @param title
         *            - alert dialog title
         * @param message
         *            - alert message
         * @param status
         *            - success/failure (used to set icon) - pass null if you don't
         *            want icon
         * */
    
        public void showAlertDialog(Context context, String title, String message,
                Boolean status) {
            AlertDialog alertDialog = new AlertDialog.Builder(context).create();
    
            // Setting Dialog Title
            alertDialog.setTitle(title);
    
            // Setting Dialog Message
            alertDialog.setMessage(message);
    
            if (status != null)
    
                // Setting OK Button
                alertDialog.setButton(0, "OK",
                        new DialogInterface.OnClickListener() {
    
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
    
                            }
                        });
    
            alertDialog.show();
        }
    }
    

    MainActivity.java

    package com.example.twitt4jintegrationdemo;
    
    import java.util.List;
    
    import com.example.twitt4jintegrationdemo.R;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    
    import twitter4j.Twitter;
    import twitter4j.TwitterException;
    import twitter4j.TwitterFactory;
    import twitter4j.User;
    import twitter4j.auth.AccessToken;
    import twitter4j.auth.RequestToken;
    import twitter4j.conf.Configuration;
    import twitter4j.conf.ConfigurationBuilder;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.content.pm.ActivityInfo;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.text.Html;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
        // Constants
        /**
         * Register your here app https://dev.twitter.com/apps/new and get your
         * consumer key and secret
         * */
        static String TWITTER_CONSUMER_KEY = "o4YaT3H0SgmjQFSkGJy1A";
        static String TWITTER_CONSUMER_SECRET = "uxCIVsaPSsvckIBpSfZCLYGli0jHus4xMkE5sgk";
    
        // 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;
    
        Button btnGetTimeLine;
    
        // 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);
    
            btnGetTimeLine = (Button) findViewById(R.id.btnGetTimeLine);
    
            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();
                }
            });
    
            /**
             * Button click event for getting timeline from twitter *
             **/
            btnGetTimeLine.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // call getTimeLine function
                    new getTimeLine().execute();
                }
            });
    
            /**
             * 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);
    
                        btnGetTimeLine.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
            btnGetTimeLine.setVisibility(View.GONE);
            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();
        }
    
        /**
         * Function to get timeline
         * */
        class getTimeLine extends AsyncTask<Void, Void, String> {
    
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setMessage("Getting Timeline from Twitter...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }
    
            /**
             * getting Places JSON
             * */
            protected String doInBackground(Void... args) {
    
                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);
    
    
                    //Twitter twitter = new TwitterFactory().getInstance();
                    User user = twitter.verifyCredentials();
                    List<twitter4j.Status> statuses = twitter.getHomeTimeline();
                    System.out.println("Showing @" + user.getScreenName()
                            + "'s home timeline.");
                    for (twitter4j.Status status : statuses) {
                        Log.d("Twitter","@" + status.getUser().getScreenName()
                                + " - " + status.getText());
                    }
    
                } catch (TwitterException e) {
                    // Error in updating status
                    Log.d("Twitter Update Error", e.getMessage());
                }
                return null;
            }
    
            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(),
                                "Retrieving TimeLine Done..", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }
    
        }
    
    }
    

    如果您有任何疑问,您可以参考这个问题并提出疑问,SO的专家可以回答您的疑问。

    希望这有帮助!!!

    ...谢谢


    图片:

    enter image description here

    enter image description here

1 个答案:

答案 0 :(得分:0)

问题本身就有答案。我正在添加这个答案,只是为了结束这个问题。请查看问题,了解有关如何集成的正确工作代码。