Guanlun
Guanlun

Reputation: 1608

Android - Sharing with Intent using the last action

When using Intent for sharing (Intent.ACTION_SEND), how can I remember the last app used for sharing and add a shortcut for that app?

In my app, if I have just shared my article using gmail, can I add a shortcut "sharing with gmail" so that I could directly share with gmail without having to select an application?

Thank in advance!

Upvotes: 2

Views: 554

Answers (1)

Zhenghong Wang
Zhenghong Wang

Reputation: 2127

There is no listener to detect which app you choose in a default intent chooser.
Therefore, you have to create a dialog which contains all intents for ACTION_SEND by yourself.

You can get a intent list for ACTION_SEND by the following code.

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);

Then, use the list to build a dialog, add listener for each intent.
After user tap one of them, save its' package name. You can retrieve the package name by ResolveInfo.activityInfo.name.

Next, you can use the package name to filter ACTION_SEND, only firing the filtered app.
Here is a snippet for launching Twitter app.

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {  
    if ("com.twitter.android.PostActivity".equals(app.activityInfo.name)) {
        final ActivityInfo activity = app.activityInfo;
        final ComponentName name = new ComponentName(activity.applicationInfo.packageName,activity.name);
        shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        shareIntent.setComponent(name);
        v.getContext().startActivity(shareIntent);
        break;
    }
}

Hope it helps!

Upvotes: 2

Related Questions