How to Send Simple Data to Other Apps?

In this post, I am going to discuss about sending/sharing simple data to other Android applications installed in your device using Intent.

What is Intent?

Intents are system messages, running around the inside of the device, notifying applications of various events, from hardware state changes (e.g.,an SD card was inserted), to incoming data (e.g., an SMS message arrived),to application events (e.g., your activity was launched from the device’s main menu).

What are we going to develop?

The application which we are going to develop will have couple of buttons. You can send text or images to other applications on clicking those button.

Application screen will look like:

Send_Data_1

Are you not sure about what Intent is?, please take a look at this example – Android Intent example which discusses about basic usage of Intent.

Need of send and receive data

Sending and receiving data (See How to Receive Simple Data from Other Apps?) between applications with intents is most commonly needed for social sharing of content. Intents allow users to share information quickly and easily, using their favorite applications.

Intent – Construction

Constructing a Intent involves five steps, they are:

  • Step 1: Create and instantiate Intent object
    Intent sendIntent = new Intent();
  • Step 2: Specify the action you want the intent to trigger. If you want something to send to other applications, set the intent action as ‘ACTION_SEND’.
    sendIntent.setAction(Intent.ACTION_SEND);
  • Step 3: Set the data you want to send to other applications like Text or Image.
    sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
  • Step 4: Set the type of data you want to send using MIME types
    sendIntent.setType("text/plain");
  • Step 5: Launch the activity.
    startActivity(sendIntent);

Send Text Content

  • The most straightforward and common use of the ACTION_SEND action is sending text content from one activity to another.
    • For example, the built-in Browser app can share the URL of the currently-displayed page as text with any application. This is useful for sharing an article or website with friends via email or social networking.
  • Below is the code to implement this type of sharing:
	Intent sendIntent = new Intent();
		// Set the action to be performed i.e 'Send Data'
		sendIntent.setAction(Intent.ACTION_SEND);
		// Add the text to the intent 
		sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
		// Set the type of data i.e 'text/plain'
		sendIntent.setType("text/plain");
		// Launches the activity; Open 'Text editor' if you set it as default app to handle Text
		startActivity(sendIntent);
  • When the code is executed, it launches the default application (For ex: Text editor) you set for handling text in your device
  • When no default application was set, it shows the chooser with list of applications (as shown below) that are capable of handling text, from which you can select one.
    Send Text
  • Optionally, you can set some standard extras for the intent to send data to Email applications like GMail App: EXTRA_EMAIL, EXTRA_CC, EXTRA_BCC, EXTRA_SUBJECT. If the receiving application is not designed to use them, it simply ignores them.

Send Binary Content

  • Binary data (most commonly Images) is shared using the ACTION_SEND action combined with setting the appropriate MIME type (image/png. image/jpg) and placing the URI to the data in an extra named EXTRA_STREAM.
    	String imagePath = Environment.getExternalStorageDirectory()
    				+ "/pgguru/" + "/share_this_image.png";
    		File imageFileToShare = new File(imagePath);
    		// Get the URI of the image 'share_this_image.png' exists under pgguru right under SD card
    		Uri uri = Uri.fromFile(imageFileToShare);
    		// Set the action to be performed i.e 'Send Data'
    		Intent sendIntent = new Intent(Intent.ACTION_SEND);
    		// Add the URI holding a stream of data  
    		sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
    		// Set the type of data i.e 'image/* which means image/png, image/jpg, image/jpeg etc.,'
    		sendIntent.setType("image/*");
    		// Launches the activity; Open 'Gallery' if you set it as default app to handle Image
    		startActivity(sendIntent);
  • This is commonly used to share an image but can be used to share any type of binary content

Let us start with creating Android application.

You can download source code from here if you don’t want to create Application from scratch, otherwise please proceed with below listings.

Step 1: Create Android Application Project

  • Create new android project [File >> New >> Android Application Project] with project name AndroidShareSimpleData
  • Enter package name as ‘com.prgguru.example’ and activity name as ‘MainActivity’
  • Choose Minimum Required SDK, Target SDK and Compile with (Choose latest SDKs to make sure Facebook SDK will work without any issues). Confused on choosing these options? Take a look at Minimum Required SDK – Target SDK – Compile With post.
  • Click Next button and finally click ‘Finish’ to create project

Step 2: Design screen

Open activity_main.xml and replace it with below code.

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.prgguru.example.MainActivity" >

    <Button
        android:id="@+id/ShareBtnText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:onClick="shareText" 
        android:text="Share Text"/>
    
      <Button
        android:id="@+id/ShareBtnTextChooser"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/ShareBtnText"
        android:onClick="shareTextusingChooser" 
        android:text="Share Text using Chooser"/>
      
       <Button
        android:id="@+id/ShareBtnImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/ShareBtnTextChooser"
        android:onClick="shareImage" 
        android:text="Share Image"/>
       
       <Button
        android:id="@+id/ShareBtnImageChooser"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/ShareBtnImage"
        android:onClick="shareImageusingChooser" 
        android:text="Share Image using Chooser"/>
       
       <Button
        android:id="@+id/ShareBtnMultipleImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/ShareBtnImageChooser"
        android:onClick="shareMultipleImages" 
        android:text="Share Multiple Images"/>
