Android Share Intent Example for URL, Text or Image


Today I’m going to give you an android share intent example that you can use to enable your app to share contents such as URL or text and Image to other apps installed in your Android device like Facebook, Twitter, Messaging, Instagram, Evernote, etc.. Example uses of this code include:

You are building an app that browses a certain website or URL.

Your app generates an image that a user can share.

android share intent example

DOWNLOAD CODE

Android Share Intent Example Step by Step

Step 1: Prepare XML Layout, we’ll have activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/buttonShareTextUrl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Share Text or URL" />

    <Button
        android:id="@+id/buttonShareImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/buttonShareTextUrl"
        android:text="Share Image" />

</RelativeLayout>

Step 2: Inside the onCreate method of MainActivity.java, put the buttons and OnClickListener handlers.

// listeners of our two buttons
View.OnClickListener handler = new View.OnClickListener() {
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.buttonShareTextUrl:
			shareTextUrl();
			break;

		case R.id.buttonShareImage:
			shareImage();
			break;
		}
	}
};

// our buttons
findViewById(R.id.buttonShareTextUrl).setOnClickListener(handler);
findViewById(R.id.buttonShareImage).setOnClickListener(handler);

Step 3: As you’ve noticed, we have shareTextUrl() method that will be triggered every time the user clicks on the “Share Text or URL” button.

private void shareTextUrl() {
	Intent share = new Intent(android.content.Intent.ACTION_SEND);
	share.setType("text/plain");
	share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

	// Add data to the intent, the receiving app will decide
	// what to do with it.
	share.putExtra(Intent.EXTRA_SUBJECT, "Title Of The Post");
	share.putExtra(Intent.EXTRA_TEXT, "http://www.codeofaninja.com");

	startActivity(Intent.createChooser(share, "Share link!"));
}

Step 4: We also have shareImage() method for sharing images. It is triggered when the user clicks on the “Share Image” button.

private void shareImage() {
	Intent share = new Intent(Intent.ACTION_SEND);

	// If you want to share a png image only, you can do:
	// setType("image/png"); OR for jpeg: setType("image/jpeg");
	share.setType("image/*");

	// Make sure you put example png image named myImage.png in your
	// directory
	String imagePath = Environment.getExternalStorageDirectory()
			+ "/myImage.png";

	File imageFileToShare = new File(imagePath);

	Uri uri = Uri.fromFile(imageFileToShare);
	share.putExtra(Intent.EXTRA_STREAM, uri);

	startActivity(Intent.createChooser(share, "Share Image!"));
}

Complete MainActivity.java code:

package com.example.androidshareurlintent;

import java.io.File;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.app.Activity;
import android.content.Intent;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // listeners of our two buttons
        View.OnClickListener handler = new View.OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {

                case R.id.buttonShareTextUrl:
                    shareTextUrl();
                    break;

                case R.id.buttonShareImage:
                    shareImage();
                    break;
                }
            }
        };

        // our buttons
        findViewById(R.id.buttonShareTextUrl).setOnClickListener(handler);
        findViewById(R.id.buttonShareImage).setOnClickListener(handler);

    }

    // Method to share either text or URL.
    private void shareTextUrl() {
        Intent share = new Intent(android.content.Intent.ACTION_SEND);
        share.setType("text/plain");
        share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

        // Add data to the intent, the receiving app will decide
        // what to do with it.
        share.putExtra(Intent.EXTRA_SUBJECT, "Title Of The Post");
        share.putExtra(Intent.EXTRA_TEXT, "http://www.codeofaninja.com");

        startActivity(Intent.createChooser(share, "Share link!"));
    }

    
    // Method to share any image.
    private void shareImage() {
        Intent share = new Intent(Intent.ACTION_SEND);

        // If you want to share a png image only, you can do:
        // setType("image/png"); OR for jpeg: setType("image/jpeg");
        share.setType("image/*");

        // Make sure you put example png image named myImage.png in your
        // directory
        String imagePath = Environment.getExternalStorageDirectory()
                + "/myImage.png";

        File imageFileToShare = new File(imagePath);

        Uri uri = Uri.fromFile(imageFileToShare);
        share.putExtra(Intent.EXTRA_STREAM, uri);

        startActivity(Intent.createChooser(share, "Share Image!"));
    }

}

Please note that when you use the setType() method, you are enabling Android to filter what apps can share your content. For example, you are sharing a text or URL, the appropriate apps to be shown can be Facebook, Messaging or Email. If you are sharing an image, proper apps can be Instagram, Snapseed or Picasa.

Today’s code output screenshots

android share intent example first run
Main screen.
Android Share Intent - share text or url
Share Text or URL button was touched. Take note of the apps on the list.
android share intent example - User chose to share to Facebook
User chose to share to Facebook
android share image
“Share Image” button was touched. Apps was different on the list.
Android Share Intent - user chose to share with gmail
User chose to share with Gmail. Our image was attached.
Android Share Intent - user chose to share with snapseed
User chose to share to Snapseed.

If you have any suggestions to improve this post, please drop it in the comments section below! I’ll be glad to update this post for further improvement. Thanks for reading our Android Share Intent Example!

,

31 responses to “Android Share Intent Example for URL, Text or Image”

  1. please help!!! there was no image when i try to post in facebook.

    also, can you do take a screenshot and directly share it to facebook only?
    thanks in advance :D

  2. Image file is attached but there is no Image.And in the log the path and the name of the image i selected are correct.what could be the reason.?

  3. i have tried this and i got “Unable to open file foe sharing” … could u please help me, i have added read, write external, and all the necessary permissions but it always fails to send …

  4. Hi @ninjazhai:disqus , nice tutorial. I have a web view app and how can i get text content of the webpage (body of the article on a webpage) and share it via share intent. please help.

  5. I didn’t get the image. it says “sharing failed,please try again”

    i’ve found that there is no image.

    what could be the reason….please resolve this issue…..

  6. I didn’t get the text when I share with facebook and it only shows the url, how to share a text and url in facebook.
    please help me

  7. This article is outdated.
    You get an Intent: Failure when grantUriPermission exception when you try it on devices from Android 6.0.

  8. Additional info:
    According to my last comment:
    The error Failure when grantUriPermission java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.net.Uri.writeToParcel(android.os.Parcel, int) occurs, because there is a bug in some version of Play Services (and not because the article is outdated)

  9. Hi how can i share 2 iamges? i used the cycle for() to put 2 uris into the intent, but it works for only last image, how can i share more than 1 photo?

Leave a Reply

Your email address will not be published. Required fields are marked *