Showing posts with label twitter. Show all posts
Showing posts with label twitter. Show all posts

Wednesday, April 27, 2011

Using Twitter4J to Tweet in Android

So I'm working on a little project for Google I/O that requires, amongst other things, the ability to post status updates to Twitter from within an Android app. I asked about it on Twitter and a couple of people asked me to post the results (and associated code snippets) so here you go.

I was hoping for a small code snippet that would let me do that without needing any third-party libraries, but the feedback from the lazy web suggested that jumping through the hoops of an OAuth implementation myself wasn't worth the effort.

The wisdom of crowds suggested Twitter4J as a simple alternative - and as the following code snippet shows - the most simple case is pleasantly simple to implement.

Twitter twitter = new TwitterFactory().getInstance();
AccessToken a = new AccessToken(oauth_token, oauth_token_secret);
twitter.setOAuthConsumer(consumer_token, consumer_secret);
twitter.setOAuthAccessToken(a);
twitter.updateStatus("If you're reading this on Twitter, it worked!");


In this instance I'm the only one who'll be using the app, so I'm dropping an auth token and auth token secret unique to my own Twitter login rather than going through the process required to obtain a user-specific auth token. If that matches your use-case you can grab those values by clicking "My Access Token" on the Twitter developer site after you've registered your app.

You can download Twitter4J for Android here. Then just add twitter4j-core-android-2.2.1.jar into your project as an external JAR.