Sharing Rich Content From Your Android Apps, to Google+ and Beyond

Tuesday, May 22, 2012 | 12:04 PM

Many developers have been using Android's share intent to help their users share content with others, directly from their apps. With the recently-launched ShareCompat library, you can now help your users share rich content with their friends (like images and videos) more easily, and the items they share include attribution to your app. All you need to do is add a few lines of code!

I'll walk through a few examples that use Google+ as the application handler, but of course, these share intent improvements can work for any service. Popular apps like Foodspotting, Pulse News, and Shazam are already using ShareCompat to help users share rich content with their Google+ circles. You can check out this photo album to see how they are all taking advantage of the new library.

Creating the Share Intent

If you'd like users to be able to share text from your app, start by building the following intent:

Intent shareIntent = ShareCompat.IntentBuilder.from(ShareActivity.this)
   .setText("This site has lots of great information about Android!
      http://www.android.com")
   .setType("text/plain")
   .getIntent()
   .setPackage("com.google.android.apps.plus");

startActivity(shareIntent);
Here, I passed text and a URL to the setText method, and I used the setType method to identify the content as "text/plain." The intent builder can then pass this information to the application that's doing the sharing. Additionally, I used the setPackage method to specify the application that I want to handle it. In this case, the Google+ application is specified.

The Google+ share box with pre-populated text and link snippet.

Sharing Pictures and Video 

Modifying an intent to share pictures or video takes just two modifications:
Intent shareIntent = ShareCompat.IntentBuilder.from(ShareActivity.this)
   .setText("Hello from Google+ Developer Relations!")
   .setStream(MEDIA_URI)
   .setType(MEDIA_TYPE)
   .getIntent()
   .setPackage("com.google.android.apps.plus");
Here, I changed the type to an appropriate content type for the media being shared (“image/png” for images, “video/mp4” for videos, etc...). Additionally, I told the intent builder that I’m sending the media store URI of the picture that I want to share.

A Rich, Personalized Post

Once users shares text, links, images, or video using share intents, the post on Google+ will include attribution to your application, like shown below.

A Google+ post with text and an image shared from the Google+ Share Intent Demo app.

As you can see in the screenshot, I combined sharing an image with sharing text. You can mix and match setting text with sharing pictures, videos, or links.

If you'd like to add similar functionality to your Android app, just check out the ShareCompat documentation. Happy sharing!

Follow the conversation on Google+.

Posted by Julia Ferraioli, Developer Advocate, Google+

0 comments: