Get results from Android Chooser

Perhaps you have some sort of content that your users would like to email to their coworker or share with their Instagram friends. Perhaps you’d like to take it a step further, and get some insight into where your users are sharing your app’s content or kick off some background task once the user selects an app.

As of Lollipop (API Level 22), the Intent class contains a new #createChooser method that takes an IntentSender parameter.

Intent createChooser (Intent target, CharSequence title,    
IntentSender sender)

An IntentSender is simply an abstraction around an Intent with some action you intend to perform with that Intent. In our case, we are using an IntentSender to broadcast that our user has selected an app.

An IntentSender is created with a PendingIntent. It’s important to note that you need to create a PendingIntent to create an IntentSender. This means that in total, we are creating two Intents (a “receiver” Intent and a “share” Intent) and one PendingIntent.

We pass in a custom BroadcastReceiver to our receiver intent’s constructor. The BroadcastReceiver’s #onReceive method acts as a callback for the user selecting an app from the app chooser.

Lets write our BroadcastReceiver first.

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
// do something here
}
}

Make sure to add the following line to your AndroidManifest.xml file. The android:exported=”false” tag simply ensures that apps outside of our application can’t send messages to this BroadcastReceiver.

<receiver android:name="MyReceiver" android:exported="false"/>

We now need to write our receiver Intent, passing in the MyReceiver to it’s constructor.

Intent receiver = new Intent(context, MyReceiver.class);

Now, we can use our receiver Intent to create a PendingIntent. The receiver Intent is used to create the PendingIntent’s IntentSender. We need this later in our #createChooser method, and this is how we wire up MyReceiver’s #onReceive method to be called once a user makes a selection.

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);

And of course, we need to build our share intent. In this example, we are sharing an image.

String type = "image/*";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType(type);
share.putExtra(Intent.EXTRA_STREAM, awesome_photo_uri);

Now, putting it all together:

startActivity(Intent.createChooser(share
, "some_title"
, pendingIntent.getIntentSender()));

And, ta-da! Now your app is listening for the user to make a selection and share your app’s content. You can do something like the line below in your #onReceive method to find out which app the user shared the photo to.

String selectedAppPackage = String.valueOf(intent.getExtras().get(EXTRA_CHOSEN_COMPONENT))