четверг, 21 июля 2011 г.

Integrating twitter into android app

Many Android developers ask how to start the default twitter client from their application. Which Intent should you use?

It is often advised to send an Intent with ACTION_SEND. However, many programs will fire up: Gmail, SMS send, dropbox, twitter clients, MMS Send, flickr send, etc. This is too broad.

On the other hand, some people advise to filter on the MIME type application/twitter. But this is too restrictive: very few clients will recognize this unofficial/non-standardized MIME type (twidroid is among them, but HTC default client is not).

So, You can:

1. Use Twitter API (helped by a library such as twitter4j;
2. Find a way to integrate with the Twitter app, although there is no published protocol
3. If you don't expect the user to do this very often, you can just open up http://twitter.com/?status= using a simple intent:

Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(message)));

Eventually, I came up with the following solution: list all applications that reply to ACTION_SEND and filter on known package names:

public Intent findTwitterClient() {
        final String[] twitterApps = {
                "com.twitter.android", // official
                "com.twidroid", // twidroyd
                "com.handmark.tweetcaster", // Tweecaster
                "com.thedeck.android"}; // TweetDeck
        Intent tweetIntent = new Intent();
        final PackageManager packageManager = getPackageManager();
        List <resolveinfo> list = packageManager.queryIntentActivities(
                tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
        for (int i = 0; i <twitterApps.length; i++) {
            for (ResolveInfo resolveInfo : list) {
                String p = resolveInfo.activityInfo.packageName;
                if (p != null && p.startsWith(twitterApps[i])) {
                    final ActivityInfo activity=app.activityInfo;
            final ComponentName name=new ComponentName(resolveInfo.applicationInfo.packageName, activity.name);
            intent=new Intent(Intent.ACTION_SEND);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            return intent;
        return null;

After this You can post text on your wall:

intent.putExtra(Intent.EXTRA_TEXT, message);

Hope, this helps You!

2 комментария:

  1. Nice post! but,would you upload code sample that use twitter integrating? I am new Be on developer android, so I need more sample code for I have learned.

    Thx.. :)

  2. Hi,yugienugraha.
    Do You tried this code?
    It isn't difficult.

    Try something like this:

    Intent tweetIntent = findTwitterClient();
    if( tweetIntent != null ){
    tweetIntent.putExtra( Intent.EXTRA_TEXT, "Hello, Android" );
    context.startActivity( tweetIntent );

    Hope this helps You