How to customize share intent in Android?

Zak picture Zak · Jul 26, 2011 · Viewed 37.8k times · Source

Now i can use the share intent to open the share dialog

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT, link);  
    startActivity(Intent.createChooser(intent, "Share with"));

but i need the dialog not to appear and share directly to one social network for example (FB or twitter)

any advice how to do that ?

Answer

Derzu picture Derzu · Feb 10, 2012

There is a way to directly open the intent you wants. You can get the list of intents and open only one.

See this code:

private void initShareIntent(String type) {
    boolean found = false;
    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.setType("image/jpeg");

    // gets the list of intents that can be loaded.
    List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
    if (!resInfo.isEmpty()){
        for (ResolveInfo info : resInfo) {
            if (info.activityInfo.packageName.toLowerCase().contains(type) || 
                    info.activityInfo.name.toLowerCase().contains(type) ) {
                share.putExtra(Intent.EXTRA_SUBJECT,  "subject");
                share.putExtra(Intent.EXTRA_TEXT,     "your text");
                share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(myPath)) ); // Optional, just if you wanna share an image.
                share.setPackage(info.activityInfo.packageName);
                found = true;
                break;
            }
        }
        if (!found)
            return;

        startActivity(Intent.createChooser(share, "Select"));
    }
}

If you wanna open twitter, do that:

initShareIntent("twi");

if facebook:

initShareIntent("face");

if mail:

initShareIntent("mail"); // or "gmail"

If you wanna show a list of intents that match with the type, insted of use the first mach, see this post: Android Intent for Twitter application