Fahim Shaikh

Fahim Shaikh's page

Software Engineer - Mobile CoE
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.

Fahim Shaikh
Fahim Shaikh– Software Engineer – Mobile CoE

, , , , , ,

30
May

In this blog post we would try and understand the basics of Application Manifest in the Android system.

The simplest of any Android application has  the following components:

  1. Resources classified in the resource folder (res).
  2. Some auto generated code like R.java.
  3. ApplicationManifest.xml file.

This blog post will deal with the third component – Application manifest file.

Application Manifest is an xml file every Android application contains with the name ApplicationMainifest.xml in the root directory of the application.

-          The file is generated automatically on finish of wizard for android project creation.
-          File gives all the information pertaining to the successful execution of all the functionalities present in the application to the android system.
-          It is like a blue print of the application components or what you can call a make file in C++ projects like Qt, Objective C in IPhone.

Sample example:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.android.sampleApp" android:versionCode="1"
	android:versionName="1.0"> - (1)
	<application android:icon="@drawable/icon" android:label="@string/app_name"
		android:permission="android.permission.BLUETOOTH"> - (2)
		<activity android:name=".SampleActivity" android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity> - (3)
	</application>
	<uses-sdk android:minSdkVersion="9" /> - (4)
	<permission android:name="com.android.myPermission"
		android:icon="@drawable/icon"
		android:label="My Permission"
		android:protectionLevel="dangerous"
		android:permissionGroup="com.android.SamplePermission"
		android:description="@string/some_description"></permission>
</manifest>

Versioning:

Refer line (1) in the code above.

<manifest> tag consists of application versioning information (android:versionCode and android:versionName) helps the android systems to maintain the upgrade/ downgrade of application.

Android system uses versionCode for understanding the upgrade of the application on the device and versionName is used only for the user notification purpose. versionName is displayed for the user to notify that a newer version of the application is available in the market.

Activity:

Refer line (3) in the code above.

Android application consists of four types of components:

  1. Service – Non-visual component always running in background to perform long operations.
  2. Content providers – It’s a data storage system eg: File storage systems and SQLite. Content providers provide a standard interface that helps in application doing standard operations on database system. E.g. address book, messages, emails etc.
  3. Broadcast receivers – status messages / events / error handling etc. for an example error messages,
  4. Activity – Activity are screens that user interacts with while using the application, it may be a form collecting keyboard inputs, clicks etc. It is same as a form is to a web application.

Activities need to be register for an application in the Manifest file for Android systems to include them in the run environment. An application may consist of one or more activities; there can be multiple activity tags in the application which may interact with each other.

<intent-filter> – Intent filters control which actions of android, user driven or application driven is going to launch the application. Activities can contains multiple intent filters. Contains:

-          <action> as MAIN (android:name=”android.intent.action.MAIN”) means that this activity is the entry point for the application.  This activity will be the top level screen (Home screen) in the application.

-          The manifest xml above show case how you can place your activity on the android home screen launcher. For that you have to put a <category> with Launcher (android:name=”android.intent.category.LAUNCHER”) telling the system that this activity should be top-level LAUNCHER.

Permission:

Refer line (2) in the code above.

Android OS model requires applications to highlight what features of OS or resources they are going to use. Take an example of an application that is going to make use of the Bluetooth for transfer of files or need internet access for connection to facebook, twitter etc.

Hence, this tag provides the information related to the access rights to the specific components or features of the application from the very same application or other applications. By default android applications do not have any permission to intervene the device data or components.

This can be provided either in <application> tag or <uses-permission>

For example:

  1. Permissions to access BLUETOOTH of device is: <application android:permission=”android.permission.BLUETOOTH” />
  2. To Receive SMS: <uses-permission android:name=”android.permission.RECEIVE_SMS” />

User can define their set of permissions under <permissions> tag.

SDK Version:

Refer line (4) in the code above.

Application which makes use of specific features like 3D transitions available in higher version Android SDK say 3.0 will not work on the devices having lower version say 2.3. Hence manifest file provides the information to the system while installation; checking for the availability of SDK version and install accordingly.

<manifest> tag holds <uses-sdk> containing minimum API level  integer (android:minSdkVersion) which helps the Android system to allow/disallow installation of the application depending upon the system’s API level.

Eg: For minSdkVersion = 9 minimum system’s API level is Android 2.3.3 SDK.

For detailed information on Manifest refer:  Application Manifest

Fahim Shaikh
Fahim Shaikh– Software Engineer – Mobile CoE

, , , , , , ,