</RelativeLayout>

Step 3: Add resource in strings.xml

Add below string resource in strings.xml present under /res/values folder:

<string name="chooser_text">Choose among them</string>

Step 4: MainActivity.java – Main Class

Open MainActivity.java and replace it with below code. Make sure you update the file paths of Images present in your SD card accordingly in the code.

Each line of code is commented well, if you still have any doubt or question discuss it.

package com.prgguru.example;

import java.io.File;
import java.util.ArrayList;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.View;

public class MainActivity extends ActionBarActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	/**
	 * Method to handle click of button '@+id/ShareBtnText'
	 * @param v
	 */
	public void shareText(View v) {
		Intent sendIntent = new Intent();
		// Set the action to be performed i.e 'Send Data'
		sendIntent.setAction(Intent.ACTION_SEND);
		// Add the text to the intent 
		sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
		// Set the type of data i.e 'text/plain'
		sendIntent.setType("text/plain");
		// Launches the activity; Open 'Text editor' if you set it as default app to handle Text
		startActivity(sendIntent);
	}
	
	/**
	 * Method to handle click of button '@+id/ShareBtnTextChoosert'
	 * @param v
	 */
	public void shareTextusingChooser(View v) {
		Intent sendIntent = new Intent();
		// Set the action to be performed i.e 'Send Data'
		sendIntent.setAction(Intent.ACTION_SEND);
		// Add the text to the intent  
		sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
		// Set the type of data i.e 'text/plain'
		sendIntent.setType("text/plain");
		// Shows chooser (List of Apps) that can handle Text data; You have to choose one among them 
		startActivity(Intent.createChooser(sendIntent,
				getResources().getText(R.string.chooser_text)));
	}
	
	/**
	 * Method to handle click of button '@+id/ShareBtnImage'
	 * @param v
	 */
	public void shareImage(View v) {
		String imagePath = Environment.getExternalStorageDirectory()
				+ "/pgguru/" + "/pic1.png";
		File imageFileToShare = new File(imagePath);
		// Get the URI of the image 'pic1.png' exists under pgguru right under SD card
		Uri uri = Uri.fromFile(imageFileToShare);
		// Set the action to be performed i.e 'Send Data'
		Intent sendIntent = new Intent(Intent.ACTION_SEND);
		// Add the URI holding a stream of data  
		sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
		// Set the type of data i.e 'image/* which means image/png, image/jpg, image/jpeg etc.,'
		sendIntent.setType("image/*");
		// Launches the activity; Open 'Gallery' if you set it as default app to handle Image
		startActivity(sendIntent);
	}
	
	/**
	 * Method to handle click of button '@+id/ShareBtnImageChooser'
	 * @param v
	 */
	public void shareImageusingChooser(View v) {
		String imagePath = Environment.getExternalStorageDirectory()
				+ "/pgguru/" + "/pic1.jpg";
		File imageFileToShare = new File(imagePath);
		Uri uri = Uri.fromFile(imageFileToShare);
		// Set the action to be performed i.e 'Send Data'
		Intent sendIntent = new Intent(Intent.ACTION_SEND);
		// Add the URI holding a stream of data 
		sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
		// Set the type of data i.e 'image/* which means image/png, image/jpg, image/jpeg etc.,'
		sendIntent.setType("image/*");
		//  Shows chooser (List of Apps) that can handle Image; You have to choose one among them 
		startActivity(Intent.createChooser(sendIntent,
				getResources().getText(R.string.chooser_text)));
	}
	
	/**
	 * Method to handle click of button '@+id/ShareBtnMultipleImage'
	 * @param v
	 */
	public void shareMultipleImages(View v) {
		String imagePath1 = Environment.getExternalStorageDirectory()
				+ "/pgguru/" + "/pic1.png";
		String imagePath2 = Environment.getExternalStorageDirectory()
				+ "/pgguru/" + "/pic2.png";
		// Multiple Images' file objects
		File image1FileToShare = new File(imagePath1);
		File image2FileToShare = new File(imagePath2);
		// Get URI of Image's location
		Uri image1URI = Uri.fromFile(image1FileToShare);
		Uri image2URI = Uri.fromFile(image2FileToShare);
		ArrayList<Uri> imageUris = new ArrayList<Uri>();
		imageUris.add(image1URI); // Add your image URIs here
		imageUris.add(image2URI); // Add your image URIs here
		// Set the action to be performed i.e 'Send Multiple Data'
		Intent sendIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
		// Add the URIs holding a stream of data 
		sendIntent.putExtra(Intent.EXTRA_STREAM, imageUris);
		// Set the type of data i.e 'image/* which means image/png, image/jpg, image/jpeg etc.,'
		sendIntent.setType("image/*");
		// Launches the activity; Open 'Gallery' if you set it as default app to handle Image
		startActivity(sendIntent);
	}
	
}

Demo

That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project (How to import android project in eclipse).

Download Source Code

[pglinkadssmall]

If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.

Share

You are always welcome to provide your comments and feedback from comment box.

[pgwriteforus]

[pgfeedback]

Related Articles

Author: Udhay

Share This Post On
468 ad
Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares