LanguagesXMLWorking with Intents in Android Apps

Working with Intents in Android Apps

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

Android provides a programming construct to request action from another application component: activities, services, content providers, and broadcast receivers. This feature is referred to as an Intent.

Basics

Intents are primarily used in three scenarios, as described in the following sections:

1. Start an Activity

An Activity is referred to a single screen within an application. Each new screen with an application is a different Activity. We can start a new instance of an Activity by calling the startActivity API, which uses Intent as a parameter.

If the intention is to use results from an Activity execution, use the startActivityForResult API. When one uses this API, the caller activity gets the callee Activity’s result on the caller’s onActivityResult callback.

2. Start a Service

A Service runs in the background and does not have a user interface. To start a service, we pass Intent (which has details on the service to start and any necessary data) to the startService() API.

The bindService() API is used to bind an application to a service when working with a client-server interface.

3. Deliver a Broadcast Message

Broadcast messages are messages that any app receives; for example, system booting, device charging started, and so forth. To deliver a broadcast, we use the sendBroadcast API (we also can use the sendOrderedBroadcast or sendStickyBroadcast API)

Types of Intents

Intents are of two types: implicit and explicit.

An implicit intent specifies a general action to perform and does not specify any specific component. A classic example is when you want to share a photo and you get prompted to choose how you want to share (email, Bluetooth, SMS, WhatsApp, and so on).

In an explicit intent, the servicing component is explicitly named by using a fully qualified class name and is used to start a component in the same app.

To create an intent, you need to provide the following:

  1. Action: This describes the action to be performed (for example, view, pick, and the like).
  2. Component Name: This is not required for an implicit intent, but is needed for an explicit intent. It is always required when you want to invoke a service.
  3. Data: This is in the form of a URI that contains the data to be acted upon. For example, if you want to open a downloaded file, the link to the downloaded file will be part of the data. You also need to specify the type of data.
  4. Category: This contains additional data about the type of component that should handle the intent.
  5. Extras: This contains additional information that might be required to complete the action.
  6. Flags: This informs Android OS how to launch an Activity and its treatment after its launch.

Hands On

Let’s create a simple Android application that demonstrates working with Intents.

Fire up Android Studio and Start a new Android Studio Project.

Intent1
Figure 1: Starting Android Studio

Provide IntentsDemo as the Application Name and click Next.

Intent2
Figure 2: Naming the application

On the next screen, leave the default values and click Next.

Intent3
Figure 3: Leaving default values in place

On the “Add an activity to Mobile” page, choose “Blank Activity.” This creates an application with a single Activity.

Intent4
Figure 4: Adding an Activity

We then are prompted to customize the Activity. We will leave the default values unchanged.

Intent5
Figure 5: Again, leaving default values in place

Click Finish to create the project files.

Next, we will add a couple of activities to the project.

Right-click on the layout folder in the Project window and select New -> Activity and choose Blank Activity.

Intent6
Figure 6: Choosing Blank Activity

Name this Activity Scenario1Activity and click Finish to create the Activity.

Intent7
Figure 7: Naming and finishing the Activity creation

Now, add another Activity and name it ReturnScenarioActivity. Click Finish to create it.

Intent8
Figure 8: Adding and naming another Activity

Next, we will add a couple of TextViews and buttons on MainActivity and, in their click event handlers, invoke the two Activities we created.

Note that the second Activity is the one where, upon completion of the Activity, we want to return back to MainActivity.

The XML contents of MainActivity will be as follows:

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

   <TextView android_text="@string/hello_world"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Call Another Activity"
      android:id="@+id/buttonScenario1"
      android:layout_below="@+id/textView"
      android:layout_toRightOf="@+id/textView"
      android:layout_toEndOf="@+id/textView"
      android:layout_marginTop="84dp"
      android:onClick="onButtonScenario1Click" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Call Activity and Return"
      android:id="@+id/buttonCallReturnableActivity"
      android:layout_centerVertical="true"
      android:layout_alignLeft="@+id/buttonScenario1"
      android:layout_alignStart="@+id/buttonScenario1"
      android:onClick="onButtonCallReturnableActivityClick" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceLarge"
      android:text="Return Code"
      android:id="@+id/textViewReturnCode"
      android:layout_below="@+id/buttonCallReturnableActivity"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="62dp" />

</RelativeLayout>

Next, we will add a button to the Scenario1 Activity to complete the Activity when it is clicked.

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

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

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Complete"
      android:id="@+id/buttonComplete"
      android:layout_below="@+id/textView2"
      android:layout_toRightOf="@+id/textView2"
      android:layout_toEndOf="@+id/textView2"
      android:layout_marginTop="115dp" />

</RelativeLayout>

Now we come to the last Activity. Add a button and an editview to specify the return string to the caller Activity.

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

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

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Return to Main Activity"
      android:id="@+id/buttonReturn"
      android:layout_below="@+id/textView"
      android:layout_toRightOf="@+id/textView"
      android:layout_toEndOf="@+id/textView"
      android:layout_marginTop="129dp"
      android:onClick="onButtonReturnClick" />

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText1"
      android:layout_marginTop="48dp"
      android:text="Enter Return value"
      android:layout_below="@+id/textView"
      android:layout_alignRight="@+id/buttonReturn"
      android:layout_alignEnd="@+id/buttonReturn />


</RelativeLayout>

Now, we will start coding wiring up the various events in the various Activities.

Open up Scenario1Activity.java and implement the onBUttonClick API

//Scenario1Activity.java
// we have nothing to do here except call finish()
// to complete the activity
public void onButtonClick(View v) {
   finish();
}

Next, we implement the click event handler for activity_return_scenario.

//Returnscenarioactivity.java
public void onButtonReturnClick(View v) {
   EditText editText1=(EditText)findViewById(R.id.editText1);
   String str = editText1.getText().toString();
   Intent intent=new Intent();
   intent.putExtra("MyMessage",str);
   setResult(50,intent);
   finish();
}

Finally, we wire up everything in the Mainactivity class.

First, we will add two member variables to return the returnCode and the textview object.

//MainActivity.java
public class MainActivity extends ActionBarActivity {
   int returnCode = 0;
   TextView tView;
   @Override

Next, we implement the click event handlers.

//Mainactivity.java
// event handler for the click event for
// Scenario1 button
public void onButtonScenario1Click(View v) {
   Intent intentScenario1 =
      new Intent(this, Scenario1Activity.class);
   this.startActivity(intentScenario1);
}


// event handler for the click event for the
// ReturnableActivity button
public void onButtonCallReturnableActivityClick(View v) {
   Intent intentReturnableActivity =
      new Intent(this, ReturnScenarioActivity.class);
   this.startActivityForResult(intentReturnableActivity, 100);
}

Lastly, we implement the OnActivityResult callback which will be involved when the ReturnScenarioActivity will complete (Remember that we involved this activity using startActivityForResult() instead of startActivity().

//MainActivity.java
@Override
protected void onActivityResult(int requestCode,
      int returnCode, Intent intent) {
   super.onActivityResult(requestCode, returnCode, intent);
   if(returnCode == 50) {
      tView= (TextView) findViewById(R.id.textViewReturnCode);
      tView.setText(intent.getStringExtra("MyMessage"));
   }
}

Our application is now code complete. If you have trouble following along, you can download the sample code from the end of this article.

When we run the application and select SCenario1, the invocation happens but is not interesting.

However, when we launch the other scenario, we can specify a value in the EditView and, when we click the button to complete the activity, that specified value is passed back to the caller activity.

Readers are encouraged to play more with Intents and post their comments below.

Summary

In this article, we learned about Intent basics and using Intents in Android applications. I hope you have found this information useful.

About the Author

Vipul Patel is a technology geek based in Seattle. He can be reached at vipul.patel@hotmail.com. You can visit his LinkedIn profile at https://www.linkedin.com/pub/vipul-patel/6/675/508.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories