Twitter API code

There are many other tutorials and examples on how to write your own Twitter API handling code in Android.. but I haven’t found one that worked without tweaking and changes. So if you are running into that same problem, I hope this small writeup and source will help you.

Not all code is purely mine, I used various sources and forgot most of them out of frustration cause they didn’t “just work” .. credits to those people tho ! without their sources and examples I wouldn’t have gotten this code to work.  And of course the libraries included are not mine, but they are free to download and you might want to hunt down their websites for the latest versions!

If you have questions about this, just drop them in the comments, so that I don’t have to answer the same questions in my inbox ;)

Step 1: Download the source code: Source code and Libraries
Step 2: Copy the lines from the ManifestAddition.xml file (in the zip) into your AndroidManifest between the <Application> tags.
Step 3: make sure to name the “Callback” scheme in the lines you just copied. Give it a simple name like “mycoolapplication_twitter”.
Step 4: Open the com/orangepixel/twitter/ file, and change the OAUTH_CALLBACK_SCHEME constant to the same “callback scheme” as you just did in your manifest (so: “mycoolapplication_twitter”)

Step 5:  Go to, Sign in with your Twitter account (obviously) and create a new Application for your Android app.  Make sure to set the permissions to “read and write”.

Step 6: Once your twitter app is created you can fill the other values with the Consumer_key and Consumer_Secret values of your Twitter application.

Step 7: Basically that should have you all setup to use the tweeting powers from within your app or game. Only thing to add now, is add your code to call the actual handling of twitter:

String tweetMessage;
final Handler twitHandler = new Handler();

public static SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(this);

public final void shareTwitter(String yourTweet) {
if (TwitterUtils.isAuthenticated( prefs )) {
// already authenticated before;
} else {
// needs authenticating, so take care of it
Intent i = new Intent(getContext(), OAuthVerify.class);
i.putExtra(“tweet_msg”, tweetMessage);

final Runnable sendTweet = new Runnable() {
public void run() {
try {
TwitterUtils.sendTweet(prefs, tweetMessage);
} catch (Exception ex) {

This might need some tailoring to your own application flow. But it’s as basic as I could make it. Just call: shareTwitter(“Howdy awesome dudes at @OrangePixel!”) and it will handle the tweeting.

If the user hasn’t authenticated before, it will pop up the known Twitter authenticate page in a little WebView, those credentials will be saved in the preferences, and after that tweets can be send without the popup


Bookmark the permalink.