Method to send a tweet via Intent. - Android Intent

Android examples for Intent:Twitter

Description

Method to send a tweet via Intent.

Demo Code


//package com.java2s;

import java.util.List;

import android.content.ActivityNotFoundException;
import android.content.Context;

import android.content.Intent;

import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

public class Main {
    /**/* w w  w  .  j  ava2 s  . c o m*/
     * Method to send a tweet.
     * 
     * @param context
     * @param message
     * @return
     */
    @Deprecated
    public static boolean tweet(Context context, String message) {

        try {
            Intent intent = findTwitterClient(context);

            if (intent == null)
                return false;

            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_TEXT, message);
            intent.setType("text/plain");
            context.startActivity(intent);
        } catch (final ActivityNotFoundException ignored) {
            return false;
        }

        return true;
    }

    /**
     * Method to find a twitter client on the device.  I lifted this from :
     * http://regis.decamps.info/blog/2011/06/intent-to-open-twitter-client-on-android/
     * 
     * @param context A valid context instance
     * @return twitter intent
     */
    @Deprecated
    public static Intent findTwitterClient(Context context) {
        final String[] twitterApps = {
                // package // name - nb installs (thousands)
                "com.twitter.android", // official - 10 000
                "com.twidroid", // twidroyd - 5 000
                "com.handmark.tweetcaster", // Tweecaster - 5 000
                "com.thedeck.android" // TweetDeck - 5 000 
        };
        Intent tweetIntent = new Intent();
        tweetIntent.setType("text/plain");
        final PackageManager packageManager = context.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])) {
                    tweetIntent.setPackage(p);
                    return tweetIntent;
                }
            }
        }

        return null;
    }
}

Related Tutorials