Android integration with Facebook and Twitter:

25 Aug

Android integration with Facebook and Twitter:

Are you an Android developer who wants to integrate your app with Twitter and Facebook 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.

I did find it easier to integrate Facebook than integrating Twitter. And you will see why. So let’s get the difficult one out of the way and handle the Twitter integration.

Twitter integration with Android:

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

5. Sit back and smile

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

We will need all this information later. You can put these in a constants class similar to the one below:

 

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

}

 

I used the following libraries for oAuth and Twitter integration:

signpost-commonshttp4-1.2.1.1.jar

signpost-core-1.2.1.1.jar

http://code.google.com/p/oauth-signpost/

httpclient-4.0.1.jar

http://hc.apache.org/httpcomponents-client-ga/

twitter4j-core-2.1.11

http://twitter4j.org/en/index.html

Include these as jars to your eclipse project.

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 WebViewLaunchActivity 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();
}
}
}
}

Most of the code you will need is posted above. Happy tweeting. Drop a comment if you have a question.

copyright 2012 10jumps Llc.

copyright 2012 10jumps LLC.