We integrate Twitter into your Android application

We integrate Twitter into your Android application


Starting to write his little toy for google phone, I wanted to send records to Twitter. As it turned out on the Internet, there are many articles about connecting to your account on Twitter, but there are very few working examples. A little effort and I found the code I needed, which turned out to be quite workable. Well, let's start integration.

Recently, Twitter has used the OAuth protocol for authorization. And so we need to log in using this protocol. And actually, send a message directly to our microblog. For this, I decided to use the following libraries:
signpost library to directly use the OAuth mechanism, Twitter4J library to send tweets.

We start


And so we need a working Twitter account (if you do not have one, register here ). Next, we will need to register our test application for interacting with Twitter. And so here
we go. Now we fill in the necessary fields, it is important for us only the following, the application type (Application Type) - Browser, Default Access type - Read & Write. The rest is filled in arbitrarily, but remembering the format of the input data (we are not trying to enter something like & * ^ & JKLLKL: into the URL & callback URL, enter everything as it should).
image
As soon as we filled in all the fields, entered the captcha - we'll see the following text.

Consumer key
************************** (character set)
Consumer secret
******************* ****** (character set)
Request token URL
api.twitter.com/oauth/request_token
Access token URL
api.twitter.com/oauth/access_token
Authorize URL
api.twitter.com/oauth/authorize
Registered OAuth Callback URL
smth.com

Yes, this callback in our application we we will not use it, there we will act a little differently and define our own callback.

Start writing an application

And so we need the following libraries:
  • signpost-commonshttp4-1.2.1.1.jar
  • signpost-core-1.2.1.1.jar
  • httpclient-4.0.1.jar
  • twitter4j-core-2.1.11

image
image
And so now we have acc. libraries.
As a result, we outline a small plan of how our application will look. For simplicity, there will be only 1 Activity.
  • status bar that displays whether we connected to twitter or not
  • Tweet button, which actually posts our test message, and if we are not logged in, it opens a browser in which we log in
  • Fomally quits Twitter, clearing previous settings (what if some other application uses the account)

image

Constant file

In this file we define the constants we need for the connection.
public class Constants {
	public static final String CONSUMER_KEY = "< тут CONSUMER KEY >";
	public static final String CONSUMER_SECRET= "<тут CONSUMER SECRET >";
	public static final String REQUEST_URL = "http://api.twitter.com/oauth/request_token";
	public static final String ACCESS_URL = "http://api.twitter.com/oauth/access_token";
	public static final String AUTHORIZE_URL = "http://api.twitter.com/oauth/authorize";
	final public static String	CALLBACK_SCHEME = "x-latify-oauth-twitter";
	final public static String	CALLBACK_URL = CALLBACK_SCHEME + "://callback";
}

Let me give you a diagram of the interaction between twitter and the application.
image

CONSUMER_KEY - a unique key for our application, we receive as soon as we registered our application (something like a login)
CONSUMER_SECRET - a secret key for our application (something like a password for a “login”)
REQUEST_URL - needed to receive a request token. Part of OAuth. We receive immediately after registration.
AUTHORIZE_URL - The URL required to access Twitter. Part of OAuth. We receive immediately after registration.
ACCESS_URL - to get access token. Part of OAuth. We receive immediately after registration.
CALLBACK SCHEME is a unique identifier that we use as a callback to get access token. Generally speaking, the choice of circuitry is not limited to anything. For examples, we will use x-sample-oauth-twitter here.
CALLBACK_URL - actually our callback with which we received an answer to which authorization was successful, we can send the requests we need using access token.

Tweet Button



tweet.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    	if (TwitterUtils.isAuthenticated(prefs)) {
    		sendTweet();
    	} else {
Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
i.putExtra("tweet_msg",getTweetMsg());
startActivity(i);
    	}
    }
});

Everything is simple here, our button simply checks if the user is logged in, if everything is ok, then we send our message, if not, it offers us to log in to the browser. To do this, use PrepareRequestTokenActivity. Login process later.

Authentication

Consider the situation first, we (user) have not yet gone through the authentication process. Before we can send our messages, we will be redirected in the browser to the Twitter login page. This is implemented using PrepareRequestTokenActivity.
Let's consider what classes we need for this.

PrepareRequestTokenActivity - Sets the user and provider OAuth (Signpost library) and starts the asynchronous OAuthRequestTokenTask. It also contains a callback when we have already authenticated to obtain an access token.
OAuthRequestTokenTask - is responsible for receiving the request token, and calling the browser, in which we actually go through authentication.
RetrieveAccessTokenTask - inner class PrepareRequestTokenActivity. Called by the on NewIntent method of the PrepareRequestTokenActivity. Stores our received tokens after authorization.

PrepareRequestTokenActivity and asynchronous OAuthRequestTokenTask call

@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
   	try {
   		this.consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
   	    this.provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,Constants.ACCESS_URL,Constants.AUTHORIZE_URL);
   	} catch (Exception e) {
   		Log.e(TAG, "Error creating consumer / provider",e);
	}
       Log.i(TAG, "Starting task to retrieve request token.");
	new OAuthRequestTokenTask(this,consumer,provider).execute();
}

Here we get our callback URL to return control to the application (x-oauthflow-twitter: // callback).

@Override
protected Void doInBackground(Void... params) {
	try {
		Log.i(TAG, "Retrieving request token from Google servers");
		final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
		Log.i(TAG, "Popping a browser with the authorize URL : " + url);
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
		context.startActivity(intent);
	} catch (Exception e) {
		Log.e(TAG, "Error during OAUth retrieve request token", e);
	}
	return null;
}


Login page

And so we are on the login page.
In order for the browser to start, register our Activity (PrepareRequestTokenActivity) in the manifest file (AndroidManifest.xml). We continue to work. Now we need to get an access token to access our microblog, we do this through RetrieveAccessTokenTask. Called by the onNewIntent method already mentioned above.
>








image


@Override
public void onNewIntent(Intent intent) {
	super.onNewIntent(intent);
	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
	final Uri uri = intent.getData();
	if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
		Log.i(TAG, "Callback received : " + uri);
		Log.i(TAG, "Retrieving Access Token");
		new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
		finish();
	}
}


Now that everything is in place, you need to consider that you need to save our session, i.e. even if we restarted the application we don’t need to go through authorization again, for this we will write a function that stores all our values ​​in the background.

@Override
protected Void doInBackground(Uri...params) {
	final Uri uri = params[0];
	final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
	try {
		provider.retrieveAccessToken(consumer, oauth_verifier);
		final Editor edit = prefs.edit();
		edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
		edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
		edit.commit();
		String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
		String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
		consumer.setTokenWithSecret(token, secret);
		context.startActivity(new Intent(context,AndroidTwitterSample.class));
		executeAfterAccessTokenRetrieval();
		Log.i(TAG, "OAuth - Access Token Retrieved");
	} catch (Exception e) {
		Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
	}
	return null;
}

The executeAfterAccessTokenRetrieval method directly extracts our message and passes it through the authentication process using OAuth.

private void executeAfterAccessTokenRetrieval() {
	String msg = getIntent().getExtras().getString("tweet_msg");
	try {
		TwitterUtils.sendTweet(prefs, msg);
	} catch (Exception e) {
		Log.e(TAG, "OAuth - Error sending to Twitter", e);
	}
}

Well, do not forget to notify the user about the successful completion of our task. write a simple toast for this.

private final Handler mTwitterHandler = new Handler();
   final Runnable mUpdateTwitterNotification = new Runnable() {
       public void run() {
       	Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG).show();
       }
   };

The message itself is sent using the Twitter4J library methods.

public static void sendTweet(SharedPreferences prefs,String msg) throws Exception {
	String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
	String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
	AccessToken a = new AccessToken(token,secret);
	Twitter twitter = new TwitterFactory().getInstance();
	twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
	twitter.setOAuthAccessToken(a);
       twitter.updateStatus(msg);
}

Here's what I got as a result:
image

Translation of the tutorial:
blog.doityourselfandroid.com/2011/02/13/guide-to-integrating-twitter-android-application
with further performance checks.
Used:

As well as the source code of the author of the English-language article, I hope they will help to fully understand the described process - github link

Also popular now: