Using Intents in Android
This tutorials describes what Intents are and how to use them in Android. It is based on Eclipse 3.7, Java 1.6 and Android 4.0.4 (Ice Cream Sandwich).
Intents are asynchronous messages which allow Android components to request functionality from other components of the Android system. For example an Activity
can send an Intents to the Android system which starts another Activity
.
Therefore Intents allow to combine loosely coupled components to perform certain tasks.
Intents can be used to signal to the Android system that a certain event has occurred. Other components in Android can register to this event and will get notified.
Intents are instances of the android.content.Intent
class.
Intents are send to the Android system. Depending on how the Intent
was constructed the Android system will run an receiver determination and determine what to do.
An Intent
can also contain data. This data can be used by the receiving component. For example your application can calls via an Intent
a browser component. As data it may send the URL to the browser component.
Android supports explicit and implicit 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.
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
Explicit Intents are typically used within on application as the classes in an application are controlled by the application developer.
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.
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.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.vogella.com"));
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
.
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 call 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.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "News for you!");
startActivity(intent);
The component which receives the Intent
can use the getIntent().getExtras()
method call to get the extra data.
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
}
2. Using Intents to call 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
.
2.2. Calling Sub-Activities for result data
If you need some information from the called Activity
use the startActivityForResult()
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");
startActivityForResult(i, REQUEST_CODE);
}
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.
@Override
public void finish() {
Intent data = new Intent();
data.putExtra("returnKey1", "Swinging on a star. ");
data.putExtra("returnKey2", "You could be better then you are. ");
setResult(RESULT_OK, data);
super.finish();
}
Once the Sub-Activity
finished, the onActivityResult()
method in the calling Activity
will be called.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("returnKey1")) {
Toast.makeText(this, data.getExtras().getString("returnKey1"),
Toast.LENGTH_SHORT).show();
}
}
}
3. Defining Intent Filters
If an Intent
is send to the Android system, it will determine suitable applications for this Intent
. If several components have been registered for this type of Intent
, Android offers the user the choice to open one of them.
This determination is based on IntentFiltes
. An IntentFilter
specifies the types of Intent
that an activity, service, or broadcast receiver can respond to. An IntentFilter
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.
The following will register an Activity
for the Intent
which is triggered when someone wants to open a webpage.
<activity android:name=".BrowserActivitiy"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http"/>
</intent-filter>
</activity>
The following example will register an Activity for the ACTION_SEND
intent for the text/plain
mime type.
<activity
android:name=".ActivityTest"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
If a component does not define Intent
filters, it can only be called by explicit Intents.
3.2. Restrictions as of Android 3.1
As of Android 3.1 the Android system will by default exclude all BroadcastReceiver
from receivingIntents 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).
This is an additional security features as the user can be sure that only the applications he started will receive broadcast Intents.
4. 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.
As said earlier, since Android version 3.1 the Android system will per default exclude allBroadcastReceiver
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).
5. 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 contain the sharing data to it in yourActivity
.
<?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 = (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);
}
6. Finding out if an Intent is available
Sometimes you want to find if an application has registered for a 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.
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;
}
Based on the result you can adjust your application for example you could disable or hide certan menu items.
7. Prerequisites for this tutorial
The following assumes that you have already basic knowledge in Android development. Please check the
Android development tutorial to learn the basics.
8. Tutorial: Explicit intents and data transfer between activities
The following tutorial demonstrates how to use explicit Intents and how to transfer data between twoActivities.
The first Activity
will call the second one via an explicit intent. Once the user select the "Back" button on his phone the first Activity
will receive some hard-coded data from the Sub-Activity
.
Create a new Android application "de.vogella.android.intent.explicit" with the Activity
calledActivityOne.
Change the layout main.xml
to the following.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="60dip"
android:text="First Activity. Press button to call second activity"
android:textSize="20sp" >
</TextView>
<Button
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Calling an intent" >
</Button>
</LinearLayout>
Create the layout "second.xml".
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alignmentMode="alignBounds"
android:columnCount="2"
android:columnOrderPreserved="false"
android:useDefaultMargins="true" >
<TextView
android:layout_gravity="center_horizontal"
android:text="Input 1"
android:textSize="32dip" />
<EditText
android:id="@+id/input1"
android:layout_gravity="fill_horizontal"
android:text="Default" />
<TextView
android:layout_gravity="center_horizontal"
android:text="Input 2"
android:textSize="32dip" />
<EditText
android:id="@+id/input2"
android:layout_gravity="fill_horizontal"
android:text="Default" />
<Button
android:layout_column="1"
android:layout_gravity="right"
android:width="80dp"
android:onClick="onClick"
android:text="Finish" />
</GridLayout>
Declare a new Activity
called ActivityTwo via the AndroidManifest.xml
file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.intent.explicit"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".ActivityOne"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="ActivityTwo"
android:label="ActivityTwo" >
</activity>
</application>
</manifest>
Create the following coding for your two Activities.
package de.vogella.android.intent.explicit;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class ActivityOne extends Activity {
private static final int REQUEST_CODE = 10;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
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");
startActivityForResult(i, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("returnKey1")) {
Toast.makeText(this, data.getExtras().getString("returnKey1"),
Toast.LENGTH_SHORT).show();
}
}
}
}
package de.vogella.android.intent.explicit;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class ActivityTwo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.second);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
String value1 = extras.getString("Value1");
String value2 = extras.getString("Value2");
if (value1 != null && value2 != null) {
EditText text1 = (EditText) findViewById(R.id.input1);
EditText text2 = (EditText) findViewById(R.id.input2);
text1.setText(value1);
text2.setText(value2);
}
}
public void onClick(View view) {
finish();
}
@Override
public void finish() {
Intent data = new Intent();
data.putExtra("returnKey1", "Swinging on a star. ");
data.putExtra("returnKey2", "You could be better then you are. ");
setResult(RESULT_OK, data);
super.finish();
}
}
Run your application. The first will send data to the second Activity
which will be shown on the user interface. If you select back on your phone, the first Activity
will display a Toast
with the data from the second Activity
.
9. Tutorial: Implicit Intents
The following tutorial demonstrates the usage of implicit Intents of the Android System.
Create a new Android application "de.vogella.android.intent.implicit" with a Activity
called "CallIntentsActivity
".
In this example we will use a Spinner
to select the Intent
which should get triggered. For the content of the Spinner
we will define static values.
Create the following "intents.xml" file in the "res/values" folder.
<resources>
<string-array name="intents">
<item>Open Browser</item>
<item>Call Someone</item>
<item>Dial</item>
<item>Show Map</item>
<item>Search on Map</item>
<item>Take picture</item>
<item>Show contacts</item>
<item>Edit first contact</item>
</string-array>
</resources>
Change the main.xml
layout file to the following.
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alignmentMode="alignBounds"
android:columnCount="1" >
<Spinner
android:id="@+id/spinner"
android:layout_gravity="fill_horizontal"
android:drawSelectorOnTop="true"
>
</Spinner>
<Button
android:id="@+id/trigger"
android:onClick="onClick"
android:text="Trigger Intent">
</Button>
</GridLayout>
To be able to use certain intents you need to register then for your application. Maintain the followingAndroidManifest.xml
.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.intent.implicit"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED" >
</uses-permission>
<uses-permission android:name="android.permission.CALL_PHONE" >
</uses-permission>
<uses-permission android:name="android.permission.CAMERA" >
</uses-permission>
<uses-permission android:name="android.permission.READ_CONTACTS" >
</uses-permission>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".CallIntentsActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Change your activity to the following. We will start the new intent with the method startActivityForResult() which allow us to specify a desired result code. Once the intent is finished the method onActivityResult() is called and you can perform actions based on the result of the activity.
package de.vogella.android.intent.implicit;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class CallIntentsActivity extends Activity {
private Spinner spinner;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
R.array.intents, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void onClick(View view) {
int position = spinner.getSelectedItemPosition();
Intent intent = null;
switch (position) {
case 0:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.vogella.com"));
break;
case 1:
intent = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:(+49)12345789"));
break;
case 2:
intent = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:(+49)12345789"));
startActivity(intent);
break;
case 3:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("geo:50.123,7.1434?z=19"));
break;
case 4:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("geo:0,0?q=query"));
break;
case 5:
intent = new Intent("android.media.action.IMAGE_CAPTURE");
break;
case 6:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("content://contacts/people/"));
break;
case 7:
intent = new Intent(Intent.ACTION_EDIT,
Uri.parse("content://contacts/people/1"));
break;
}
if (intent != null) {
startActivity(intent);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
Toast.makeText(this, result, Toast.LENGTH_LONG);
}
}
}
If you start your application you should see an list of buttons and if you press the button, different activities should be performed. Note that you didn't specify any receiving application only the thing that should be done.
10. Tutorial: Registering an IntentFilter
The following example will register a Activity
for the Intent
which is triggered to view a http webpage.
Our application downloads the HTML source of this page and display this in a TextView
.
Create the Android project "de.vogella.android.intent.browserfilter" with the Activity calledBrowserActivity
.
Register your Activity
to the Intent
via the Intent.Action_VIEW
action and the scheme "http" via the following AndroidManifest.xml
. The manifest also declares the permission to access the Internet.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.intent.browserfilter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".BrowserActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
</application>
</manifest>
Change the main.xml
layout file to the following.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView"/>
</LinearLayout>
Install your application. If you now trigger an Intent to open an URL your should be able to select your own component. You can for example trigger this Intent
via the example from the implicit tutorials.
package de.vogella.android.intent.browserfilter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
public class BrowserActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.main);
Intent intent = getIntent();
TextView text = (TextView) findViewById(R.id.textView);
String action = intent.getAction();
if (action != Intent.ACTION_VIEW) {
throw new RuntimeException("Should not happen");
}
Uri data = intent.getData();
URL url;
try {
url = new URL(data.getScheme(), data.getHost(), data.getPath());
BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
while ((line = rd.readLine()) != null) {
text.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you select you component the HTML code should be loaded into your text view.
11. Tutorial: Picking an Image via Intent
The following example shows how to pick an Image from any registered photo application on Android via an Intent.
Create a new Android project called de.vogella.android.imagepick with one Activity calledImagePickActivity.
Change the activity_main.xml
layout file to the following.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="pickImage"
android:text="Button" >
</Button>
<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/icon" >
</ImageView>
</LinearLayout>
Change your Activity class according to the following coding.
package de.vogella.android.imagepick;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class ImagePickActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.result);
}
public void pickImage(View View) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
if (bitmap != null) {
bitmap.recycle();
}
stream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(stream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If you run this application you can select an Image from your Image library on your Android phone and assign it to your ImageView
.
Please help me to support this article:
Thanks
akm
www.cdacians.com