How to Receive Simple Data from Other Apps?

In this post, I am going to discuss about receiving simple data from 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 handle the incoming text or image and display them accordingly.

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 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.
  • Just as your application can send data (See How to Send Simple Data to Other Apps?) to other applications, so too can it easily receive data from other applications.
  • Just imagine how users interact with your application, and what data types you want to receive from other applications (like Text or Image or even other binary data).
    • For example, a social networking application would likely be interested in receiving text content, like an interesting web URL, from another app. The Google+ and Facebook Android applications accept both text and single or multiple images. With this app, a user can easily start a new Google+ or Facebook post with photos from the Android Gallery app. Sounds interesting right??

Update Your Manifest

  • Intent filters instruct the system what intents an application component is willing to accept.
  • Similar to how you constructed an intent with action ACTION_SEND in the Sending Simple Data, you create intent filters in order to be able to receive intents with this action.
  • You define an intent filter in your manifest, using the element <intent-filter>. For example, if your application handles receiving text content, a single image of any type, or multiple images of any type, your manifest would look like:
     
    <activity android:name=".MainActivity">
    <!-- Added intent filter for handling incoming Texts, Single and Multiple Images - Starts here  -->                   
                <intent-filter>
                    <action android:name="android.intent.action.SEND" />
    
                    <category android:name="android.intent.category.DEFAULT" />
    
                    <data android:mimeType="text/plain" />
                </intent-filter>
                
                <intent-filter>
                    <action android:name="android.intent.action.SEND" />
    
                    <category android:name="android.intent.category.DEFAULT" />
    
                    <data android:mimeType="image/*" />
                </intent-filter>
                
                <intent-filter>
                    <action android:name="android.intent.action.SEND_MULTIPLE" />
    
                    <category android:name="android.intent.category.DEFAULT" />
    
                    <data android:mimeType="image/*" />
              
                </intent-filter>
       <!-- Added intent filter for handling incoming Texts, Single and Multiple Images - Ends here -->
    </activity>
    
  • When another application tries to share text or single image or multiple images by constructing an intent and passing it to startActivity(), your application will be listed as an option in the intent chooser.
  • When User selects your application from the chooser, .MainActivity activity will be launched. It is up to your application on how to handle the incoming data.

Handle the Incoming Text Content
Get the appropriate EXTRA from Intent (It is going to be ‘TEXT’ here) and handle it according to your need:

	private void handleSendText(Intent intent) {
		// Get the text from intent
		String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
		// When Text is not null
		if (sharedText != null) {
			// Show the text as Toast message
			Toast.makeText(this, sharedText, Toast.LENGTH_LONG).show();
		}
	}

Handle the Incoming Binary Content

Get the appropriate EXTRA from Intent (It is going to be ‘STREAM’ here) and handle it according to your need:

	private void handleSendImage(Intent intent) {
		// Get the image URI from intent
		Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
		// When image URI is not null
		if (imageUri != null) {
			// Update UI to reflect image being shared
			imageView.setImageURI(imageUri);
		} else{
			Toast.makeText(this, "Error occured, URI is invalid", Toast.LENGTH_LONG).show();
		}
	}

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 AndroidReceiverData
  • 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.guru.example.MainActivity" >

    <TextView
        android:id="@+id/sentText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <ImageView
        android:id="@+id/sentImage"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/sentText"
        android:layout_centerHorizontal="true" >
    </ImageView>

</RelativeLayout>

Step 3: Update Android Manifest

Add intent filters for handling Text and Single image in Manifest:

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <!-- Added intent filter for handling incoming Texts, Single and Multiple Images - Starts here  -->                   
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="text/plain" />
            </intent-filter>
            
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="image/*" />
            </intent-filter>
                    
            <!-- Added intent filter for handling incoming Texts, Single and Multiple Images - Ends here -->
        </activity>

Step 4: MainActivity.java – Main Class

Open MainActivity.java and replace it with below code.

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

package com.guru.example;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	private ImageView imageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageView = (ImageView) findViewById(R.id.sentImage);
		// Get the intent that started this activity
		Intent intent = getIntent();
		// Get the action of the intent
		String action = intent.getAction();
		// Get the type of intent (Text or Image)
		String type = intent.getType();
		// When Intent's action is 'ACTION+SEND' and Tyoe is not null
		if (Intent.ACTION_SEND.equals(action) && type != null) {
			// When tyoe is 'text/plain'
			if ("text/plain".equals(type)) {
				handleSendText(intent); // Handle text being sent
			} else if (type.startsWith("image/")) { // When type is 'image/*'
				handleSendImage(intent); // Handle single image being sent
			}
		}

	}
	
	/**
	 * Method to hanlde incoming text data
	 * @param intent
	 */
	private void handleSendText(Intent intent) {
		// Get the text from intent
		String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
		// When Text is not null
		if (sharedText != null) {
			// Show the text as Toast message
			Toast.makeText(this, sharedText, Toast.LENGTH_LONG).show();
		}
	}
	
	/**
	 * Method to handle incoming Image 
	 * @param intent
	 */
	private void handleSendImage(Intent intent) {
		// Get the image URI from intent
		Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
		// When image URI is not null
		if (imageUri != null) {
			// Update UI to reflect image being shared
			imageView.setImageURI(imageUri);
		} else{
			Toast.makeText(this, "Error occured, URI is invalid", Toast.LENGTH_LONG).show();
		}
	}
}

Step 5: Add permission in Android Manifest

Add read and write permissions in Android Manifest to read/write Image from/to SD card.

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

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: Android Guru

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