Get IntentSender object for createChooser method in Android
The chooser target intent is not a PendingIntent
. For instance, in the following snippet, I am declaring intent for ACTION_SEND
, with type text/plain
, and this is the my target intent for the Intent.createChooser
. Then I am creating another Intent
, receiver, and a handler, the PendingIntent
, which will invoke onReceive
of my BroadcastReceiver after the user picks something from the chooser.
// Set up the broadcast receiver (preferably as a class member)
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Unregister self right away
context.unregisterReceiver(this);
// Component will hold the package info of the app the user chose
ComponentName component = intent.getParcelableExtra<ComponentName>(Intent.EXTRA_CHOSEN_COMPONENT);
// Do something with component
}
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
intent.setType("text/plain");
// Use custom action only for your app to receive the broadcast
final String shareAction = "com.yourdomain.share.SHARE_ACTION";
Intent receiver = new Intent(shareAction);
receiver.putExtra("test", "test");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
Intent chooser = Intent.createChooser(intent, "test", pendingIntent.getIntentSender());
// Before firing chooser activity, register the receiver with our custom action from above so that we receive the chosen app
context.registerReceiver(broadcastReceiver, new IntentFilter(SHARE_ACTION));
startActivity(chooser);
Edit:
The information, in the case of the BroadcastReceiver
is embedded in the intent you get as parameter. After you selected one of the option, retrieve the Bundle's extras and using the key Intent.EXTRA_CHOSEN_COMPONENT
, you should be able to find what the user picked.
Try adding as simple Log.d to onReceive
for (String key : intent.getExtras().keySet()) {
Log.d(getClass().getSimpleName(), " " + intent.getExtras().get(key));
}
In my example I got
ComponentInfo{org.telegram.messenger/org.telegram.ui.LaunchActivity}
for Telegram
and
ComponentInfo{com.google.android.apps.inbox/com.google.android.apps.bigtop.activities.ComposeMessageActivity}
for InBox