06
Jun

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.

By

Team Member - Member of Mobile Center of Excellence

17
Nov

Over the past decade the explosion of Social Networking sites like Facebook, MySpace and Twitter has drastically changed the way how people interact socially. Social sites are playing a key role in building social graphs, sharing information and fostering innovation. The spectrum of its usability has grown widely since its inception, from users just building profiles and making friends to businesses using it for branding & interacting with their consumers, recruitment firms to find potential employees, science communities for exchange of ideas, non-profits for spreading social good and by students & teachers as a communication tool.This growth in its usability is due the hundreds of millions of active users together spending billions of minutes everyday on these sites building profiles, making status updates, uploading photos and building social graphs making them information rich.

While these sites have built some of the best tools on the world wide web, the opening up of their product to developers via APIs in the past 3 years have spawned “developer ecosystems” that build applications over popular services like Twitter and Facebook that help a person do everything from network with travelers to play social online games. Given below is a brief of 3 Social Networking Developer Ecosystems that would help you to better understand your options.

1.    Facebook
Facebook launched the Facebook platform in May 2007 for application developers that provides a framework to develop applications that would render within facebook.com and interact with core Facebook features.  Simultaineously a markup language called the Facebook Markup Language(FBML) was also introduced that is used to give applications the Facebook “look and feel”  and hook into several Facebook integration points, including the profile, profile actions, Facebook canvas, News Feed and Mini-Feed.  Since then, tens of thousands of applications have been built on top of the Facebook platform. Later on, Facebook Query Language (FQL) was introduced that allows you to use a SQL-style interface to  query Facebook social data without using the API. While most platforms force developers to use iFrames if they want to embed javascript within the application, Facebook answered this question with the introduction of FBJS that allowed developers to manipulate markup on the fly, animation and AJAX making applications more dynamic. Today, Facebook has over 350,000+ applications that play a critical role in maximizing Facebook’s active user base. Being the most popular application on Facebook, “Farmville” currently has over 60 million monthly active users.

In late 2008, Facebook announced Facebook Connect that allows developers to let users login to their websites with their Facebook credentials. It even allows other Facebook features, like your friend list and friend invite features to be implemented on your website, which can in turn send data back to Facebook as News Feeds. With over 15K websites already utilizing Facebook Connect, it has now become a must have feature for every social website for 2 main reasons : (1) Users do not have to go through the process of registering on your website if they are a Facebook user, your website can directly pull info from the users Facebook profile and (2) Your web site gets tons of exposure on Facebook as the users actvities on your site get posted to his Facebook profile.

Facebook has even gone a step further in encouraging developers by introducing the fbFund where developers can submit their applications to qualify for investments to grow their venture.

2.    Twitter
Twitter is one of the best examples of an very Open API and has provided developers a opportunity to build a full-fledged business by using it. Within a short span of time this ecosystem has transformed into a mainstream phenomenon with the development of Twitter apps that do everything from managing your twitter profile to analyzing tweets for real world trends. The Twitter API is nothing but a simple service that provides RESTfull access to the Twitter database and activity streams. Twitter initially started of with the basic authentication by which developers send the users credentials in the header of the HTTP request. But this being insecure and difficult to track hence in early 2009 they integrated the OAuth pattern of integration into the REST API permitting users a seamless experience of login into a 3rd party website using their Twitter account.

Twitter lacks many features in its pursuit of for simplicity and this gives openings to developers to fill the holes. Currently around 80% of Twitter’s usage is via 3rd party apps. and the Twitter API has 10x the traffic of its website. Twitter does not have 300+ million active user but it has momentum, excitement and virility which can cause your application to go from zero to a million users in a matter of days or weeks. Twitter is fast growing and new features are getting added regularly, requiring your application to adapt to it at the same time. A major problem with the Twitter ecosystem is its stability, so you have to make sure that your application doesn’t break and throw heaps of code when the API is down.

3.    MySpace
MySpace first got into the platform party by teaming with Google and a number of other social networks against the Facebook platform and releasing OpenSocial in November 2007, which were a set of API’s that would make applications interoperable with any social network system that supports it. The patnership spearheaded an initiative to standardize and simplify the development of social applications. Later on in early 2008 MySpace  independently launched the MySpace Developer Platform(MDP) that supports the OpenSocial model to enhance the overall experience of users through the development of Social Applications.

MySpace has undertaken a recent expansion of their platform through the MySpaceID project. MySpaceID provides Developers the opportunity to access user identities within the context of third-party environments. The main components of the MySpace platform are pretty similar to that of Facebook, but since MySpace supports the OpenSocial model the same application can be ported to any other social network with just a few minor tweaks to the code. With just around 15k apps in the MySpace apps Gallery and just a few websites integrating with MySpaceID, the Facebook ecosytem emerges as the clear winner in this case.

No doubt that these 3 ecosystems are the best and most established but they aren’t the only ones. Networks like Bebo, Yahoo, Friendster and the recently launched Google Wave have opened up their set of API’s that would allow you to reach millions of users through your applications. All these platforms are fast-growing and frequently-changing for the good, so as a developer even though you have a lot of choice with the ecosystems, it is suggested that you pick one ecosystem that you are a big fan of and program for it as keeping pace with all the ecosystems would be a real challenging task.

- Royston Olivera