web-dev-qa-db-fra.com

Android Intégration Twitter avec oauth et Twitter4j

Je veux intégrer Twitter dans une Android et j'ai trouvé de nombreux tutoriels. J'en ai implémenté 2. Mais après avoir implémenté, lors de l'exécution de l'application, j'ai appris qu'ils utilisent une ancienne version de Twitter4J bibliothèque.

Bien que de nombreux autres didacticiels soient disponibles, mais aucun n'est le dernier one.i.e. juste 2-3 mois de plus. J'ai besoin d'un tutoriel ou d'un exemple utilisant la dernière Twitter4J version de la bibliothèque qui est Twitter4j-core-3.0. .

Mon objectif principal est de permettre à l'utilisateur de publier tweets sur son compte. Mais encore une fois, si l'utilisateur n'est pas connecté, je dois d'abord demander des informations d'identification. De plus, si l'utilisateur clique sur le bouton logout, j'ai besoin d'un moyen de déconnecter l'utilisateur.

17
Geek

J'ai résolu le problème. J'ai apporté des modifications au code que j'ai trouvé dans un tutoriel pour le faire fonctionner. Copie du code entier ici. Remplacez simplement par votre ConsumerKey et ConsumerSecret.

Vous devez ajouter la bibliothèque Twitter4j au dossier libs de votre projet.

AndroidManifest.xml:

<manifest xmlns:Android="http://schemas.Android.com/apk/res/Android"
    package="com.androidhive.twitterconnect"
    Android:versionCode="1"
    Android:versionName="1.0" >

    <uses-sdk
        Android:minSdkVersion="14"
        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=".MainActivity"
            Android:label="@string/title_activity_main" >
            <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>

MainActivity.Java:

package com.androidhive.twitterconnect;

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 com.androidhive.twitterconnect.R;
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 = "PutYourConsumerKeyHere"; // place your cosumer key here
    static String Twitter_CONSUMER_SECRET = "PutYourConsumerSecretHere"; // place your consumer secret here

    // 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;
    private AccessToken accessToken;

    // 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
                final String verifier = uri
                        .getQueryParameter(URL_Twitter_OAUTH_VERIFIER);

                try {

                    Thread thread = new Thread(new Runnable(){
                        @Override
                        public void run() {
                            try {

                                // Get the access token
                                MainActivity.this.accessToken = Twitter.getOAuthAccessToken(
                                        requestToken, verifier);

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

                    // 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());
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 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();


                Thread thread = new Thread(new Runnable(){
                    @Override
                    public void run() {
                        try {

                            requestToken = Twitter
                                    .getOAuthRequestToken(Twitter_CALLBACK_URL);
                            MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                                    .parse(requestToken.getAuthenticationURL())));

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                thread.start();         
        } 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());
                e.printStackTrace();
            }
            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();
    }

}

AlertDialogManager.Java:

package com.androidhive.twitterconnect;

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 alert dialog icon
            alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
}

ConnectionDetector.Java:

package com.androidhive.twitterconnect;

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;
    }
}

C'est code d'origine par Ravi Tamada. Les modifications que j'ai apportées sont dans MainActivity.Java et AndroidManifest.xml fichiers uniquement.

29
Geek

J'ai trouvé un bon exemple qui fonctionne bien avec Twitter4j 3.0.3 sur Android. D'autres ne fonctionnent pas. http://hintdesk.com/how-to-Tweet-in-Twitter-within-Android-client/

9
Vince Yuan

Ceci est l'exemple de travail de mon code, j'utilise Twitter4j et vous n'avez pas besoin de définir d'intention dans le manifeste car j'utilise Webview au lieu du navigateur.

Placez votre clé de consommateur et secrète et vous devriez être prêt à partir

package com.example.mysituationtwittertest;

import Twitter4j.Twitter;
import Twitter4j.TwitterException;
import Twitter4j.TwitterFactory;
import Twitter4j.auth.AccessToken;
import Twitter4j.auth.RequestToken;
import Twitter4j.conf.Configuration;
import Twitter4j.conf.ConfigurationBuilder;
import Android.app.Activity;
import Android.content.SharedPreferences;
import Android.content.SharedPreferences.Editor;
import Android.net.Uri;
import Android.os.AsyncTask;
import Android.os.Bundle;
import Android.util.Log;
import Android.view.View;
import Android.webkit.WebView;
import Android.webkit.WebViewClient;
import Android.widget.Button;
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 = "XXXXXXXXXXXXXXXXXXX"; // place your
                                                                // cosumer
                                                                // key here
static String Twitter_CONSUMER_SECRET = "XXXXXXXXXXXXXXXX"; // place
                                                                                    // your
                                                                                    // consumer
                                                                                    // secret
                                                                                    // here

// 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://youdare";

// 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 btnShareTwitter;

WebView myWebView;

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

// Shared Preferences
private static SharedPreferences mSharedPreferences;

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

    // All UI elements
    btnShareTwitter = (Button) findViewById(R.id.btnShareTwitter);
    myWebView = (WebView) findViewById(R.id.webView1);

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            if (url != null && url.startsWith(Twitter_CALLBACK_URL))
                new AfterLoginTask().execute(url);
            else
                webView.loadUrl(url);
            return true;
        }
    });

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

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

        @Override
        public void onClick(View arg0) {
            // Call login Twitter function
            new LoginTask().execute();
        }
    });

}

/**
 * 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);
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    else {
        // user already logged into Twitter
        Toast.makeText(getApplicationContext(),
                "Already Logged into Twitter", Toast.LENGTH_LONG).show();
    }
}

/**
 * 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);
}

public void handleTwitterCallback(String url) {

    Uri uri = Uri.parse(url);

    // oAuth verifier
    final String verifier = uri
            .getQueryParameter(URL_Twitter_OAUTH_VERIFIER);

    try {

        // Get the access token
        MainActivity.this.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());

        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("XXXXXXXXXXXXXXXXX");

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

class LoginTask extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO Auto-generated method stub
        loginToTwitter();
        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub

        myWebView.loadUrl(requestToken.getAuthenticationURL());
        myWebView.setVisibility(View.VISIBLE);
        myWebView.requestFocus(View.FOCUS_DOWN);

    }

}

class AfterLoginTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        myWebView.clearHistory();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        // TODO Auto-generated method stub
        handleTwitterCallback(params[0]);
        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        myWebView.setVisibility(View.GONE);
        Toast.makeText(MainActivity.this, "Tweet Successful",
                Toast.LENGTH_SHORT).show();

    }

}

@Override
public void onBackPressed() {
    if (myWebView.getVisibility() == View.VISIBLE) {
        if (myWebView.canGoBack()) {
            myWebView.goBack();
            return;
        } else {
            myWebView.setVisibility(View.GONE);
            return;
        }
    }
    super.onBackPressed();
}

}
4
Ravi

Pour illustrer mon commentaire ci-dessus, voici ma dernière classe de travail MainActivity. Assez similaire au code ci-dessus, les différences sont les suivantes:

  • la classe interne OAuthAccessTokenTask, qui comprend la récupération du jeton Oauth et les informations utilisateur
  • son rappel onRequestTokenRetrieved(Exception)

Notez également que pour que cela fonctionne, vous devez déclarer une URL de rappel dans les paramètres de votre application Twitter, même fausse. Il m'a fallu quelques heures pour comprendre comment cela fonctionne.

Lorsque vous consultez la documentation Twitter4j, les premiers morceaux de code font référence à un code PIN que vous devez obtenir à partir d'une page Web d'autorisation. C'est ce qui se produit lorsqu'aucune URL de rappel n'est définie dans votre application. Elle s'appelle PIN authentification basée et vous ne voulez pas l'utiliser sur un mobile :)

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 = "PutYourConsumerKeyHere"; // place your cosumer key here
    static String Twitter_CONSUMER_SECRET = "PutYourConsumerSecretHere"; // place your consumer secret here

    // 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;
    private AccessToken accessToken;
    private User user;

    // 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);
                new OAuthAccessTokenTask().execute(verifier);
            }
        }

    }

     private class OAuthAccessTokenTask extends AsyncTask<String, Void, Exception>
     {
        @Override
        protected Exception doInBackground(String... params) {
            Exception toReturn = null;

            try {
                accessToken = Twitter.getOAuthAccessToken(requestToken, params[0]);
                user = Twitter.showUser(accessToken.getUserId());

            }
            catch(TwitterException e) {
                Log.e(MainActivity.class.getName(), "TwitterError: " + e.getErrorMessage());
                toReturn = e;
            }
            catch(Exception e) {
                Log.e(MainActivity.class.getName(), "Error: " + e.getMessage());
                toReturn = e;
            }

            return toReturn;
        }

        @Override
        protected void onPostExecute(Exception exception) {
            onRequestTokenRetrieved(exception);
        }
     }

     private void onRequestTokenRetrieved(Exception result) {

         if (result != null) {
             Toast.makeText(
                     this, 
                     result.getMessage(), 
                     Toast.LENGTH_LONG
                     ).show();
         }

         else {
             try {
                 // Shared Preferences
                 Editor editor = mSharedPreferences.edit();

                 // After getting access token, access token secret
                 // store them in application preferences
                 editor.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                 editor.putString(PREF_KEY_OAUTH_SECRET,
                         accessToken.getTokenSecret());
                 // Store login status - true
                 editor.putBoolean(PREF_KEY_Twitter_LOGIN, true);
                 editor.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
                 String username = user.getName();

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

    /**
     * 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();


                Thread thread = new Thread(new Runnable(){
                    @Override
                    public void run() {
                        try {
                            requestToken = Twitter.getOAuthRequestToken(Twitter_CALLBACK_URL);
                            MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));

                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "Already Logged into Twitter", Toast.LENGTH_LONG).show();
                        }
                    }
                });
                thread.start();         
        } 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());
                e.printStackTrace();
            }
            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();
    }
}
3
daffycricket

Avez-vous vu le projet se connecter avec Twitter github, il est basé sur Twitter4j et implémente la connexion Twitter pour Android.

0
ejectamenta