Intents in Android

Share this article

Android, as a system, is designed for different components to work together efficiently. Thus Android provides many services for building loosely coupled components that can effectively communicate.

Intents are basically a message-passing mechanism provided in Android, and are asynchronous in nature. One component can send Intent to another component to request for a particular functionality or feature. To take an example, an email reader application might send an intent to another activity, which might take the user name and password from the user perform user validation.

Types of Intents in Android

Explicit Intent

In explicit intent, the sender on the intent explicitly mentions the component that should receive the intent. This can be done using the Java class identifier.

Implicit Intent

In implicit intent, the sending component does not exactly specify the receiving component, the sending component will just mention the action that needs to be performed. The sending component may optionally send additional URI and data with the intent.

Different components can register themselves for being the receiver of intents by giving and intent filter tag in their AndroidManifest.xml

How to use Intents to call native Android Application

Native Android apps also use intents. You can even pass intents from your application to launch and use some native Android applications, like the dialer or web browser.

Now, we’re going to look at an application in which we will create an activity. In the activity we will take sms text and the number from the user.

Then we will launch the sms application by passing an intent to the Android system. We will pass the number and sms message to the sms application.

Step 1. Creating the Layout and UI.

For this we first create an activity called as LaunchIntentActivity, then we create a layout as follows.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1,2"
>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="2dip"
android:paddingRight="4dip"
android:text="Message Text:"
/>
<EditText android:id="@+id/messageText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="true"
android:editable="true"
android:singleLine="true"
android:layout_weight="1"
/>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="2dip"
android:paddingRight="4dip"
android:text="Recipient Number"
/>
<EditText android:id="@+id/messageNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="true"
android:editable="true"
android:singleLine="true"
android:layout_weight="1"
/>
</TableRow>
</TableLayout>
<Button android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Show Message!"
android:onClick="showMessage"
/>
</LinearLayout>

Here, we have first created a linear layout, added two TextView and two EditText to display to the user, and to take the number and the text of the sms from the user. I have also created a button called as showMessage on click of which showMessage function will be called.

The following is the code for the activity.

package launchIntent.com;

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

public class LaunchIntentActivity extends Activity {
	private EditText messageText;
	private EditText messageNumber;
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		messageText=(EditText)findViewById(R.id.messageText);
		messageNumber=(EditText)findViewById(R.id.messageNumber);
	}
	public void showMessage(View v) {

		String _messageText=messageText.getText().toString();
		String _messageNumber=messageNumber.getText().toString();
				
		Intent sendIntent = new Intent(Intent.ACTION_VIEW);
		sendIntent.setData(Uri.parse("sms:"+_messageNumber));
            sendIntent.putExtra("sms_body", _messageText); 
            startActivity(sendIntent);
	}
}

Step 2. Initialization for the Activity

In the onCreate function, we set the main layout which we created as the content view. Then we have two private members for each of the EditText that we have.

public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		messageText=(EditText)findViewById(R.id.messageText);
		messageNumber=(EditText)findViewById(R.id.messageNumber);
	}

The UI of the Activity will look like this:

intent_app_emulator

Step 3. Sending the Intent

On the click of the Show Message button the showMessage function is called.

public void showMessage(View v) {

		String _messageText=messageText.getText().toString();
		String _messageNumber=messageNumber.getText().toString();
				
		Intent sendIntent = new Intent(Intent.ACTION_VIEW);
		sendIntent.setData(Uri.parse("sms:"+_messageNumber));
            sendIntent.putExtra("sms_body", _messageText); 
            startActivity(sendIntent);
	}

In this we get the values entered by the user and store them in string variables.

Then we create a ACTION_VIEW intent, and pass it the URI as sms:Number the user entered.

In intents we can add extra data which will be passed to the recipient of the Intent. This is done through the putExtra method on the intent. We add the extra data called as sms_body and pass the data which the user entered.

Then we send the intent using the startActivity function and passing it the intent object.
This will launch the sms application with the number and message already pre filled with the values we sent as shown below.

How to catch some native Android action using intents

As stated above, all the events which occur in the Android system are communicated through intents. So you can register your application to be launched when a specific event happens. You can register you activity to service an intent by adding the intent-filter tag under the activity tag in the AndroidManifest.xml.

We are now going to write and activity which will be called whenever a contact is to be sent an sms.

Step. 1 Create the CatchSmsIntent Activity

First we need to create a simple activity which we will register to be launched when a contact is suppose to be smsed.

package catchSmsIntent.com;

import android.app.Activity;
import android.os.Bundle;

public class CatchSmsIntent extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //-----------------------------------
        //Code to handle the sms
        //-----------------------------------
    }
}

Step 2. Add the intent-filter

Open the AndroidManifest.xml file and, under the activity, add the tag to catch the action android.intent.action.SENDTO.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="catchSmsIntent.com"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".CatchSmsIntent"
                  android:label="@string/app_name">
           <intent-filter>
           <action android:name="android.intent.action.MAIN" />
           <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
           <intent-filter>
		<action android:name="android.intent.action.SENDTO" />
		<category android:name="android.intent.category.DEFAULT" />
		<data android:scheme="sms" />
		<data android:scheme="smsto" />
		</intent-filter>
        </activity>

    </application>

</manifest>

When we add this intent filter we register our activity with the android system that our application is to be launched when a contact is supposed to be Text Messaged.

From the contacts, select Text Contact.

This will launch the android application chooser with CatchSmsIntent as also one of the options as shown below.

intents_4

Using Intents to communicate between two specific Activities (Explicit Intents)

As described earlier, explicit intents are intent where you specify the exact receiver of the intent. Hence intents can be used to pass message and data between two activities.

Now we are going to see this in the following program. In this program we are going to create two activities. The first activity creates two EditText to take two numbers from the user. Then it will pass these numbers through an intent which will ask user which operation he wants to perform. The operations supported are add and sub which add or subtract the two numbers respectively.

Step 1. The calling activity

The code for the calling activity is as follows.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class CallingActivity extends Activity {
    /** Called when the activity is first created. */
	private EditText number1;
	private EditText number2;
	private static final int REQUEST_CODE = 10;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        number1=(EditText)findViewById(R.id.number1);
        number2=(EditText)findViewById(R.id.number2);
    }
    public void getOperation(View v) {
		String _number1=number1.getText().toString();
		String _number2=number2.getText().toString();
		Intent i = new Intent(this, CalledActivity.class);
		i.putExtra("number1", _number1);
		i.putExtra("number2", _number2);
		// Set the request code to any code you like, you can identify the
		// callback via this code
		startActivityForResult(i, REQUEST_CODE);
	}
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
			if (data.hasExtra("result")) {
				Toast.makeText(this, data.getExtras().getString("result"),
						Toast.LENGTH_SHORT).show();
			}
		}
	}
}

This activity creates two EditText to take two numbers and one button.

In pressing the button, the function getOperation is called.

public void getOperation(View v) {
		String _number1=number1.getText().toString();
		String _number2=number2.getText().toString();
		Intent i = new Intent(this, CalledActivity.class);
		i.putExtra("number1", _number1);
		i.putExtra("number2", _number2);
		// Set the request code to any code you like, you can identify the
		// callback via this code
		startActivityForResult(i, REQUEST_CODE);
	}

In this function first the values the user entered are taken into variables. Then we have to create intent with the second parameter as CalledActivity.class which is the Java class identifier of the second activity which we will create. This will be the receiver of the intent.
The two numbers are passed to the CalledActivity within the intent using the putExtra method.

Then we call the function startActivityForResult with the intent and a request code. When the second activity has finished servicing the intent then it will call the onActivityResult of the current activity with the same request code as to identify that the returned result is for this intent.

Step 2. The called Activity

The following is the code for the called activity.

package explicitIntents.com;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;


public class CalledActivity extends Activity {
    /** Called when the activity is first created. */
	private EditText operation;
	private String value1;
	private String value2;
	private String result;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calledactivitylayout);
        operation=(EditText)findViewById(R.id.operation);
        
        Bundle extras = getIntent().getExtras();
		if (extras == null) {
			return;
		}
		value1 = extras.getString("number1");
		value2 = extras.getString("number2");
		
    }
    public void setOperation(View v) {
    	
    	String _operation = operation.getText().toString();
    	
    	if( _operation.equals("add") )
    	{
    		int answer  = Integer.parseInt(value1) + Integer.parseInt(value2);
    		result = "" + answer;
    	}
    	else if( _operation.equals("sub") )
    	{
    		int answer  = Integer.parseInt(value1) - Integer.parseInt(value2);
    		result = "" + answer;
    	}
    	// Other operations ........ can be added here
    	    	    	
    	finish();
	}
    
    @Override
	public void finish() {
		Intent data = new Intent();
		data.putExtra("result", result);
		setResult(RESULT_OK, data);
		super.finish();
	}
}

The called activity in the onCreate gets the values passed to it in the intent using the function getIntent().getExtras();

It also sets the layout with one EditText and one button on click of it the function setOperation is called. In this the operation value which the user has entered is taken and appropriate result is stored in the member variable result.

Then the function finish is called which creates a new intent to send the result back to the CallingActivity by calling the setResult and passing the intent to it.

Step 3. Getting the Result

When the called activity returns the function onActivityResult is called with the Request code, result code and the intent.

@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
			if (data.hasExtra("result")) {
				Toast.makeText(this, data.getExtras().getString("result"),
						Toast.LENGTH_SHORT).show();
			}
		}
	}
}

Here we check if the result is OK and the the request code is the one we sent with the intent.

Then we get the result back from the intent using the function data.getExtras().getString("result") and pass it to a Toast to show the result to the user.

This is how explicit intents can be used to pass data and get results between activities.

Conclusion

Android provides a lot of services to build great, flexible applications on top of the its system.

Intents provide applications with an easy and flexible way to pass messages between each other, and activities to create flexible applications which can:

  • Use services of other applications by passing intents to them
  • Provide services to other applications
  • Override the native android applications to perform tasks
  • Pass data between different activities
  • Abbas SuterwalaAbbas Suterwala
    View Author

    Abbas is a software engineer by profession and a passionate coder who lives every moment to the fullest. He loves open source projects and WordPress. When not chilling around with friends he's occupied with one of the following open source projects he's built: Choomantar, The Browser Counter WordPress plugin, and Google Buzz From Admin.

    Android Tutorials
    Share this article
    Read Next
    Get the freshest news and resources for developers, designers and digital creators in your inbox each week