If you ever worked on an app that can share content with other apps, you might have stumbled upon Intent.ACTION_SEND or Intent.ACTION_SEND_MULTIPLE. While this is good, there is an easy way to build intents and passing extras to share a content using ShareCompat.
The ShareCompat provide a couple of classes to easily build intents for sharing contents. It is available in v4 support library.
The ShareCompat class contains two helper classes IntentBuilder and IntentReader used to share and receive contents respectively across apps.
Sharing plaintext using ShareCompat.IntentBuilder
Here we use IntentBuilder to build an intent with all needed extras for the content. The
setType() method is used to set the mime type of the content. This is required to resolve apps that can handle this content.
setText() method we can provide the content. This method takes CharSequence as parameter, so we can also style the text. However, the receiving app may or may not have support for displaying styled text.
createChooserIntent() method prompts the user with a chooser screen of all the applicable apps each time the content is shared. If we build intent without a chooser, then the default app the user has set for sharing this type of content is started automatically.
Sharing HTML content
You can also share HTML content. The
setHtmlText() method is used to set html content to the intent extra. This method also initializes the
setText() with the formatted text if it is not initialized before.
If you want to send email, there are helper methods for adding a list of “to”, “cc” and “bcc” fields (
setEmailTo(), setEmailCc(), setEmailBcc()). Use
setSubject() to set the email’s subject.
Here is an example to share an image.
setStream() is used to set the Uri for the file you like to share. For example, to share an image set the type to “image/png” and set the Uri to
You can also use
addStream() to add multiple files. Then the intent created will become an ACTION_SEND_MULTIPLE intent.
Apps can receive a shared content using ShareCompat.IntentReader. This static class provides methods to read data and relevant information from the Intent.
To receive content, you must declare an Intent Filter with the action and type of data your app can receive.
Here action SEND is used to receive single content. If you wish to handle multiple contents, then use action SEND_MULTIPLE. The category DEFAULT is required to handle implicit intent. Category Browsable allows web pages to directly share content to the app.
Specify the type of data your app can handle using the mimeType attribute.
In the receiver class, get the intent and parse the content.
We get the Intent using the IntentReceiver and check if it is a shared intent. If so, then start processing.
For example to get a plaintext content,
Similarly to get an image,
You can find my demo on ShareCompat on my github page