BLOGS

Product Engineering Outsourcing, Tech Talk

06
Jun

Twitter4j OAuth on Android

Can your application tweet, can it post on walls of people who like this application? Let’s have a look at how to integrate twitter with an android application.

What is OAuth?

OAuth is an open protocol which allows the users to share their private information and assets like photos, videos etc. with another site without sharing their credentials (username and password) to the latter. Hence making it very secure way of transmission of data..

Reference: You can learn more about the same at About OAuth.

We will learn about how this connection is implemented below. Here are the steps that will lead to create a successful twitter post.

  • Get your application signed to twitter site – You will have to login first. This will give you a form to fill up the application details like Application Icon, Application Name, Organization, etc. The most important of these is the Application type (which should be Browser Type) and Callback URL. Also, give access type as Read and Write.

On submission of the form you will receive Customer Key and Customer Secret. Copy these and keep them for usage in the android application.

  • Create an Android project from the IDE, I am using Eclipse to show the below example.

In application manifest xml add the INTERNET permissions and BROWSABLE intent filter. To know more about application manifest you can refer to my post on Application Manifest where I have explained the key components of Application manifest. Here I am going to highlight only the intent filter which will launch browser and data tag which describes the call back URL where the twitter data is downloaded and displayed to the user.

<?xml ………… >
……
……
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>
	<category android:name="android.intent.category.DEFAULT"></category>
	<category android:name="android.intent.category.BROWSABLE"></category>
	<data android:host="OAuthTwitter" android:scheme="myTweet"></data>
</intent-filter>
……
……
</xml>

  • Twitter4j is a Java library for Twitter API’s which also you to integrate your Java application with the Twitter services. Advantage of using this is, it is very simple to use and with OAuth it provides a very secure interaction. To know more about Twitter4j refer link. Twiiter4j related can be discussed on Google group. You’ll need to download jar files from twitter4j (twitter4j-2.2.2.zip) and signpost (signpost-core-1.2.1.1.jar & signpost-commonshttp4-1.2.1.1.jar). Add these libraries to the project. Follow below steps for the same.
  1. Right click on the project and go to build path.
  2. Click on “Add external libraries” to add the jar files into the project.

  • There are multiple ways in which you can create a tweet using twitter4j. Below is the simplest way for the same.
package com.android.OAuth;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import oauth.signpost.OAuthProvider; // ---- (1)

import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import twitter4j.Twitter; // ---- (2)
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;

public class OAuthTwitter extends Activity {
	public final static String CONSUMER_KEY = "give your consumer key"; // ---- (3)
	public final static String CONSUMER_SECRET = "give your consumer secret";
	public final static String CALLBACK_URL = "myTweet-OAuthTwitter:///"; // ---- (4)

	private CommonsHttpOAuthConsumer commonHttpOAuthConsumer;
	private OAuthProvider authProvider;

	private Twitter twitter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        commonHttpOAuthConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);  // ----- (5)
        authProvider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
        		"http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize");
        try {
			String oAuthURL = authProvider.retrieveRequestToken(commonHttpOAuthConsumer, CALLBACK_URL);
			this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(oAuthURL)));
		} catch (OAuthMessageSignerException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (OAuthNotAuthorizedException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (OAuthExpectationFailedException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (OAuthCommunicationException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
    }

    protected void onNewIntent(Intent intent) { // ---- (6)
    	super.onNewIntent(intent);

    	Uri uri = intent.getData(); // ---- (7)
    	if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
    		String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
    		try {
    			authProvider.retrieveAccessToken(commonHttpOAuthConsumer, verifier); // ---- (8)

    			AccessToken accessToken = new AccessToken(commonHttpOAuthConsumer.getToken(),
    					commonHttpOAuthConsumer.getTokenSecret()); // ---- (9)

    			twitter = new TwitterFactory().getInstance(); // ---- (10)
    			twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

    			twitter.setOAuthAccessToken(accessToken); // ---- (11)

    			// Alternate way:
    			// twitter = new TwitterFactory().getOAuthAuthorizedInstance(CONSUMER_KEY, CONSUMER_SECRET,
    			//		 new AccessToken(commonHttpOAuthConsumer.getToken(), commonHttpOAuthConsumer.getTokenSecret()));

    			// Tweet message to be updated.
    			String tweet = "Hiee there, This is send from my application - OAuth, Twitter";
    			twitter.updateStatus(tweet); // ---- (12)
    		}
    		catch (Exception e) {
    			Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG);
    		}
    	}
    }
}

Here is the brief about the code above. Please see inline numbers above for comments.

-          Lines (1) & (2) shows the “include” of the libraries related to signpost and twitter respectively.

-          Line (3) is where you need to add the Consumer key and Consumer Secret received after registering the application to the twitter site.

-          Line (4) describes the call back URL for the application to which return the user after authorization.

-          Line (5) follows the implementation which opens the network using the consumer key and consumer secret with the help of signpost API’s.

-          After twitter verifies the consumer key and secret the application returns to the line (6).

-          Line (7) verifies the Uri from the intent if containing the call back URL.

-          Line (8) retrieves the token and secret into the OAuthConsumer.

-          Line (9) gets the access token from the OAuthConsumer.

-          Line (10) inits twitter4j for sending the tweet with the respective consumer key and secret.

-          Line (11) sets the access token from the OAuth provider to the twitter4j.

-          Line (12) updates the tweet to the server.

Now your application is ready to send tweet and update application’s status on twitter.

Member of Mobile Center of Excellence

6 comments on “Twitter4j OAuth on Android
  1. reTs says:

    I am trying with the code and after the line
    this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(oAuthURL)));
    the app opens the page asking for authorization of my twitter app using the default browser,that’s what I want. However it is not invoking onNewIntent method afterwards.
    Have I missed something? Thank you.

  2. Fahim Shaikh says:

    Cross check the following points:
    1. Intent filter with content type as “BROWSABLE” mentioned in the application manifest file. Check step 2 in blog.
    2. Earlier one had set application type as BROWSER while registering Application to the twitter site. They have removed it now. Cross check if you can grap anything out of this.

    If this persist, share the application log.

  3. Xon says:

    hey man, the browser doesn’t redirect to the apps after authorization.. what’s wrong man? I’ve set the content as BROWSABLE in the manifest.. please help me..

  4. Dhanesh Mane Fahim Shaikh says:

    Hi Xon,

    Check out the following points.Pls follow all the steps in case you missed any.

    1. Check the manifest file if the in the for the activity have been correctly set to the redirection URI.
    Also, check if the specified URL matches with the callback url declared in the code.

    2. Also make the launch mode for the activity as singleTask or SingleInstance depending on your requirement.

    Hope this solves your problem.

    Thanks,
    Fahim

  5. Nice post! that is good information, it is useful to me thanks.

  6. Rosario says:

    I’m really enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much
    more pleasant for me to come here and visit more often.

    Did you hire out a developer to create your theme? Fantastic work!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>