Integration of android application with twitter.

Thursday, September 27, 2012


Are you an Android developer who wants to integrate your app with Twitter so that your end user can:

1. Login with Twitter
2. Post messages to Twitter

It’s not so hard to achieve these two - if you know what you are doing. And the steps below should make it easy for you to achieve the desired results.


  • Setting up the Twitter account and application.
The basic steps are:

1. You have to create an Account on Twitter before you do anything.
2. Register you application with Twitter here (https://dev.twitter.com/user)
3. Create the Activity to enter your tweet


4. Authenticate users and let the user grant you access to your application so your application can post on his/her stream


Let’s start with step #2. After you register your application with Twitter, you will get the following information:

Once the application is registered, you’ll receive the following information associated with your application :

Consumer key

************************ (masked)

Consumer secret

************************ (masked)

Request token URL

https://api.twitter.com/oauth/request_token

Access token URL

https://api.twitter.com/oauth/access_token

Authorize URL

https://api.twitter.com/oauth/authorize

Registered OAuth Callback URL

http://someurl.com


This is all the information we need to start integrating Twitter in our Android application.
Note : The callback URL specified here is just a required field that we need to fill in, but is not used in our application. Instead, we define our own callback URL that we’ll pass on when authenticating the user.

  • The sample application.
The sample application is available in Github in the AndroidTwitterSample repository. Before running this project, make sure you change the com.ecs.android.sample.twitter.Constants file to include your consumer key and consumer secret. The application provides you with an end-to-end example on how to authenticate against Twitter and send tweets on behalf or the authenticated user.

The sample project has a dependency towards 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
Note : You’ll need to include these libraries into your own project if you want to enable the Twitter integration.

  • The constants files
public class Constants {

public static final String CONSUMER_KEY = "<FILL IN YOUR CONSUMER KEY FROM TWITTER HERE>";
public static final String CONSUMER_SECRET= "<FILL IN YOUR CONSUMER SECRET FROM TWITTER HERE>";

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

}


Please be sure to read up on oAuth (http://oauth.net/) a little to understand the steps below
Next lets create the screen where the users will enter their tweets:


public class AndroidTwitterActivity extends Activity {
….
private EditText mTwitterMessage;
private TextView mTweetSize;
…..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twitter);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
mTwitterMessage = (EditText) findViewById(R.id.editTweetMsg);
mTweetSize = (TextView) findViewById(R.id.tweetSize);
mTweetSize.setText("" + (140 - mTwitterMessage.length()));
Button tweet = (Button) findViewById(R.id.btn_tweet);
…...
// make sure you keep track of number of characters:
mTwitterMessage.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

public void onTextChanged(CharSequence s, int start, int before, int count) {
String charsLeft = "" + (140 - s.length());
mTweetSize.setText(charsLeft);
}
public void afterTextChanged(Editable s) {}
});

tweet.setOnClickListener(new View.OnClickListener() {
/**
Send a tweet. If the user hasn't authenticated to Tweeter yet, he'll be redirected via a browser
to the twitter login page. Once the user authenticated, he'll authorize the Android application to send
tweets on the users behalf.
*/

public void onClick(View v) {
if (TwitterUtils.isAuthenticated(prefs)) {
sendTweet();
finish();

} else {
Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
i.putExtra("tweet_msg",getTweetMsg());
startActivity(i);
}
}
});



The following code should let you authenticate with Twitter. We are using a WebView to display the oAuth screen from Twitter. This is where you will enter the Twitter credentals. Once authenticated, you will go back to the previous Activity from where the tweet will be posted.

URL variable below is the request token.


public class TwitterIntegration extends Activity {


 String url;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if(extras!=null){
url = extras.getString("url");
}
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
webview.setVisibility(View.VISIBLE);
setContentView(webview);

/* WebViewClient must be set BEFORE calling loadUrl! */
webview.setWebViewClient(new WebViewClient() {

@Override
public void onPageStarted(WebView view, String url,Bitmap bitmap) {
System.out.println("onPageStarted : " + url);
}
@Override
public void onPageFinished(WebView view, String url) {
//sview.setVisibility(View.INVISIBLE);

if (url.startsWith(Constants.OAUTH_CALLBACK_URL)) {
try {

if (url.indexOf("oauth_token=")!=-1) {
view.setVisibility(View.INVISIBLE);
goBack(url);

}
else if (url.indexOf("error=")!=-1) {
view.setVisibility(View.INVISIBLE);

}

} catch (Exception e) {
e.printStackTrace();
}
}
}
});
webview.loadUrl(url);

}

private void goBack(String url){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Uri uri = Uri.parse(url);
if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
new RetrieveAccessTokenTask(this,PrepareRequestTokenActivity.getConsumer(),PrepareRequestTokenActivity.getProvider(),prefs).execute(uri);
finish();
}
}
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {

private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;

public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs=prefs;
}

/**
* Retrieve the oauth_verifier, and store the oauth and oauth_token_secret
* for future API calls.
*/
@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,AndroidTwitterActivity.class));

executeAfterAccessTokenRetrieval();

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

return null;
}

private void executeAfterAccessTokenRetrieval() {
String msg = getIntent().getExtras().getString("tweet_msg");
try {
// TwitterUtils.sendTweet(prefs, "This is a tweet");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.