Up your app’s sharing game with Direct Share

As you send pictures, messages, goofy drawings, and humble-brags about your sweet life to the people you love, sharing suddenly rises in importance. You may even find yourself daydreaming about how sharing should work in your app. (Because we all know you didn’t spend too long on it the first time around.) Thankfully, Marshmallow’s Direct Share feature makes it easy to create a custom Share experience without too much hassle.

Your app can specify direct share targets that will be displayed in the Share dialog presented to the user. To be clear, this means that instead of launching your app, you can now launch a specific conversation in response to a Share intent. Context can be critical, and your app has a chance to shine here.

So, to spruce up your app and amp up your Share game, you’ll need a ChooserTargetService. This service needs to implement onGetChooserTargets() to provide the direct share targets to the system. And this method is where you can get fancy. Maybe it makes the most sense to offer up the ten most recent conversations. Or perhaps your app offers a way for users to track who they care the most about, and you can provide a list of those BFFs instead. Or maybe you know which conversations (like group messages, for example) are most prone to using attachments, and those are your likely share targets. This magic is up to you. We just made the framework, so that you could shine.

Then, in your manifest, you’ll obvi declare the service. But when you do, don’t forget to specify the BIND_CHOOSER_TARGET_SERVICE permission. Then, for each activity that you’ll be using with the new service, you’ll need to attach some new metadata to your intent filter. This is what will launch your wonderful service to provide the extra Share targets. Otherwise, you’re stuck with the old-school approach.

<activity android:name=“.SendMessageActivity”
android:label=“@string/app_name”
android:theme=“@style/DirectShareDialogTheme”>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<meta-data
android:name="android.service.chooser.chooser_target_service"
android:value=".SampleChooserTargetService" />

</activity>
...
<service
android:name=".SampleChooserTargetService"
android:label="@string/app_name"
android:permission="android.permission.BIND_CHOOSER_TARGET_SERVICE">
<intent-filter>
<action
android:name="android.service.chooser.ChooserTargetService" />
</intent-filter>
</service>

If you’d like to see this in action, we have a sample for you. Check it out and then update your own app to #BuildBetterApps.

Join the discussion on the Google+ post and follow the Android Development Patterns Collection for more!

Like what you read? Give Joanna Smith a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.