31 March 2017

Sharing is Caring

Or so they say.

Luckily for us, Android makes it super easy to share things between apps. It even provides a pretty-looking Intent chooser*!


We can get this nifty bottom sheet with only a few lines of code:
// Construct the intent we want to send
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
shareIntent.setType("text/plain");

// Ask Android to create the chooser for us
final Intent chooser = Intent.createChooser(shareIntent, getString(R.string.share_text));
startActivity(chooser);

That's it, your work is done.

But what if we want the users to choose our own app? For example, we have a Share via Domain activity in our app that we prefer our users to use when sharing properties. It generates an email you can send to your friends and includes some information about the property. However, we still want to give users the option to share via other channels.

Luckily for us (we Android devs are really lucky, in case you haven't noticed), there is an API that allows us to do just that.

We can add extras (via EXTRA_INITIAL_INTENTS) to the chooser Intent that will tell the OS to prioritise the Intents we want. In my sandbox app, I made a simple activity that will display the text we send in shareIntent above.

Intent customSharer = new Intent(this, CustomShareActivity.class);
Intent[] initialIntents = new Intent[] {customSharer};
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, initialIntents);

This will surface our priority intents at the very top of the list. It will appear with app icon, with the value we have in label from the Manifest.

<activity android:name=".bottomsheet.CustomShareActivity"
          android:label="Choose Me!"/>
We end up with something like this:


Pretty cool, huh?


*I know, the developer docs screenshots are a tad outdated. ¯\_(ツ)_/¯