Android Intent for Twitter application

I’m posting this because I haven’t seen a solution yet that does exactly what I want.

This primarily launches the official Twitter app, or if that is not installed, either brings up a “Complete action using…” dialog (like this) or directly launches a web browser.

For list of different parameters in the twitter.com URL, see the Tweet Button docs.
Remember to URL encode the parameter values. (This code is specifically for tweeting a URL; if you don’t want that, just leave out the url param.)

// Create intent using ACTION_VIEW and a normal Twitter url:
String tweetUrl = String.format("https://twitter.com/intent/tweet?text=%s&url=%s",
        urlEncode("Tweet text"), 
        urlEncode("https://www.google.fi/"));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(tweetUrl));

// Narrow down to official Twitter app, if available:
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
    if (info.activityInfo.packageName.toLowerCase().startsWith("com.twitter")) {
        intent.setPackage(info.activityInfo.packageName);
    }
}

startActivity(intent);

(URL encoding is cleaner if you have a little utility like this somewhere, e.g. “StringUtils”.)

public static String urlEncode(String s) {
    try {
        return URLEncoder.encode(s, "UTF-8");
    }
    catch (UnsupportedEncodingException e) {
        Log.wtf(TAG, "UTF-8 should always be supported", e);
        throw new RuntimeException("URLEncoder.encode() failed for " + s);
    }
}

For example, on my Nexus 7 device, this directly opens the official Twitter app:

enter image description here

If official Twitter app is not installed and user either selects Chrome or it opens automatically (as the only app which can handle the intent):

enter image description here

Leave a Comment