Android Intent for Twitter application

wouter88 picture wouter88 · Jan 16, 2010 · Viewed 78.4k times · Source

Is it possible to show a list of applications (with intent.createChooser) that only show me my twitter apps on my phone (so htc peep (htc hero) or twitdroid). I have tried it with intent.settype("application/twitter") but it doesnt find any apps for twitter and only shows my mail apps.

Thank you,

Wouter

Answer

Jonik picture Jonik · Jan 17, 2014

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