Android SDK: Implement a Share Intent

Android SDK: Implement a Share Intent

Tutorial Details
  • Technology: Android SDK
  • Difficulty: Intermediate
  • Completion Time: 15 - 35 Minutes

This tutorial runs through the basic process of creating a share button, implementing the share Intent, passing your content, and building the chooser list.

Implementing the share Intent allows users of your apps to share content across multiple channels, including email, text messaging, social networking and more. You can give your users a good level of control over how they wish to share your content by letting them select from the list of sharing applications available on their own devices.


Step 1: Start a New Android Project

If you already have an application you want to implement sharing with, you can use it. If not, create a new project in your Android IDE. In Eclipse, choose “File,” “New,” “Project” then “Android Project.” Fill in your project details and click “Finish.” your new app’s details will appear in the workspace.

Creating a New Android Project in Eclipse

Step 2: Choose an Activity to Launch the Share Intent

If you already have an Activity in your Android app that you plan on launching the share Intent from, open it in your IDE’s editor area. Otherwise, you can use the main class for your new app or create a new class, making it an Activity so that you can include a button to launch your sharing Intent. Make your class extend the Activity class and include an “onCreate” method in which you can build your user interface elements.


Step 3: Create a Share Button

You can launch your sharing Intent on any user action, such as pressing an options or context menu item. The following Java code creates an image button, inside the “onCreate” method of the Activity:

ImageButton sharingButton = new ImageButton(this);
sharingButton.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
sharingButton.setImageResource(R.drawable.sharing);

This creates a button based on the Android ImageButton class, which the Activity will need to import. This code refers to an image saved with the file-name “sharing” which is stored the drawable folder of the application resources. You can use your own image and alter the code to reflect its name. Alternatively, you can create a standard button with text rather than an image.


Step 4: Listen for Button Clicks

Depending on which type of button you’re using to launch your Intent, you may need to implement a listener function. For the image button, you can add the following code:

sharingButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
shareIt();
}
});

This code specifies a method for the application to call when users press the share button. By including the code in a dedicated method, you can call on the sharing functionality from multiple locations in your code, such as from the “onContextItemSelected” method for long-presses or the “onOptionsItemSelected” for option menu button presses.


Step 5: Implement the Share Method

Add a new method to your Activity, matching the name specified in your button listener method, as follows:

private void shareIt() {
//sharing implementation here
}

This method will contain the implementation code for sharing content from your app. You can choose to pass parameters to the method if this suits your project.


Step 6: Create a Send Intent

Create the sharing Intent. Add the following Java code inside your sharing method, creating an Intent object with the send action type:

Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
Option List to Appear on Pressing the Share Button

Step 7: Set the Sharing Type

Set a MIME type for the content you’re sharing. This will determine which applications the chooser list presents to your users. Plain text, HTML, images and videos are among the common types to share. The following Java code demonstrates sending plain text:

sharingIntent.setType("text/plain");

This is a flexible option, as you can send plain text reliably through many different channels.

It is possible to target specific applications using the “setType” method, but this can be a risky strategy, potentially causing problems if the user does not have those particular apps installed. By keeping the sharing function as generic as possible, you give your users control over how they want to share your content. Sticking to the standard behaviour for sharing in Android applications also creates an intuitive user experience.


Step 8: Build the Share Content

You can pass various elements of your sharing content to the send Intent, including subject, text / media content, and addresses to copy to in the case of email sharing. This Java code builds a string variable to hold the body of the text content to share:

String shareBody = "Here is the share content body";

You can of course build the content using variables and methods within your application.

Remember that some of your content will not appear when the user chooses certain channels. For example, if you set a subject, it will not appear if the user chooses to share using text messaging, and anything over 140 characters will be cropped if the user chooses Twitter.

Scrolling Through the Chooser List for Sharing a Web page

Step 9: Pass Content to the Intent

Pass your sharing content to the “putExtra” method of the Intent class using the following Java code:

sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);

This code first adds a subject to the sharing content, then adds the text body by referring to the string variable.


Step 10: Create a Chooser

Now that you have defined the content to share when the user presses the share button, you simply have to instruct Android to let the user choose their sharing medium. Add the following code inside your share method:

startActivity(Intent.createChooser(sharingIntent, "Share via"));

This code passes the name of the sharing Intent along with a title to display at the top of the chooser list. This example uses “Share via” which is a standard option you may have seen in existing apps. However, you can choose a title to suit your own application.

When the user chooses an application from the list, your share content will be passed to that application. For example, if the user chooses an email application, any subject you specified will be automatically populated in the subject field. The user will be able to edit the content before sending it if they wish to do so.

The Sharing Content Passed to the Gmail Application

Conclusion

The process of implementing a share Intent in your Android applications is not a complex one. However, the bigger challenge is choosing your sharing content in a way that serves the purpose of your application, while keeping it user-friendly. For example, you can’t share the same content in a text message or tweet that you could send using email. For this reason it’s best to keep your sharing content as general as possible, so that the function will be as effective for Twitter and Facebook as it is for Gmail and email.

Add Comment

Discussion 31 Comments

  1. Junaid says:

    Nice tutorial :)

  2. somyadeep says:

    very useful resource . I m loving it . thanks a ton !!

  3. Invincible says:

    Nice one…will surely give it a try

  4. dduudee says:

    DUDE, LIKE WTF… i landed server times on your pages.
    you got great pictures, great explanations

    BUT I DON”T HAVE TIME TO READ ALL, I WANT THE COMPLETE CODE TO COPY PASTE

    PLEASE PUT ON THE BOTTOM OF EACH TUTORIAL THE COMPLETE CODE

    for those like me.

    I’m sure lots of other ppl would appreciate this

    • silent says:

      Duuuude,

      Don’t be an ass. If you don’t want to scroll through all of it’s text, create a project, copy it. Next time you need the code, just look at your project.

      This code here is for educational purpose. That is why there’s so much text in it.

    • Matt says:

      Just what the world needs… One more clueless cut-n-paste programmer.

      Believe it or not, some of us actually want to understand how and why things work.

  5. deraga says:

    Thank you so much for this tutorial. This has made my work much easier.

    ps. to the guy above, learn how to read before you code eh?

  6. djk says:

    i implemented it already, but facebook sharing is not working. From search on google got the info that facebook app has bug listed officially.
    But now i have to add 1 option facebook to this list dialog, anyone know how can i add it in this dialog?
    thanks in advance.

  7. selva says:

    Hai,

    Really a nice tutorial .I worked it but i wont get the dialog including the options.

    Thanks.

  8. Luiz Verçosa says:

    Thank you for this tutorial! It worked nicely!

  9. Isaac says:

    Nice tutorial!
    Did this on an emulator and it did some things differently, but essentially worked regardless.
    thanks!

  10. Author

    Thanks for the comments guys. Just to follow up on comments about the emulator/ list. The share dialog shows a list reflecting which sharing applications are installed on the device, so on the emulator it might only show a couple, or even jump straight into one, e.g. the messaging application. You really need to test the code on an actual device to see it working normally. You can set your emulator up to run certain sharing apps but it’s a tricky process, in my experience running and testing on an actual device is the safest option.

  11. Dian says:

    Hello!! Thanks for your user-friendly tutorial!

    Is it possible to customize the style of the popping list?
    by a .xml or other method.

    Thanks a lot!

    • Author

      Hi Dian

      Thanks for commenting. I believe you would probably have to implement your own dialog instead of using the default one. Obviously this would involve a lot more work.. To be honest I think keeping to the default chooser makes your apps more intuitively usable anyway, as your users are accustomed to seeing it in the same way for other apps.

      Hope that helps

  12. Great tutorial :D

    Is there a way to know which application the user ended up choosing?

  13. Alex says:

    Hi Sue, do I need any permissions for this to work? I only have the one for internet.
    I get the popup but instead of the list I get ‘No applications can perform this action’.
    Thanks for the tutorial

  14. GD says:

    Which files do the various steps go into? I’m a copy and paster rather than a programmer!

    • Author

      Hi GD

      If you read through the tutorial each step makes it clear where the code goes. It basically all goes into an Activity class, which is the main Java file for your application if you only have one Activity in it.

      • GD says:

        Thanks, I need to also edit the other files that are affected also, e.g. the main.xml needs a corresponding button with the name being called to match up.

      • GD says:

        I got it to work by using the following code. I’ve pasted it below for all those that may be at the stage I was at.

        /* Class My Email Function */

        public class SendEmail extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button share = (Button) findViewById(R.id.button1);
        share.setOnClickListener(new View.OnClickListener()

        {

        @Override
        public void onClick(View Button) {

        Intent it = new Intent(Intent.ACTION_SEND);
        it.putExtra(Intent.EXTRA_EMAIL, “me@abc.com”);
        it.putExtra(Intent.EXTRA_TEXT, “The email body text”);
        it.setType(“text/plain”);
        startActivity(Intent.createChooser(it,
        “Choose Email Client”));

        }
        });

        You need a public class and two public voids in your activity file.
        An onclicklistener
        Also you need to call the name of the button labeled in the main.xml file with
        Button share = (Button) findViewById(R.id.button1);

  15. Neel says:

    Nice set of tutorials.. very useful resource . I m loving it . thanks a lot.

    I have done the sharing thing for text/plain MIME type and it works fine. But how do I implement the same for Facebook or Mail application??

    Please share me your thoughts and comments on this.

    Thanks in advance.

    • Author

      Hi Neel

      Thanks for the feedback. The same code (with plain text) works for all sharing applications on the device including Facebook and Mail. If you’re running the code on an emulator you may not see these listed as the emulator does not normally have those applications installed. Try it on an actual device to see the full list of sharing applications.

      Hope that helps.

      • Kostadin says:

        I’m not using emulator. I’m using Samsung Galaxy S with Android 2.3.4.
        All listed applications in share list accept data. Only Facebook opens empty dialog.

        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, “Линк от BGmaps за Андроид”);
        shareIntent.putExtra(Intent.EXTRA_TEXT, String.format(“%s%s: http://hhhhhh.com/link/29369F84DA0E9B6EC3822678FEF20280“, link.GetBaloon_HeaderString(), link.GetBaloon_DescriptionString()));

    • Author

      Hi Kostadin

      There is a bug in the Facebook app that means, depending on the content of what you’re sharing, it might not always work. I would hope Facebook will eventually fix this bug, but in the meantime you can optionally use the Facebook API if you need to target it specifically. See this page: http://stackoverflow.com/questions/3515198/share-text-on-facebook-from-android-app-via-action-send

      Hope that helps.

  16. nb says:

    Awesome tutorial! Easy to follow and worked perfect. By far the best source for android tutorials

  17. krishna says:

    Nice tutorial. Easy to understand.

  18. Marco says:

    Good tutorial. Works fine with Mail, Twitter, Google+.
    But doesn’t work with Facebook?
    Does anybody know a workaround?

  19. Dom says:

    Is there a way to make this an Stand alone App pulling say Images from a specified gallery on the sd card to share ?

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.