2.3: Activities and Implicit Intents

Contents:

In a previous chapter you learned about intents, and how to launch specific activities in your app with explicit intents. In this chapter you'll learn how to send and receive implicit intents, where you declare a general action to perform in the intent, and the system matches your request with a specific activity. Additionally, you'll learn more about Android tasks, and how you can configure your apps to associate new activities with different tasks.

About implicit intents

In an earlier chapter you learned about explicit intents, where you can start one activity from another by specifying the class name of that activity. This is the most basic way to use intents, to start an activity or other app component and pass data to it (and sometimes pass data back.)

A more flexible use of intents is the implicit intent. With implicit intents you do not specify the exact activity (or other component) to run—instead, you include just enough information in the intent about the task you want to perform. The Android system matches the information in your request intent with activities available on the device that can perform that task. If there's only one activity that matches, that activity is launched. If there are multiple matching activities, the user is presented with an app chooser that enables them to pick which app they would like to perform the task. Intent requests matched with apps

For example, you have an app that lists available snippets of video. If the user touches an item in the list, you want to play that video snippet. Rather than implementing an entire video player in your own app, you can launch an intent that specifies the task as "play an object of type video." The Android system then matches your request with an activity that has registered itself to play objects of type video.

Activities register themselves with the system as being able to handle implicit intents with intent filters, declared in the Android manifest. For example, the main activity (and only the main activity) for your app has an intent filter that declares it the main activity for the launcher category. This intent filter is how the Android system knows to start that specific activity in your app when the user taps the icon for your app on the device home screen.

Intent actions, categories, and data

Implicit intents, like explicit intents, are instances of the Intent class. In addition to the parts of an intent you learned about in an earlier chapter (such as the intent data and intent extras), these fields are used by implicit intents:

  • The intent action, which is the generic action the receiving activity should perform. The available intent actions are defined as constants in the Intent class and begin with the word ACTION_. A common intent action is ACTION_VIEW, which you use when you have some information that an activity can show to the user, such as a photo to view in a gallery app, or an address to view in a map app. You can specify the action for an intent in the intent constructor, or with the setAction() method.
  • An intent category, which provides additional information about the category of component that should handle the intent. Intent categories are optional, and you can add more than one category to an intent. Intent categories are also defined as constants in the Intent class and begin with the word CATEGORY_. You can add categories to the intent with the addCategory() method.
  • The data type, which indicates the MIME type of data the activity should operate on. Usually, this is inferred from the URI in the intent data field, but you can also explicitly define the data type with the setType() method.

Intent actions, categories, and data types are used both by the Intent object you create in your sending activity, as well as in the intent filters you define in the Android manifest for the receiving activity. The Android system uses this information to match an implicit intent request with an activity or other component that can handle that intent.

Sending implicit intents

Starting activities with implicit intents, and passing data between those activities, works much the same way as it does for explicit intents:

  1. In the sending activity, create a new Intent object.
  2. Add information about the request to the Intent object, such as data or extras.
  3. Send the intent with startActivity() (to just start the activity) or startActivityforResult() (to start the activity and expect a result back).

When you create an implicit Intent object, you:

  • Do not specify the specific activity or other component to launch.
  • Add an intent action or intent categories (or both).
  • Resolve the intent with the system before calling startActivity() or startActivityforResult().
  • Show an app chooser for the request (optional).

Create implicit Intent objects

To use an implicit intent, create an Intent object as you did for an explicit intent, only without the specific component name.

Intent sendIntent = new Intent();

You can also create the Intent object with a specific action:

Intent sendIntent = new Intent(Intent.ACTION_VIEW);

Once you have an Intent object you can add other information (category, data, extras) with the various Intent methods. For example, this code creates an implicit Intent object, sets the intent action to ACTION_SEND, defines an intent extra to hold the text, and sets the type of the data to the MIME type "text/plain".

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType("text/plain");

Resolve the activity before starting it

When you define an implicit intent with a specific action and/or category, there is a possibility that there won't be any activities on the device that can handle your request. If you just send the intent and there is no appropriate match, your app will crash.

To verify that an activity or other component is available to receive your intent, use the resolveActivity() method with the system package manager like this:

if (sendIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(chooser);
}

If the result of resolveActivity() is not null, then there is at least one app available that can handle the intent, and it's safe to call startActivity(). Do not send the intent if the result is null.

If you have a feature that depends on an external activity that may or may not be available on the device, a best practice is to test for the availability of that external activity before the user tries to use it. If there is no activity that can handle your request (that is, resolveActivity() returns null), disable the feature or provide the user an error message for that feature.

Show the app chooser

To find an activity or other component that can handle your intent requests, the Android system matches your implicit intent with an activity whose intent filters indicate that they can perform that action. If there are multiple apps installed that match, the user is presented with an app chooser that lets them select which app they want to use to handle that intent. Android App Chooser

In many cases the user has a preferred app for a given task, and they will select the option to always use that app for that task. However, if multiple apps can respond to the intent and the user might want to use a different app each time, you can choose to explicitly show a chooser dialog every time. For example, when your app performs a "share this" action with the ACTION_SEND action, users may want to share using a different app depending on the current situation.

To show the chooser, you create a wrapper intent for your implicit intent with the createChooser() method, and then resolve and call startActivity() with that wrapper intent. The createChooser() method also requires a string argument for the title that appears on the chooser. You can specify the title with a string resource as you would any other string.

For example:

// The implicit Intent object
Intent sendIntent = new Intent(Intent.ACTION_SEND);
// Always use string resources for UI text.
String title = getResources().getString(R.string.chooser_title);
// Create the wrapper intent to show the chooser dialog.
Intent chooser = Intent.createChooser(sendIntent, title);
// Resolve the intent before starting the activity
if (sendIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(chooser);
}

Receiving implicit intents

If you want an activity in your app to respond to implicit intents (from your own app or other apps), declare one or more intent filters in the Android manifest. Each intent filter specifies the type of intents it accepts based on the intent's action, data, and category. The system will deliver an implicit intent to your app component only if that intent can pass through one of your intent filters.

Note: An explicit intent is always delivered to its target, regardless of any intent filters the component declares. Conversely, if your activities do not declare any intent filters, they can only be launched with an explicit intent.

Once your activity is successfully launched with an implicit intent you can handle that intent and its data the same way you did an explicit intent, by:

  1. Getting the Intent object with getIntent().
  2. Getting intent data or extras out of that intent.
  3. Performing the task the intent requested.
  4. Returning data to the calling activity with another intent, if needed.

Intent filters

Define intent filters with one or more <intent-filter> elements in the app's manifest file, nested in the corresponding <activity> element. Inside <intent-filter>, specify the type of intents your activity can handle. The Android system matches an implicit intent with an activity or other app component only if the fields in the Intent object match the intent filters for that component.

An intent filter may contain these elements, which correspond to the fields in the Intent object described above:

  • <action>: The intent action.
  • <data>: The type of data accepted, including the MIME type or other attributes of the data URI (such as scheme, host, port, path, and so no).
  • <category>: The intent category.

For example, the main activity for your app includes this <intent-filter> element, which you saw in an earlier chapter:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

This intent filter has the action MAIN and the category LAUNCHER. The <action> element specifies that this is the "main" entry point to the application. The <category> element specifies that this activity should be listed in the system's application launcher (to allow users to launch this activity). Only the main activity for your app should have this intent filter.

Here's another example for an implicit intent to share a bit of text. This intent filter matches the implicit intent example from the previous section:

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

You can specify more than one action, data, or category for the same intent filter, or have multiple intent filters per activity to handle different kinds of intents.

The Android system tests an implicit intent against an intent filter by comparing the parts of that intent to each of the three intent filter elements (action, category, and data). The intent must pass all three tests or the Android system won't deliver the intent to the component. However, because a component may have multiple intent filters, an intent that does not pass through one of a component's filters might make it through on another filter.

Actions

An intent filter can declare zero or more <action> elements for the intent action. The action is defined in the name attribute, and consists of the string "android.intent.action." plus the name of the intent action, minus the ACTION_ prefix. So, for example, an implicit intent with the action ACTION_VIEW matches an intent filter whose action is android.intent.action.VIEW.

For example, this intent filter matches either ACTION_EDIT and ACTION_VIEW:

<intent-filter>
    <action android:name="android.intent.action.EDIT" />
    <action android:name="android.intent.action.VIEW" />
    ...
</intent-filter>

To get through this filter, the action specified in the incoming Intent object must match at least one of the actions. You must include at least one intent action for an incoming implicit intent to match.

Categories

An intent filter can declare zero or more <category> elements for intent categories. The category is defined in the name attribute, and consists of the string "android.intent.category." plus the name of the intent category, minus the CATEGORY prefix.

For example, this intent filter matches either CATEGORY_DEFAULT and CATEGORY_BROWSABLE:

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

Note that all activities that you want to accept implicit intents must include the android.intent.category.DEFAULT intent-filter. This category is applied to all implicit Intent objects by the Android system.

Data

An intent filter can declare zero or more <data> elements for the URI contained in the intent data. As the intent data consists of a URI and (optionally) a MIME type, you can create an intent filter for various aspects of that data, including:

  • URI Scheme
  • URI Host
  • URI Path
  • Mime type

For example, this intent filter matches data intents with a URI scheme of http and a MIME type of either "video/mpeg" or "audio/mpeg".

<intent-filter>
    <data android:mimeType="video/mpeg" android:scheme="http" />
    <data android:mimeType="audio/mpeg" android:scheme="http" />
    ...
</intent-filter>

Sharing data with ShareCompat.IntentBuilder

Share actions are an easy way for users to share items in your app with social networks and other apps. Although you can build a share action in your own app using implicit intents with the ACTION_SEND action, Android provides the ShareCompat.IntentBuilder helper class to easily implement sharing in your app.

Note: For apps that target Android releases after API 14, you can use the ShareActionProvider class for share actions instead of ShareCompat.IntentBuilder. The ShareCompat class is part of the V4 support library, and allows you to provide share actions in apps in a backward-compatible fashion. ShareCompat provides a single API for sharing on both old and new Android devices. You'll learn more about the Android support libraries in a later chapter.

With the ShareCompat.IntentBuilder class you do not need to create or send an implicit intent for the share action. Use the methods in ShareCompat.IntentBuilder to indicate the data you want to share as well as any additional information. Start with the from() method to create a new intent builder, add other methods to add more data, and end with the startChooser() method to create and send the intent. You can chain the methods together like this:

ShareCompat.IntentBuilder
    .from(this)         // information about the calling activity
    .setType(mimeType)  // mime type for the data
    .setChooserTitle("Share this text with: ") //title for the app chooser
    .setText(txt)       // intent data
    .startChooser();    // send the intent

Managing tasks and activities

In a previous chapter you learned about tasks and the back stack, in which the task for your app contains its own stack for the activities the user has visited while they use your app. As the user navigates around your app, activity instances for that task are pushed and popped from the stack for that task.

Most of the time the user's navigation from activity to activity and back again through the stack is straightforward. Depending on the design and navigation of your app there may be complications, especially with activities that are started from other apps and other tasks.

For example, say you have an app with three activities: A, B, and C. A launches B with an intent, and B launches C. C, in turn sends an intent to launch A. In this case the system creates a second instance of A on the top of the stack, rather than bringing the already-running instance to the foreground. Depending on how you implement your activities, the two instances of A can get out of sync and provide a confusing experience for the user as they navigate back through the stack. Multiple activity instances in the same task

Or, say your activity C can be launched from a second app with an implicit intent. The user runs the second app, which has its own task and its own back stack. If that app uses an implicit intent to launch your activity C, a new instance of C is created and placed on the back stack for that second app's task. Your app still has its own task, its own back stack, and its own instance of C. Multiple activity instances in different tasks

Much of the time the Android's default behavior for tasks and activities works fine and you don't have to worry about how your activities are associated with tasks, or how they exist in the back stack. If you want to change the normal behavior, Android provides a number of ways to manage tasks and the activities within those tasks, including:

  • Activity launch modes, to determine how an activity should be launched.
  • Task affinities, which indicate which task a launched activity belongs to.

Activity Launch Modes

Use activity launch modes to indicate how new activities should be treated when they're launched—that is, if they should be added to the current task, or launched into a new task. Define launch modes for the activity with attributes on the <activity> element of the Android manifest, or with flags set on the intent that starts that activity.

Activity attributes

To define a launch mode for an activity add the android:launchMode attribute to the <activity> element in the Android manifest. This example uses a launch mode of "standard", which is the default.

<activity
   android:name=".SecondActivity"
   android:label="@string/activity2_name"
   android:parentActivityName=".MainActivity"
   android:launchMode="standard">
   ...
</activity>

There are four launch modes available as part of the <activity> element:

  • "standard" (the default): New activities are launched and added to the back stack for the current task. An activity can be instantiated multiple times, a single task can have multiple instances of the same activity, and multiple instances can belong to different tasks.
  • "singleTop": If an instance of an activity exists at the top of the back stack for the current task and an intent request for that activity arrives, Android routes that intent to the existing activity instance rather than creating a new instance. A new activity is still instantiated if there is an existing activity anywhere in the back stack other than the top.
  • "singleTask": When the activity is launched the system creates a new task for that activity. If another task already exists with an instance of that activity, the system routes the intent to that activity instead.
  • "singleInstance": Same as single task, except that the system doesn't launch any other activities into the task holding the activity instance. The activity is always the single and only member of its task.

The vast majority of apps will only use the standard or single top launch modes. See the launchMode attribute documentation for more detailed information on launch modes.

Intent flags

Intent flags are options that specify how the activity (or other app component) that receives the intent should handle that intent. Intent flags are defined as constants in the Intent class and begin with the word FLAG_. You add intent flags to an Intent object with setFlag() or addFlag().

Three specific intent flags are used to control activity launch modes, either in conjunction with the launchMode attribute or in place of it. Intent flags always take precedence over the launch mode in case of conflicts.

  • FLAG_ACTIVITY_NEW_TASK: start the activity in a new task. This is the same behavior as the singleTask launch mode.
  • FLAG_ACTIVITY_SINGLE_TOP: if the activity to be launched is at the top of the back stack, route the intent to that existing activity instance. Otherwise create a new activity instance. This is the same behavior as the singleTop launch mode.
  • FLAG_ACTIVITY_CLEAR_TOP: If an instance of the activity to be launched already exists in the back stack, destroy any other activities on top of it and route the intent to that existing instance. When used in conjunction with FLAG_ACTIVITY_NEW_TASK, this flag locates any existing instances of the activity in any task and brings it to the foreground.

See the Intent class for more information about other available intent flags.

Handle new intents

When the Android system routes an intent to an existing activity instance, the system calls the onNewIntent() callback method (usually just before the onResume() method). The onNewIntent() method includes an argument for the new intent that was routed to the activity. Override the onNewIntent() method in your class to to handle the information from that new intent.

Note that the getIntent() method—to get access to the intent that launched the activity—always retains the original intent that launched the activity instance. Call setIntent() in the onNewIntent() method:

@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    // Use the new intent, not the original one
    setIntent(intent);
}

Any call to getIntent() after this returns the new intent.

Task Affinities

Task affinities indicate which task an activity prefers to belong to when that activity instance is launched. By default all activities belong to the app that launched them. Activities from outside an app launched with implicit intents belong to the app that sent the implicit intent.

To define a task affinity, add the android:taskAffinity attribute to the <activity> element in the Android manifest. The default task affinity is the package name for the app (declared in . The new task name should be unique and different from the package name. This example uses "com.example.android.myapp.newtask" for the affinity name.

<activity
   android:name=".SecondActivity"
   android:label="@string/activity2_name"
   android:parentActivityName=".MainActivity"
   android:taskAffinity="com.example.android.myapp.newtask">
   ...
</activity>

Task affinities are often used in conjunction with the singleTask launch mode or the FLAG_ACTIVITY_NEW_TASK intent flag to place a new activity in its own named task. If the new task already exists, the intent is routed to that task and that affinity.

Another use of task affinities is reparenting, which enables a task to move from the activity in which it was launched to the activity it has an affinity for. To enable task reparenting, add a task affinity attribute to the <activity> element and set android:allowTaskReparenting to true.

<activity
   android:name=".SecondActivity"
   android:label="@string/activity2_name"
   android:parentActivityName=".MainActivity"
   android:taskAffinity="com.example.android.myapp.newtask"
   android:allowTaskReparenting="true" >
   ...
</activity>

The related exercises and practical documentation is in Android Developer Fundamentals: Practicals.

Learn More

results matching ""

    No results matching ""