SlideShare a Scribd company logo
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 = newIntent(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
publicvoidfinish() {
//Prepare data intent
Intentdata= newIntent();
data.putExtra("returnKey1","Swingingona star.");
data.putExtra("returnKey2","Youcouldbe betterthenyouare.");
//Activityfinishedok,returnthe 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 - Registeryour Activity as Browser
The following code will register an Activity for the Intent which is triggered when
someone wants to open a webpage.
@Override
protectedvoid onActivityResult(intrequestCode,intresultCode,Intentdata)
{
if (resultCode==RESULT_OK && requestCode ==REQUEST_CODE) {
if (data.hasExtra("returnKey1")) {
Toast.makeText(this,data.getExtras().getString("returnKey1"),
Toast.LENGTH_SHORT).show();
}
}
}
<activityandroid:name=".BrowserActivitiy"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.VIEW"/>
<categoryandroid:name="android.intent.category.DEFAULT"/>
<data android:scheme="http"/>
Example - Registeryour 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>
<actionandroid:name="android.intent.action.SEND"/>
<categoryandroid:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
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
publicbooleanonCreateOptionsMenu(Menumenu) {
getMenuInflater().inflate(R.menu.mymenu,menu);
//providerisa fieldinyourActivity
provider=(ShareActionProvider) menu.findItem(R.id.menu_share)
.getActionProvider();
setShareIntent();
returntrue;
}
publicvoidsetShareIntent(){
Intentintent=newIntent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,"Message");
provider.setShareIntent(intent);
}
publicstaticbooleanisIntentAvailable(Contextctx,Intentintent) {
final PackageManagermgr= ctx.getPackageManager();
List<ResolveInfo>list=
mgr.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
returnlist.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.

More Related Content

What's hot (20)

PDF
Android App Development 07 : Intent &amp; Share
Anuchit Chalothorn
 
PPTX
Android development session 2 - intent and activity
Farabi Technology Middle East
 
PDF
[Android] Intent and Activity
Nikmesoft Ltd
 
ODP
Android App Development - 02 Activity and intent
Diego Grancini
 
PDF
Intents in Android
ma-polimi
 
PDF
Android: Intent, Intent Filter, Broadcast Receivers
CodeAndroid
 
PDF
Android Lesson 2
Daniela Da Cruz
 
DOCX
CONTROL CLOUD DATA ACCESS PRIVILEGE AND ANONYMITY WITH FULLY ANONYMOUS ATTRIB...
Nexgen Technology
 
PPTX
08.1. Android How to Use Intent (explicit)
Oum Saokosal
 
DOCX
Assistive Technology_Research
Meng Kry
 
PPTX
Androd Listeners
ksheerod shri toshniwal
 
DOCX
Using intents in android
Oum Saokosal
 
DOCX
Exercises
maamir farooq
 
PPTX
Create an other activity lesson 3
Kalluri Vinay Reddy
 
PDF
G04944851
IOSR-JEN
 
PDF
Social Aggregator Paper
Akchay Srivastava
 
PDF
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
IJCSEIT Journal
 
PDF
P01813101103
IOSR Journals
 
PDF
Lab2-android
Lilia Sfaxi
 
PPTX
Notification android
ksheerod shri toshniwal
 
Android App Development 07 : Intent &amp; Share
Anuchit Chalothorn
 
Android development session 2 - intent and activity
Farabi Technology Middle East
 
[Android] Intent and Activity
Nikmesoft Ltd
 
Android App Development - 02 Activity and intent
Diego Grancini
 
Intents in Android
ma-polimi
 
Android: Intent, Intent Filter, Broadcast Receivers
CodeAndroid
 
Android Lesson 2
Daniela Da Cruz
 
CONTROL CLOUD DATA ACCESS PRIVILEGE AND ANONYMITY WITH FULLY ANONYMOUS ATTRIB...
Nexgen Technology
 
08.1. Android How to Use Intent (explicit)
Oum Saokosal
 
Assistive Technology_Research
Meng Kry
 
Androd Listeners
ksheerod shri toshniwal
 
Using intents in android
Oum Saokosal
 
Exercises
maamir farooq
 
Create an other activity lesson 3
Kalluri Vinay Reddy
 
G04944851
IOSR-JEN
 
Social Aggregator Paper
Akchay Srivastava
 
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
IJCSEIT Journal
 
P01813101103
IOSR Journals
 
Lab2-android
Lilia Sfaxi
 
Notification android
ksheerod shri toshniwal
 

Viewers also liked (7)

DOCX
Android views and layouts-chapter4
Dr. Ramkumar Lakshminarayanan
 
DOCX
Android practice of layout in application-chapter6
Dr. Ramkumar Lakshminarayanan
 
DOCX
Android style resource and other resources types-chapter12
Dr. Ramkumar Lakshminarayanan
 
DOCX
Android resources in android-chapter9
Dr. Ramkumar Lakshminarayanan
 
DOCX
Android animation and color state list resources-chapter 10
Dr. Ramkumar Lakshminarayanan
 
DOCX
Android-dialogs in android-chapter14
Dr. Ramkumar Lakshminarayanan
 
Android views and layouts-chapter4
Dr. Ramkumar Lakshminarayanan
 
Android practice of layout in application-chapter6
Dr. Ramkumar Lakshminarayanan
 
Android style resource and other resources types-chapter12
Dr. Ramkumar Lakshminarayanan
 
Android resources in android-chapter9
Dr. Ramkumar Lakshminarayanan
 
Android animation and color state list resources-chapter 10
Dr. Ramkumar Lakshminarayanan
 
Android-dialogs in android-chapter14
Dr. Ramkumar Lakshminarayanan
 
Ad

Similar to Android intents in android application-chapter7 (20)

PPT
Intent, Service and BroadcastReciver (2).ppt
BirukMarkos
 
PPTX
Tk2323 lecture 3 intent
MengChun Lam
 
PDF
Ch5 intent broadcast receivers adapters and internet
Shih-Hsiang Lin
 
PPTX
Data Transfer between activities and Database
faiz324545
 
ODP
Ppt 2 android_basics
Headerlabs Infotech Pvt. Ltd.
 
PDF
Intents are Awesome
Israel Camacho
 
PPTX
Unit - III.pptx
VaishnaviGaikwad67
 
PPTX
W5_Lec09_Lec10_Intents.pptx
ChSalmanSalman
 
PPT
ANDROID
DrMeftahZouai
 
PPTX
learn about Android Extended Intents.pptx
adgeofspace04
 
PPTX
Hello android world
eleksdev
 
PPT
Level 1 &amp; 2
skumartarget
 
PPTX
Data Transfer between Activities & Databases
Muhammad Sajid
 
PPTX
Android - Intents and Filters hgfh gfh.pptx
FarhanGhafoor7
 
PPTX
Intents in Mobile Application Development.pptx
AbinayaDeviC
 
PPTX
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
34ShreyaChauhan
 
PPT
Intents broadcastreceivers
Training Guide
 
PPTX
MAD_Intentuffjgfjjjhgjjgjjggjghggghggh.pptx
himanshunanobhatt
 
PPTX
3-Implicit Intents.pptx
ab2478037
 
PPT
Android overview
Ashish Agrawal
 
Intent, Service and BroadcastReciver (2).ppt
BirukMarkos
 
Tk2323 lecture 3 intent
MengChun Lam
 
Ch5 intent broadcast receivers adapters and internet
Shih-Hsiang Lin
 
Data Transfer between activities and Database
faiz324545
 
Ppt 2 android_basics
Headerlabs Infotech Pvt. Ltd.
 
Intents are Awesome
Israel Camacho
 
Unit - III.pptx
VaishnaviGaikwad67
 
W5_Lec09_Lec10_Intents.pptx
ChSalmanSalman
 
ANDROID
DrMeftahZouai
 
learn about Android Extended Intents.pptx
adgeofspace04
 
Hello android world
eleksdev
 
Level 1 &amp; 2
skumartarget
 
Data Transfer between Activities & Databases
Muhammad Sajid
 
Android - Intents and Filters hgfh gfh.pptx
FarhanGhafoor7
 
Intents in Mobile Application Development.pptx
AbinayaDeviC
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
34ShreyaChauhan
 
Intents broadcastreceivers
Training Guide
 
MAD_Intentuffjgfjjjhgjjgjjggjghggghggh.pptx
himanshunanobhatt
 
3-Implicit Intents.pptx
ab2478037
 
Android overview
Ashish Agrawal
 
Ad

More from Dr. Ramkumar Lakshminarayanan (20)

PPT
IT security awareness
Dr. Ramkumar Lakshminarayanan
 
PPT
Basics of IT security
Dr. Ramkumar Lakshminarayanan
 
PDF
IT Security Awareness Posters
Dr. Ramkumar Lakshminarayanan
 
PPT
Normalisation revision
Dr. Ramkumar Lakshminarayanan
 
PPTX
Windows mobile programming
Dr. Ramkumar Lakshminarayanan
 
PPTX
Concurrency control
Dr. Ramkumar Lakshminarayanan
 
PPT
Web technology today
Dr. Ramkumar Lakshminarayanan
 
PDF
Phonegap for Android
Dr. Ramkumar Lakshminarayanan
 
PDF
Create and Sell Android App (in tamil)
Dr. Ramkumar Lakshminarayanan
 
PDF
Android app - Creating Live Wallpaper (tamil)
Dr. Ramkumar Lakshminarayanan
 
PDF
Android Tips (Tamil)
Dr. Ramkumar Lakshminarayanan
 
PDF
Android Animation (in tamil)
Dr. Ramkumar Lakshminarayanan
 
PDF
Creating List in Android App (in tamil)
Dr. Ramkumar Lakshminarayanan
 
PDF
Single Touch event view in Android (in tamil)
Dr. Ramkumar Lakshminarayanan
 
PDF
Android Application using seekbar (in tamil)
Dr. Ramkumar Lakshminarayanan
 
PDF
Rating Bar in Android Example
Dr. Ramkumar Lakshminarayanan
 
PDF
Creating Image Gallery - Android app (in tamil)
Dr. Ramkumar Lakshminarayanan
 
PDF
Create Android App using web view (in tamil)
Dr. Ramkumar Lakshminarayanan
 
PDF
Hardware Interface in Android (in tamil)
Dr. Ramkumar Lakshminarayanan
 
IT security awareness
Dr. Ramkumar Lakshminarayanan
 
Basics of IT security
Dr. Ramkumar Lakshminarayanan
 
IT Security Awareness Posters
Dr. Ramkumar Lakshminarayanan
 
Normalisation revision
Dr. Ramkumar Lakshminarayanan
 
Windows mobile programming
Dr. Ramkumar Lakshminarayanan
 
Concurrency control
Dr. Ramkumar Lakshminarayanan
 
Web technology today
Dr. Ramkumar Lakshminarayanan
 
Phonegap for Android
Dr. Ramkumar Lakshminarayanan
 
Create and Sell Android App (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Android app - Creating Live Wallpaper (tamil)
Dr. Ramkumar Lakshminarayanan
 
Android Tips (Tamil)
Dr. Ramkumar Lakshminarayanan
 
Android Animation (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Creating List in Android App (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Single Touch event view in Android (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Android Application using seekbar (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Rating Bar in Android Example
Dr. Ramkumar Lakshminarayanan
 
Creating Image Gallery - Android app (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Create Android App using web view (in tamil)
Dr. Ramkumar Lakshminarayanan
 
Hardware Interface in Android (in tamil)
Dr. Ramkumar Lakshminarayanan
 

Recently uploaded (8)

PPTX
Mobile Apps Helping Business Grow in 2025
Infylo Techsolutions
 
PPT
lect 1 Introduction.ppt11112222333344455
212231
 
PDF
💡 Digital Marketing Decoded: Mastering Online Growth Strategies for 2025 🚀
marketingaura24
 
PDF
INTERLINGUAL SYNTACTIC PARSING: AN OPTIMIZED HEAD-DRIVEN PARSING FOR ENGLISH ...
kevig
 
PPT
lec2 wireless transmission exlaining.ppt
212231
 
PPTX
The Intersection of Emoji and NFT. What can be the Consequences?
Refit Global
 
PDF
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
PDF
Building Smart, Scalable Solutions with Android App Development
Brancosoft Private Limited
 
Mobile Apps Helping Business Grow in 2025
Infylo Techsolutions
 
lect 1 Introduction.ppt11112222333344455
212231
 
💡 Digital Marketing Decoded: Mastering Online Growth Strategies for 2025 🚀
marketingaura24
 
INTERLINGUAL SYNTACTIC PARSING: AN OPTIMIZED HEAD-DRIVEN PARSING FOR ENGLISH ...
kevig
 
lec2 wireless transmission exlaining.ppt
212231
 
The Intersection of Emoji and NFT. What can be the Consequences?
Refit Global
 
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
Building Smart, Scalable Solutions with Android App Development
Brancosoft Private Limited
 

Android intents in android application-chapter7

  • 1. 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
  • 2. 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");
  • 3. 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 = newIntent(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 }
  • 4. 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 publicvoidfinish() { //Prepare data intent Intentdata= newIntent(); data.putExtra("returnKey1","Swingingona star."); data.putExtra("returnKey2","Youcouldbe betterthenyouare."); //Activityfinishedok,returnthe data
  • 5. 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 - Registeryour Activity as Browser The following code will register an Activity for the Intent which is triggered when someone wants to open a webpage. @Override protectedvoid onActivityResult(intrequestCode,intresultCode,Intentdata) { if (resultCode==RESULT_OK && requestCode ==REQUEST_CODE) { if (data.hasExtra("returnKey1")) { Toast.makeText(this,data.getExtras().getString("returnKey1"), Toast.LENGTH_SHORT).show(); } } } <activityandroid:name=".BrowserActivitiy" android:label="@string/app_name"> <intent-filter> <actionandroid:name="android.intent.action.VIEW"/> <categoryandroid:name="android.intent.category.DEFAULT"/> <data android:scheme="http"/>
  • 6. Example - Registeryour 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> <actionandroid:name="android.intent.action.SEND"/> <categoryandroid:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/> </intent-filter> </activity>
  • 7. 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 publicbooleanonCreateOptionsMenu(Menumenu) { getMenuInflater().inflate(R.menu.mymenu,menu); //providerisa fieldinyourActivity provider=(ShareActionProvider) menu.findItem(R.id.menu_share) .getActionProvider(); setShareIntent(); returntrue; } publicvoidsetShareIntent(){ Intentintent=newIntent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT,"Message"); provider.setShareIntent(intent); } publicstaticbooleanisIntentAvailable(Contextctx,Intentintent) { final PackageManagermgr= ctx.getPackageManager(); List<ResolveInfo>list= mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); returnlist.size() >0; }
  • 8. 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.