This chapter looks at Intents — probably the most unique and important concept in Android development. Using implicit Intents, it is possible to request an action be performed on a piece of data, enabling Android to determine which application components can best service that request. Broadcast In...
This chapter looks at Intents — probably the most unique and important concept in Android development. Using implicit Intents, it is possible to request an action be performed on a piece of data, enabling Android to determine which application components can best service that request. Broadcast Intents are used to announce events system wide.
Size: 239.38 KB
Language: en
Added: Aug 04, 2014
Slides: 8 pages
Slide Content
Chapter 7
Intents in Android Application
By
Dr. Ramkumar Lakshminarayanan
Introduction
This chapter looks at Intents — probably the most unique and important concept in
Android development. Using implicit Intents, it is possible to request an action be performed
on a piece of data, enabling Android to determine which application components can best
service that request. Broadcast Intents are used to announce events system wide.
Intents
Intents are used as a message-passing mechanism that works both within your application
and between applications. You can use Intents to do the following:
Explicitly start a particular Service or Activity using its class name
Start an Activity or Service to perform an action with (or on) a particular piece of data
Broadcast that an event has occurred
You can use Intents to support interaction among any of the application components
installed on an Android device, no matter which application they're a part of. This turns your
device from a platform containing a collection of independent components into a single,
interconnected system.
One of the most common uses for Intents is to start new Activities, either explicitly (by
specifying the class to load) or implicitly (by requesting that an action be performed on a
piece of data). In the latter case the action does not need to be performed by an Activity
within the calling application.
You can also use Intents to broadcast messages across the system. Applications can
register Broadcast Receivers to listen for, and react to, these Broadcast Intents. This enables
you to create event-driven applications based on internal, system, or third-party application
events.
Android broadcasts Intents to announce system events, such as changes in Internet
connectivity or battery charge levels. The native Android applications, such as the Phone
Dialer and SMS Manager, simply register components that listen for specific Broadcast
Intents — such as "incoming phone call" or "SMS message received" — and react
accordingly. As a result, you can replace many of the native applications by registering
Broadcast Receivers that listen for the same Intents.
Using Intents, rather than explicitly loading classes, to propagate actions — even within
the same application — is a fundamental Android design principle. It encourages the
decoupling of components to allow the seamless replacement of application elements. It also
provides the basis of a simple model for extending an application's functionality.
Using Intents to Launch Activities
The most common use of Intents is to bind your application components and
communicate between them. Intents are used to start Activities, allowing you to create a
workflow of different screens.
To create and display an Activity, call startActivity, passing in an Intent, as follows:
startActivity(mylntent);
The startActivity method finds and starts the single Activity that best matches your Intent.
You can construct the Intent to explicitly specify the Activity class to open, or to
include an action that the target Activity must be able to perform. In the latter case, the run
time will choose an Activity dynamically using a process known as intent resolution.
Android supports explicit and implicit Intents.
Explicit Intents
Explicit Intents explicitly defines the component which should be called by the
Android system, by using the Java class as identifier.
The following shows an explicit Intent. If that Intent is correctly send to the Android
system and the class is accessible, it will start the associated class.
Explicit Intents are typically used within on application as the classes in an
application are controlled by the application developer.
Implicit Intents
Implicit Intents do not directly specify the Android components which should be
called. They specify the action which should be performed and optionally an URI which
should be used for this action.
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
For example the following tells the Android system to view a webpage. Typically the
web browser is registered to this Intent but other component could also register themself to
this event.
If these Intents are send to the Android system it searches for all components which
are registered for the specific action and the data type.
If only one component is found, Android starts this component directly. If several
components are identifier by the Android system, the user will get an selection dialog and can
decide which component should be used for the Intent.
Data Transfer
An implicit Intent contains the Action and optional the URI. The receiving component
can get this information via the getAction() and getData() methods.
Explicit and implicit Intents can also contain additional data. This data can be filled
by the component which creates the Intent. It can and can get extracted by the component
which receives the Intent.
The component which creates the Intent can add data to it via the
overloaded putExtra() method. Extras are key/value pairs; the key is always a String. As
value you can use the primitive data types (int, float,..), String, Bundle, Parceable and
Serializable.
For example you can trigger all components which have been registered to send some
data via the new Intent(Intent.ACTION_SEND) This Intent determines possible receivers via
the type. What is send it defined via the putExtra method. You can use any String as key, the
following uses the keys which are predefined for the ACTION_SEND intent.
The component which receives the Intent can use the getIntent().getExtras() method
call to get the extra data.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.android.com"));
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "News for you!");
startActivity(intent);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
// Get data via the key
String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
// Do something with the data
}
Calling Activities
If you send an Intent to the Android system, Android requires that you tell it to which
type of component your Intent should be send.
To start an Activity use the method startActivity(Intent). This method is defined on
theContext object and available in every Activity object.
If you call an Activity with the startActivity(Intent) method the caller requires no
result from the called Activity.
Calling Sub-Activities for result data
If you need some information from the called Activity use the startActivityForResult()
method.
If you use the startActivityForResult() method then the started Activity is called
a Sub-Activity.
If the Sub-Activity is finished it can send data back to its caller via Intent. This is
done in the finish()method.
public void onClick(View view) {
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
// Set the request code to any code you like, you can identify the
// callback via this code
startActivityForResult(i, REQUEST_CODE);
}
@Override
public void finish() {
// Prepare data intent
Intent data = new Intent();
data.putExtra("returnKey1", "Swinging on a star. ");
data.putExtra("returnKey2", "You could be better then you are. ");
// Activity finished ok, return the data
setResult(RESULT_OK, data);
Once the Sub-Activity finished, the onActivityResult() method in the
calling Activity will be called.
Defining Intent Filters
If an Intents is send to the Android system, it will determine suitable applications for
this Intents. If several components have been registered for this type of Intents, Android
offers the user the choice to open one of them.
This determination is based on IntentFilters. An IntentFilters specifies the types
of Intent that an Activity,Service, or Broadcast Receiver can respond to. An Intent
Filter declares the capabilities of a component. It specifies what an Activity or Service can do
and what types of broadcasts a Receiver can handle. It allows the corresponding component
to receive Intents of the declared type.
IntentFilters are typically defined via the AndroidManifest.xml file.
For BroadcastReceiver it is also possible to define them in coding. An IntentFilters is defined
by its category, action and data filters. It can also contain additional metadata.
If a component does not define an Intent filter, it can only be called by explicit Intent
Example - Register your Activity as Browser
The following code will register an Activity for the Intent which is triggered when
someone wants to open a webpage.
Example - Register your Activity for the Share Intent
The following example will register an Activity for the ACTION_SEND Intent for
the text/plain mime type. If a component does not define an Intent filter, it can only be called
by explicit Intents.
Intents as event triggers
Intents can also be used to send broadcast messages into the Android
system. BroadcastReceivers can register to event and will get notified if such an event is
triggered.
Your application can register to system events, e.g. a new email has arrived, system
boot is complete or a phone call is received and react accordingly.
Since Android version 3.1 the Android system will per default exclude all
BroadcastReceiver from receiving Intents if the corresponding application has never been
started by the user or if the user explicitly stopped the application via the Android menu (in
Manage Application).
Share Intent and ShareActionProvider
As of Android 4.0 you can also add an Action Provider to your ActionBar which
allows to share. For this you have to define a special menu entry and assign an Intent which
contains the sharing data to it in your Activity.
<activity
android:name=".ActivityTest"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
Unfortunately this does not seem to work in the Android emulator, we can test by
deploying in android devices.
Finding out if an Intent is available
Sometimes you want to find if an application has registered for certain Intent. For
example you want to check if a certain receiver is available and if you enable some
functionality in your app.
This can be done via the PackageManager class. The following code checks if an
someone has registered himself for a certain Intent. Construct your Intent as you desired to
trigger it and pass it to the following method.
Based on the result you can adjust your application for example you could disable or
hide certan menu items.
Chapter Summary
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/menu_share"
android:title="Share"
android:showAsAction="ifRoom"
android:actionProviderClass="android.widget.ShareActionProvider" />
<item
android:id="@+id/item1"
android:showAsAction="ifRoom"
android:title="More entries...">
</item>
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mymenu, menu);
// provider is a field in your Activity
provider = (ShareActionProvider) menu.findItem(R.id.menu_share)
.getActionProvider();
setShareIntent();
return true;
}
public void setShareIntent() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Message");
provider.setShareIntent(intent);
}
public static boolean isIntentAvailable(Context ctx, Intent intent) {
final PackageManager mgr = ctx.getPackageManager();
List<ResolveInfo> list =
mgr.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
In this chapter we discussed about important concept in Android development Intents.
Intents can be used implicitly and explicitly. In the next chapter we will see examples of
using intents in the application development.