0% found this document useful (0 votes)
18 views107 pages

Unit III

The document provides an overview of Android Intents, which are used to facilitate communication between activities in an Android application. It explains how to create and invoke intents, the various actions and data pairs that can be used, and includes examples of standard actions such as dialing a phone number or viewing a webpage. Additionally, it covers secondary attributes of intents and provides code snippets for practical implementation in Android applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views107 pages

Unit III

The document provides an overview of Android Intents, which are used to facilitate communication between activities in an Android application. It explains how to create and invoke intents, the various actions and data pairs that can be used, and includes examples of standard actions such as dialing a phone number or viewing a webpage. Additionally, it covers secondary attributes of intents and provides code snippets for practical implementation in Android applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

12

Android
Intents
Victor Matos
Cleveland State University

Notes are based on:


Android Developers
http://developer.android.com/index.html
12. Android – Intents

Intents
Android Activities
An Android application could include any number of activities.

• An activity uses the setContentView(...) method to expose (usually) a


single UI from which a number of actions could be performed.

• Activities are independent of each other; however they usually


cooperate exchanging data and actions.

• Typically, one of the activities is designated as the first one (main) that
should be presented to the user when the application is launched.

• Moving from one activity to another is accomplished by asking the


current activity to execute an intent.
• Activities interact with each other in an asynchronous mode.

2
12. Android – Intents

Intents
Android Activities
Android Application

Main Activity

results
intents
Sub-Activity-1

Sub-Activity-n

extras

3
12. Android – Intents

Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html

Intents are invoked using the following options

startActivity (intent) launches an Activity

sendBroadcast (intent) sends an intent to any interested


BroadcastReceiver components

startService(intent) communicate with a background Service.


or
bindService(intent, …)

4
12. Android – Intents

Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html

The main arguments of an Intent are:

1. Action The built-in action to be performed, such


as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, …
or user-created-activity
2. Data The primary data to operate on, such as a phone
number to be called (expressed as a Uri).

Intent: { action + data }

Activity-1 Activity-2
Optional results
5
12. Android – Intents

Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html

Typically an intent is called as follows:

Intent myActivity = new Intent (action, data);

startActivity (myActivity);

Primary data (as an URI)


tel://
http://
Built-in or sendto://
user-created
activity

6
12. Android – Intents

Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html

Examples of action/data pairs are:

ACTION_DIAL tel:123
Display the phone dialer with the given number filled in.

ACTION_VIEW http://www.google.com
Show Google page in a browser view. Note how the VIEW action does what is considered the
most reasonable thing for a particular URI.

ACTION_EDIT content://contacts/people/2
Edit information about the person whose identifier is "2".

ACTION_VIEW content://contacts/people/2
Used to start an activity to display 2-nd person.

ACTION_VIEW content://contacts/ people/


Display a list of people, which the user can browse through. Selecting a particular
person to view would result in a new intent
7
12. Android – Intents

Intents
Built-in Standard Actions
List of standard actions that Intents can use for launching activities (usually through
startActivity(Intent).

ACTION_MAIN ACTION_ANSWER
ACTION_VIEW ACTION_INSERT
ACTION_ATTACH_DATA ACTION_DELETE
ACTION_EDIT ACTION_RUN
ACTION_PICK ACTION_SYNC
ACTION_CHOOSER ACTION_PICK_ACTIVITY
ACTION_GET_CONTENT ACTION_SEARCH
ACTION_DIAL ACTION_WEB_SEARCH
ACTION_CALL ACTION_FACTORY_TEST
ACTION_SEND
ACTION_SENDTO

8
12. Android – Intents

Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html

Example

Display the phone dialer with the given number filled in.

Intent myActivity2 = new Intent (Intent.ACTION_DIAL,


Uri.parse( "tel:555-1234"));
startActivity(myActivity2);

9
12. Android – Intents

Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html

Intents - Secondary Attributes


In addition to the primary action/data attributes, there are a
number of secondary attributes that you can also include
with an intent, such as:
1. Category 2. Components
3. Type 4. Extras

Example: Doing a Google search looking for golf clubs

Intent intent = new Intent (Intent.ACTION_WEB_SEARCH );

intent.putExtra(SearchManager.QUERY,
"straight hitting golf clubs");

startActivity(intent); Secondary data

Apparently the Google answer is ‘none’ 10


12. Android – Intents

Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html

Intents - Secondary Attributes

Example: Sending a text message (using extra attributes)

Intent intent = new Intent( Intent.ACTION_SENDTO,


Uri.parse("sms://"));

intent.putExtra("address", "555-1234");
intent.putExtra("sms_body", "remember to buy bread and milk");

startActivity(intent);

“address”, “sms_body” are keywords 11


12. Android – Intents

Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html

Intents - Secondary Attributes

Example: Showing Pictures (using extra attributes)

Intent myIntent = new Intent();

myIntent.setType("image/pictures/*");
myIntent.setAction(Intent.ACTION_GET_CONTENT);

startActivity(myIntent);

12
12. Android – Intents

Intents
1. A Complete Example: Activity1 displays an interface to accept a phone number and
requests (built-in) Activity2 to make the call.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/label1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff0000cc"
android:text="This is Activity1"
android:textStyle="bold"
android:textSize="20sp" />
<EditText
android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="54px"
android:text="tel:555-1234"
android:textSize="18sp" />

<Button
android:id="@+id/btnCallActivity2"
android:layout_width="149px"
android:layout_height="wrap_content"
android:text="Make Phone Call"
android:textStyle="bold" />
</LinearLayout>
13
12. Android – Intents

Intents
1. A Complete Example: Activity1 displays an interface to accept a phone number and
requests (built-in) Activity2 to make the call.

14
12. Android – Intents

Intents
1. A Complete Example: Activity1 displays an interface to accept a phone number and
requests (built-in) Activity2 to make the call.
//IntentDemo1_Intent: making a phone call
package cis493.intents;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class IntentDemo1 extends Activity {


TextView label1;
EditText text1;
Button btnCallActivity2;

15
12. Android – Intents

Intents
1. A Complete Example: Activity1 displays an interface to accept a phone number and
requests (built-in) Activity2 to make the call.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {

setContentView(R.layout.main);
label1 = (TextView)findViewById(R.id.label1);
text1 = (EditText)findViewById(R.id.text1);

btnCallActivity2 = (Button)findViewById(R.id.btnCallActivity2);
btnCallActivity2.setOnClickListener(new ClickHandler());
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}//onCreate

16
12. Android – Intents

Intents
1. A Complete Example: Activity1 displays an interface to accept a phone number and
requests (built-in) Activity2 to make the call.
) private class ClickHandler implements OnClickListener {
@Override
public void onClick(View v) {
try {
// myActivity2 places a phone call
// for ACTION_CALL or ACTION_DIAL
// use 'tel:' formatted data: "tel:555-1234"
// for ACTION_VIEW use data: "http://www.youtube.com"
// (you also need INTERNET permission - see Manifest)

String myData = text1.getText().toString();


Intent myActivity2 = new Intent(Intent.ACTION_DIAL,
Uri.parse(myData));
startActivity(myActivity2);
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}//onClick
}//ClickHandler
17
}//IntentDemo1
12. Android – Intents

Intents
1. A Complete Example: Activity1 displays an interface to accept a phone number and
requests (built-in) Activity2 to make the call.

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cis493.intents"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".IntentDemo1“
android:label="@string/app_name">
<intent-filter> Action/category
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>

18
12. Android – Intents

Intents
Built-in Standard Broadcast Actions
List of standard actions that Intents can use for receiving broadcasts (usually
through registerReceiver(BroadcastReceiver, IntentFilter) or a <receiver> tag
in a manifest).

ACTION_TIME_TICK
ACTION_TIME_CHANGED
ACTION_TIMEZONE_CHANGED
ACTION_BOOT_COMPLETED
ACTION_PACKAGE_ADDED
ACTION_PACKAGE_CHANGED
ACTION_PACKAGE_REMOVED
ACTION_UID_REMOVED
ACTION_BATTERY_CHANGED

19
12. Android – Intents

Intents
More Examples: Using Standard Actions

Call Immediately
Modify the complete example1 replacing
the method ‘ClickHandler’ with
the following code

String myData = "tel:555-1234";

Intent myActivity2 = new Intent(Intent.ACTION_CALL,


Uri.parse(myData));

startActivity(myActivity2);

Needs Permission:
<uses-permission android:name="android.permission.CALL_PHONE" />
20
12. Android – Intents

Intents
More Examples: Using Standard Actions

Show all your Contacts


Modify the complete example1 replacing
the method ‘ClickHandler’ with
the following code

String myData = "content://contacts/people/";

Intent myActivity2 = new Intent(Intent.ACTION_VIEW,


Uri.parse(myData));

startActivity(myActivity2);

21
12. Android – Intents

Intents
More Examples: Using Standard Actions

Show a Particular Contact (ID = 2)


Modify the complete example1 replacing
the method ‘ClickHandler’ with
the following code

String myData = "content://contacts/people/2";

Intent myActivity2 = new Intent(Intent.ACTION_VIEW,


Uri.parse(myData));

startActivity(myActivity2);

22
12. Android – Intents

Intents
More Examples: Using Standard Actions

Edit a Particular Contact (ID = 2)


Modify the complete example1 replacing
the method ‘ClickHandler’ with
the following code

String myData = "content://contacts/people/2";

Intent myActivity2 = new Intent(Intent.ACTION_EDIT,


Uri.parse(myData));

startActivity(myActivity2);

23
12. Android – Intents

Intents
More Examples: Using Standard Actions

View a Webpage
Modify the complete example1 replacing
the method ‘ClickHandler’ with
the following code

String myData = "http://www.youTube.com";

Intent myActivity2 = new Intent(Intent.ACTION_VIEW,


Uri.parse(myData));

startActivity(myActivity2);

Caution. Add to the Manifest a request to use the Internet:


<uses-permission android:name="android.permission.INTERNET" />
24
12. Android – Intents

Intents
More Examples: Using Standard Actions

Geo Mapping an Address


Provide a geoCode expression holding a street
address (or place, such as ‘golden gate ca’ )
Replace spaces with ‘+’.

String geoCode =
"geo:0,0?q=1860+east+18th+street+cleveland+oh";
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(geoCode));
startActivity(intent);

Modify the Manifest adding the following requests:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />


<uses-permission android:name="android.permission.INTERNET" /> 25
12. Android – Intents

Intents
More Examples: Using Standard Actions

Geo Mapping Coordinates (latitude, longitude)


Provide a geoCode holding latitude and
longitude (also an addittional zoom ‘?z=xx’ with
xx in range 1..23)

String geoCode =
"geo:41.5020952,-81.6789717";
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(geoCode));
startActivity(intent);

Modify the Manifest adding the following requests:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />


<uses-permission android:name="android.permission.INTERNET" /> 26
12. Android – Intents

Intents
More Examples: Using Standard Actions

Geo Mapping - Google StreetView


geoCode Uri structure:
google.streetview:cbll=lat,lng&cbp=1,
yaw,,pitch,zoom&mz=mapZoom
Reference: http://developer.android.com/guide/appendix/g-app-intents.html

String geoCode =
"google.streetview:cbll=41.5020952,-81.6789717&cbp=1,270,,45,1&mz=1";

Intent intent = new Intent(Intent.ACTION_VIEW,


Uri.parse(geoCode));
startActivity(intent);

Modify the Manifest adding the following requests:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />


<uses-permission android:name="android.permission.INTERNET" /> 27
12. Android – Intents

Intents
More Examples: Using Standard Actions

Launching the Music Player


Reference: http://developer.android.com/guide/appendix/g-app-intents.html

//launch music player

Intent myActivity2 =
new Intent("android.intent.action.MUSIC_PLAYER");

startActivity(myActivity2);

28
12. Android – Intents

Intents
More Examples: Using Standard Actions

Playing a song stored in the SD card


Reference: http://developer.android.com/guide/appendix/g-app-intents.html

// play song "amarcord.mp3" saved in the SD


Intent myActivity2 =
new Intent(android.content.Intent.ACTION_VIEW);

Uri data = Uri.parse("file:///sdcard/amarcord.mp3");


String type = "audio/mp3";

myActivity2.setDataAndType(data, type);

startActivity(myActivity2);
29
12. Android – Intents

Intents
More Examples: Using Standard Actions

Sending MMS
Add picture #1 from SD to MMS
Reference: http://developer.android.com/guide/appendix/g-app-intents.html

//send mms attach picture #1 to it

Uri uri = Uri.parse("content://media/external/images/media/1");

myActivity2 = new Intent(Intent.ACTION_SEND);

myActivity2.putExtra("address", "555-1234");
myActivity2.putExtra("sms_body", "some text message goes here");
myActivity2.putExtra(Intent.EXTRA_STREAM, uri);
myActivity2.setType("image/png");

startActivity(myActivity2);
30
12. Android – Intents

Intents
More Examples: Using Standard Actions

Sending Email
Reference: http://developer.android.com/guide/appendix/g-app-intents.html

// send email
Uri uri = Uri.parse("mailto:[email protected]");
Intent myActivity2 = new Intent(Intent.ACTION_SENDTO, uri);

// you may skip the next two pieces [subject/text]


myActivity2.putExtra(Intent.EXTRA_SUBJECT,
"subject goes here");
myActivity2.putExtra(Intent.EXTRA_TEXT,
"The email's body goes here");

startActivity(myActivity2);
31
12. Android – Intents

Intents
More Examples: Using Standard Actions

Setting System
Reference: http://developer.android.com/reference/android/provider/Settings.html

Intent intent = new Intent(


android.provider.Settings.ACTION_SETTINGS);

startActivity(intent);

32
12. Android – Intents

Intents
More Examples: Using Standard Actions

Setting System Locale:


Language & Keyboard
Reference: http://developer.android.com/reference/android/provider/Settings.html

Intent intent = new Intent(

android.provider.Settings.ACTION_LOCALE_SETTINGS);

startActivity(intent);

33
34
12. Android – Intents

Intents
Starting Activities and Getting Results

The startActivity(Intent) method is used to start a new activity, which


will be placed at the top of the activity stack.

Sometimes you want to get a result back


from the called sub-activity when it ends.

For example, you may start an activity that let the user pick a person
from a list of contacts; when it ends, it returns the person that was
selected.

35
12. Android – Intents

Intents
Starting Activities and Getting Results

In order to get results back from the called activity we use the method

startActivityForResult ( Intent, requestCodeID )

Where the second (requestCodeID) parameter identifies the call.

The result sent by the sub-activity could be picked up through the


asynchronous method

onActivityResult ( requestCodeID, resultCode, Intent )

36
12. Android – Intents

Intents
Starting Activities and Getting Results

• Before an activity exits, it can call setResult (resultCode)


to return a termination signal back to its parent.

• Always supply a result code, which can be the standard results


Activity.RESULT_CANCELED, Activity.RESULT_OK,
or any custom values.

• All of this information can be capture back on the parent's


onActivityResult (int requestCodeID, int resultCode, Intent data)
along with the integer identifier it originally supplied.

• If a child activity fails for any reason (such as crashing), the parent activity will
receive a result with the code RESULT_CANCELED.

37
12. Android – Intents

Intents
Starting Activities and Getting Results

Intent: {action + data + requestCodeID }

Activity-1
Activity-2
startActivityForResult

__________________
onActivityResult() _________________
… onResult()
… requestCodeID …
resultCode …
optional data
38
12. Android – Intents

Intents
Example2. Let’s play golf - Call for a tee-time.
1. Show all contacts and pick a particular one (Intent.ACTION_PICK).
2. For a successful interaction the main-activity accepts the returned URI
identifying the person we want to call (content://contacts/people/n).
3. ‘Nicely’ show the selected contact’s entry allowing calling, texting,
emailing actions (Intent.ACTION_VIEW).

Intent.ACTION_PICK
User’s main Built-in Activity-2
Contact’s Uri (show contact list)
Activity-1

Intent.ACTION_VIEW Call
Send text message
Built-in Activity-3 Send email
(show selected
contact)
39
12. Android – Intents

Intents
Example2. Let’s play golf - Call for a tee-time.

Cont.

Main Activity Intent.ACTION_PICK Intent.ACTION_VIEW 40


12. Android – Intents

Intents
Example2 (cont.) Let’s play golf - Call for a tee-time

Selected contact’s URI 41


Place the call Terminate the call
12. Android – Intents

Intents
Example2. Calling a sub-activity, receiving results.

//IntentDemo2_Intent: making a phone call


//receiving results from a sub-activity
package cis493.intents;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class IntentDemo2 extends Activity {


TextView label1;
EditText text1;
Button btnCallActivity2;

42
12. Android – Intents

Intents
Example2. Calling a sub-activity, receiving results.

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
label1 = (TextView)findViewById(R.id.label1);
text1 = (EditText)findViewById(R.id.text1);

btnCallActivity2 = (Button)findViewById(R.id.btnPickContact);
btnCallActivity2.setOnClickListener(new ClickHandler());
}
catch (Exception e) {
Toast.makeText(getBaseContext(),
e.getMessage(), Toast.LENGTH_LONG).show();
}
}//onCreate

43
12. Android – Intents

Intents
Example2. Calling a sub-activity, receiving results.

private class ClickHandler implements OnClickListener {


@Override
public void onClick(View v) {
try {
// myData refer to: content://contacts/people/
String myData = text1.getText().toString();

//you may also try ACTION_VIEW instead


Intent myActivity2 = new Intent(Intent.ACTION_PICK,
Uri.parse(myData));
// start myActivity2.
// Tell it that our requestCodeID (or nickname) is 222
startActivityForResult(myActivity2, 222);

// Toast.makeText(getApplicationContext(),
// "I can't wait for you", 1).show();
}
catch (Exception e) {
label1.setText(e.getMessage());
}
}//onClick
}//ClickHandler 44
12. Android – Intents

Intents
Example2. Calling a sub-activity, receiving results.

@Override
protected void onActivityResult(int requestCode,
Listener
int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// use requestCode to find out who is talking back to us
switch (requestCode){
case (222): {
// 222 is our friendly contact-picker activity
if (resultCode == Activity.RESULT_OK) {
String selectedContact = data.getDataString();
// it will return an URI that looks like:
// content://contacts/people/n
// where n is the selected contacts' ID
label1.setText(selectedContact.toString());

//show a 'nice' screen with the selected contact


Intent myAct3 = new Intent (Intent.ACTION_VIEW,
Uri.parse(selectedContact));
startActivity(myAct3);
} 45
12. Android – Intents

Intents
Example2. Calling a sub-activity, receiving results.

else {
//user pressed the BACK button
label1.setText("Selection CANCELLED "
+ requestCode + " " + resultCode);
}
break;
}
}//switch
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}// onActivityResult

}//IntentDemo2

46
12. Android – Intents

Intents
Example2. Calling a sub-activity, receiving results.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent“ >
<TextView
android:id="@+id/label1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff0000cc"
android:text="This is Activity1"
android:textStyle="bold"
android:textSize="20sp“/>
<EditText
android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="54px"
android:text="content://contacts/people/"
android:textSize="18sp” />
<Button
android:id="@+id/btnPickContact"
android:layout_width="149px"
android:layout_height="wrap_content"
android:text="Pick a Contact"
android:textStyle="bold“ />
</LinearLayout>
47
12. Android – Intents

Intents
Example3. Showing Pictures and Video - Calling a sub-activity, receiving results.
private void showSoundTracks() {
All videos and all still images
Intent myIntent = new Intent();
myIntent.setType("video/*, images/*");
myIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(myIntent, 0);

}//showSoundTracks

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);

if ((requestCode == 0) && (resultCode == Activity.RESULT_OK)) {

String selectedImage = intent.getDataString();

Toast.makeText(this, selectedImage, 1).show();

// show a 'nice' screen with the selected image


Intent myAct3 = new Intent(Intent.ACTION_VIEW, Uri.parse(selectedImage));
startActivity(myAct3);
}
}//onActivityResult
48
12. Android – Intents

Intents
Example3. Showing Pictures and Video - Calling a sub-activity, receiving results.

video

49
12. Android – Intents

Intents
Example4. Showing/Playing Sound Tracks - Calling a sub-activity, receiving results.
private void showSoundTracks() {
Intent myIntent = new Intent();
myIntent.setType("audio/mp3");
myIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(myIntent, 0);
}//showSoundTracks

The returned string value is similar to the following


“content://media/external/audio/media/14”
ACTION_VIEW on that Uri would produce a result
similar to the image on the right

50
12. Android – Intents

Intents
Questions ?

51
12. Android – Intents

Intents
Built-in Standard Broadcast Actions
List of standard actions that Intents can use for receiving broadcasts (usually
through registerReceiver(BroadcastReceiver, IntentFilter) or a <receiver> tag
in a manifest).

ACTION_TIME_TICK
ACTION_TIME_CHANGED
ACTION_TIMEZONE_CHANGED
ACTION_BOOT_COMPLETED
ACTION_PACKAGE_ADDED
ACTION_PACKAGE_CHANGED
ACTION_PACKAGE_REMOVED
ACTION_UID_REMOVED
ACTION_BATTERY_CHANGED

52
12. Android – Intents

Intents
Appendix: Getting Permissions

Becomes:
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
53
12-2
Android
Intents
Part 2
Inter-Process Communication Using Bundles

Victor Matos
Cleveland State University

Notes are based on:


Android Developers
http://developer.android.com/index.html
12. Android – Intents – Part 2

Intents

Android Intents
An activity usually presents a single visual user interface from which a number of
actions could be performed.

Moving from one activity to another is accomplished by having the current


activity start the next one through so called intents.

Intent
Activity-1 {action + data}
Activity-2
startActivityForResult
… onResult()
onActivityResult() …
requestCode
… …
requestResult
[ optional data ]
2
12. Android – Intents – Part 2

Intents
Android Bundles
Most programming languages support the notion of IPC method-calling with
arguments flowing birectionally from the caller to the invoked method.

In android the calling activity issues an invocation to another activity using an


Intent object.

Notably in Android, the caller does not stop waiting for


the called activity to return results. Instead a listening-
method [onActivityResult(...) ] should be used.

3
IPC Inter-Process Communication
12. Android – Intents – Part 2

Intents

Android Bundles
Normally the IPC expressions actual parameter list, and
formal parameter list are used to designated the signature of
particpating arguments, and the currently supplied data.

Instead of using the traditional formal / actual parameter lists,


Android relies on the concept of Intents to establish Inter-process-
communication.

Intents optionally carry a named actual list or bundle for data


exchange.

4
12. Android – Intents – Part 2

Intents

Android Bundles
The Android Bundle container is a simple mechanism used to pass data between
activities.

A Bundle is a type-safe collection of <name, value> pairs.

There is a set of putXXX and getXXX methods to store and retrieve (single and
array) values of primitive data types from/to the bundles. For example

Bundle myBundle = new Bundle();


myBundle.putDouble (“var1”, 3.1415);
...
Double v1 = myBundle.getDouble(“var1”);

5
12. Android – Intents – Part 2

Intents
Android Intents & Bundles

Activity1: Sender Activity2: Receiver


Intent myIntentA1A2 = new Intent (Activity1.this, Activity2.class);

Bundle myBundle1 = new Bundle();


myBundle1.putInt (“val1”, 123);

myIntentA1A2.putExtras(myBundle1); INTENT
Sender class / Receiver class
startActivityForResult(myIntentA1A2, 1122);
requestCode (1122)
resultCode

Extras: { val1 = 123 }

6
12. Android – Intents – Part 2

Intents
Android Intents & Bundles

Activity1: Sender Activity2: Receiver


Intent myLocalIntent2 = getIntent();

Bundle myBundle = myLocalIntent.getExtras();

int val1 = myBundle.getInt(“val1");


INTENT
Sender class / Receiver class
requestCode (1122)
resultCode

Extras: { val1 = 123 }

7
12. Android – Intents – Part 2

Intents
Android Intents & Bundles

Activity1: Sender Activity2: Receiver


myBundle.putString("val1", 456 );

myLocalIntent.putExtras(myBundle);

setResult(Activity.RESULT_OK, myLocalIntent);
INTENT
Sender class / Receiver class
requestCode (1122)
resultCode (OK)

Extras: { val1 = 456 }

8
12. Android – Intents – Part 2

Intents
Android Bundles Available at: http://developer.android.com/reference/android/os/Bundle.html
Example of Public Methods
void clear()
Removes all elements from the mapping of this Bundle.
Object clone()
Clones the current Bundle.
boolean containsKey(String key)
Returns true if the given key is contained in the mapping of this Bundle.
void putIntArray(String key, int[] value)
Inserts an int array value into the mapping of this Bundle, replacing any
existing value for the given key.
void putString(String key, String value)
Inserts a String value into the mapping of this Bundle, replacing any existing
value for the given key.
void putStringArray(String key, String[] value)
Inserts a String array value into the mapping of this Bundle, replacing any
existing value for the given key.
void putStringArrayList(String key, ArrayList<String> value)
Inserts an ArrayList value into the mapping of this Bundle, replacing any
existing value for the given key.
void remove(String key)
Removes any entry with the given key from the mapping of this Bundle.
int size()
Returns the number of mappings contained in this Bundle.

9
12. Android – Intents – Part 2

Intents
Tutorial. Activity Excahange
Activity1 collects two values from its UI and calls Activity2 to compute the
sum of them. The result is sent back from Activity 2 to Activity1.

10
12. Android – Intents – Part 2

Intents
Tutorial. Activity Excahange <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
Step1. Create GUI for Activity1(main1.xml) android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:text="Activity1"
android:textSize="22sp"
android:background="#ff0000ff"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText
android:hint="Enter first value (a signed double)"
android:id="@+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal|numberSigned|number" />
<EditText
android:hint="Second value (a positive integer)"
android:id="@+id/EditText02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number" />
<Button
android:text="Add Values"
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:background="#ff0000ff"
android:text="Sum is..."
android:textSize="28sp"
Note. The element android:inputStyle android:id="@+id/TextView01"
indicates the first value could be numeric, with android:layout_width="fill_parent"
android:layout_height="wrap_content" />
optional decimals and sign. </LinearLayout>
11
12. Android – Intents – Part 2

Intents
Tutorial. Activity Excahange <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
Step2. Create GUI for Activity2(main2.xml) android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff888888">

<TextView
android:text="Activity2"
android:textSize="22sp"
android:background="#ff0000ff"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<EditText
android:text="Data reveived..."
android:id="@+id/etDataReceived"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<Button
android:text="Done - Callback"
android:id="@+id/btnDone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

12
12. Android – Intents – Part 2

Intents
Tutorial. Activity Excahange
Step3. Activity1. After clicking the button data, from UI is put in a bundle and sent to
Activity2. A listener remains alert waiting for results to come from the called activity.
package cis493.matos.intents6; // create a container to ship data
// Activity1 Bundle myData = new Bundle();
// get input data from user, call Activity2, show result
import android.app.Activity; // add <key,value> data items to the container
import android.content.Intent; myData.putDouble("val1", v1);
import android.os.Bundle; myData.putDouble("val2", v2);
import android.view.View;
import android.view.View.OnClickListener; // attach the container to the intent
import android.widget.Button; myIntentA1A2.putExtras(myData);
import android.widget.EditText;
import android.widget.TextView; // call Activity2, tell your local listener to wait response
startActivityForResult(myIntentA1A2, 101);
public class Activity1 extends Activity {
EditText txtVal1; }//onClick
EditText txtVal2; });
TextView lblResult; }//onCreate
Button btnAdd;
////////////////////////////////////////////////////////////////////
@Override / local listener receiving callbacks from other activities
public void onCreate(Bundle savedInstanceState) { @Override
super.onCreate(savedInstanceState); protected void onActivityResult(int requestCode,
setContentView(R.layout.main1); int resultCode, Intent data) {
txtVal1 = (EditText)findViewById(R.id.EditText01); super.onActivityResult(requestCode, resultCode, data);
txtVal2 = (EditText)findViewById(R.id.EditText02);
lblResult = (TextView) findViewById(R.id.TextView01); try{
if ((requestCode == 101 ) && (resultCode == Activity.RESULT_OK)){
btnAdd = (Button) findViewById(R.id.btnAdd); Bundle myResults = data.getExtras();
btnAdd.setOnClickListener(new OnClickListener() { Double vresult = myResults.getDouble("vresult");
lblResult.setText("Sum is " + vresult);
@Override }
public void onClick(View v) { }
// get values from the UI catch (Exception e) {
Double v1 = Double.parseDouble(txtVal1.getText().toString()); lblResult.setText("Oops! - " + requestCode + " " + resultCode);
Double v2 = Double.parseDouble(txtVal2.getText().toString()); }
}//onActivityResult
// create intent to call Activity2
Intent myIntentA1A2 = new Intent (Activity1.this, }//Activity1
Activity2.class);
13
12. Android – Intents – Part 2

Intents
Tutorial. Activity Excahange
Step4. Activity2. Called from Activity1. Extracts input data from the bundle attached to
the intent. Performs local computation. Adds result to bundle. Returns OK signal.
package cis493.matos.intents6;
// add to the bundle the computed result
import android.app.Activity; myBundle.putDouble("vresult", vResult);
import android.content.Intent;
import android.os.Bundle; // attach updated bumble to invoking intent
import android.view.View; myLocalIntent.putExtras(myBundle);
import android.view.View.OnClickListener;
import android.widget.Button; // return sending an OK signal to calling activity
import android.widget.EditText; setResult(Activity.RESULT_OK, myLocalIntent);

public class Activity2 extends Activity }//onCreate


implements OnClickListener{
EditText dataReceived; @Override
Button btnDone; public void onClick(View v) {
// close current screen - terminate Activity2
@Override finish();
protected void onsuper.onCreate(savedInstanceState); }//onClick
setContentView(R.layout.main2);
dataReceived = (EditText) findViewById(R.id.etDataReceived); }//Activity2
btnDone = (Button) findViewById(R.id.btnDone);
btnDone.setOnClickListener(this);
Create(Bundle savedInstanceState) {

// pick call made to Activity2 via Intent


Intent myLocalIntent = getIntent();

// look into the bundle sent to Activity2 for data items


Bundle myBundle = myLocalIntent.getExtras();
Double v1 = myBundle.getDouble("val1");
Double v2 = myBundle.getDouble("val2");

// operate on the input data


Double vResult = v1 + v2;

// for illustration purposes. show data received & result


dataReceived.setText("Data received is \n"
+ "val1= " + v1 + "\nval2= " + v2
+ "\n\nresult= " + vResult);
14
12. Android – Intents – Part 2

Intents
Tutorial. Activity Excahange
Step5. Update the application‘s manifest. Add new <activity> tag for “Activity2“

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cis493.matos.intents6"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Activity1"
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=".Activity2"> add
</activity>

</application>
<uses-sdk android:minSdkVersion="4" />

</manifest>

15
12. Android – Intents – Part 2
This example is similar to previous.

Intents
You may want to skip it.

Example: Activity1 invokes Activity2 using an Intent. A bundle containg a set of


values is sent back-and-forth between both activities.

16
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities (see 12IntentDemo3.zip).

//Activity1: Invoking a user-defined sub-activity


//sending and receiving results from the sub-activity
package cis493.intents;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class Activity1 extends Activity {


TextView label1;
TextView label1Returned;
Button btnCallActivity2;
private final int IPC_ID = 1122;
17
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
label1 = (TextView) findViewById(R.id.label1);
label1Returned = (TextView) findViewById(R.id.label1Returned);
btnCallActivity2 = (Button) findViewById(R.id.btnCallActivity2);
btnCallActivity2.setOnClickListener(new Clicker1());
// for demonstration purposes- show in top label
label1.setText("Activity1 (sending...) \n\n"
+ "myString1: Hello Android" + "\n"
+ "myDouble1: 3.141592 " + "\n"
+ "myIntArray: {1 2 3} ");
} catch (Exception e) {
Toast.makeText(getBaseContext(),
e.getMessage(), Toast.LENGTH_LONG).show();
}
}// onCreate
18
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities.
private class Clicker1 implements OnClickListener {
@Override
public void onClick(View v) {
try {
// create an Intent to talk to Activity2
Intent myIntentA1A2 = new Intent(Activity1.this, Activity2.class);
// prepare a Bundle and add the data pieces to be sent
Bundle myData = new Bundle();
myData.putString("myString1", "Hello Android");
myData.putDouble("myDouble1", 3.141592);
int[] myLittleArray = { 1, 2, 3 };
myData.putIntArray("myIntArray1", myLittleArray);
// bind the Bundle and the Intent that talks to Activity2
myIntentA1A2.putExtras(myData);
// call Activity2 and wait for results
startActivityForResult(myIntentA1A2, IPC_ID);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
}
}// onClick
}// Clicker1 19
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
switch (requestCode) {
case IPC_ID: {
//OK. This is the place to process the results sent back from the subactivity
//see next slide
} else {
// user pressed the BACK button
label1.setText("Selection CANCELLED!");
}// if
break;
}// case
}// switch
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}// try
}// onActivityResult

}// AndroIntent1

20
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
switch (requestCode) {
case IPC_ID: {
//OK. This is the place to process the results sent back from the sub-activity
//see next slide
} else {
// user pressed the BACK button
label1.setText("Selection CANCELLED!");
}// if
break;
}// case
}// switch
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}// try
}// onActivityResult

}// AndroIntent1

21
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities.
// Activity2 is over - see what happened
if (resultCode == Activity.RESULT_OK) {

// good! - we have some data sent back from Activity2


Bundle myReturnedData = data.getExtras();

String myReturnedString1 = myReturnedData.getString("myReturnedString1");


Double myReturnedDouble1 = myReturnedData.getDouble("myReturnedDouble1");
String myReturnedString2 = myReturnedData.getString("myCurrentTime");

// display in the bottom label


label1Returned.setText(myReturnedString1 + "\n"
+ Double.toString(myReturnedDouble1) + "\n"
+ myReturnedString2);
}

22
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities.
// Activity2. This subactivity receives a bundle of data, performs some work on the data and,
// returns results to Activity1.
package cis493.intents;
import java.util.Date;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class Activity2 extends Activity {


TextView label2;
Button btnCallActivity1;

23
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities.
// Activity2 – cont…
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
//bind UI variables to Java code
label2 = (TextView)findViewById(R.id.label2);
btnCallActivity1 = (Button)findViewById(R.id.btnCallActivity1);
btnCallActivity1.setOnClickListener(new Clicker1());

//create a local Intent handler – we have been called!


Intent myLocalIntent = getIntent();

//grab the data package with all the pieces sent to us


Bundle myBundle = myLocalIntent.getExtras();

//extract the individual data parts of the bundle


String str1 = myBundle.getString("myString1");
double dob1 = myBundle.getDouble("myDouble1");
int[] arr1 = myBundle.getIntArray("myIntArray1");

24
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities.
//Activity2 – cont…
//do something with the data here (for example...)
String strArr = "{ ";
int sumIntValues = 0;
for (int i=0; i<arr1.length; i++) {
sumIntValues += arr1[i];
strArr += Integer.toString( arr1[i] ) + " ";
}
strArr += " }";

//show arriving data in GUI label


label2.setText("Activity2 (receiving...) \n\n" + "myString1: " + str1 + "\n" +
"myDouble1: " + Double.toString(dob1) + "\n" + "myIntArray1: " + strArr);

//now go back to myActivity1 with some data made here


double someNumber = sumIntValues + dob1;
myBundle.putString("myReturnedString1", "Adios Android");
myBundle.putDouble("myReturnedDouble1", someNumber);
myBundle.putString("myCurrentTime", new Date().toLocaleString() );
myLocalIntent.putExtras(myBundle);

setResult(Activity.RESULT_OK, myLocalIntent);
}//onCreate()); 25
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities.
Layout main.xml
<?xml version="1.0" encoding="utf-8"?> android:id="@+id/label1"
<LinearLayout android:layout_width="fill_parent"
android:id="@+id/linLayout" android:layout_height="wrap_content"
android:layout_width="fill_parent" android:background="#ff0033cc"
android:layout_height="fill_parent" android:text="Data to be sent to SubActivity:"
android:background="#ffccffff" android:textStyle="bold"
android:orientation="vertical" >
xmlns:android="http://schemas.android.com/apk/res/android" </TextView>
> <Button
<TextView android:id="@+id/btnCallActivity2"
android:id="@+id/caption1" android:layout_width="149px"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_height="wrap_content" android:padding="6sp"
android:background="#ffff3300" android:text="Call Activity2"
android:padding="4sp" android:textStyle="bold"
android:text=" Activity1 " >
android:textSize="20px" </Button>
android:textStyle="bold" <TextView
android:textColor="#ff000000" android:id="@+id/label1Returned"
> android:layout_width="fill_parent"
</TextView> android:layout_height="wrap_content"
<TextView android:background="#ff0033cc"
android:id="@+id/widget107" android:text=" Data returned by Activity2"
android:layout_width="fill_parent" android:textStyle="bold"
android:layout_height="2sp" >
> </TextView>
</TextView> </LinearLayout>
<TextView
26
12. Android – Intents – Part 2

Intents
Example: Activity1 invokes Activity2 using an Intent. A bundle conating a set of
values is sent back-and-forth between both activities.
Layout main2.xml
<?xml version="1.0" encoding="utf-8"?> </TextView>
<LinearLayout <TextView
android:id="@+id/linearLayout" android:id="@+id/label2"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="wrap_content"
android:background="#ffffffcc" android:background="#ff0033cc"
android:orientation="vertical" android:text="Data Received from Activity1 ..."
xmlns:android="http://schemas.android.com/apk/res/android" android:textStyle="bold"
> >
<TextView </TextView>
android:layout_width="fill_parent" <Button
android:layout_height="wrap_content" android:id="@+id/btnCallActivity1"
android:background="#ffff9900" android:layout_width="149px"
android:padding="4sp" android:layout_height="wrap_content"
android:text=" Activity2" android:padding="6sp"
android:textSize="20px" android:text="CallBack Activity1"
android:textStyle="bold" android:textStyle="bold"
> >
</TextView> </Button>
<TextView </LinearLayout>
android:id="@+id/widget107"
android:layout_width="fill_parent"
android:layout_height="2sp"
>

27
12. Android – Intents

Intents
Questions ?

28
11/1/2009

19
Android
Intent Filters

Victor Matos
Cleveland State University

Notes are based on:


Android Developers
http://developer.android.com/index.html

19. Android – Intent Filters

Intent Filters
An Analogy: Requesting Actions Using HTTP and Android

1. The HPPT1 protocol uses a number of <Action, resource> pairs to


accomplish its work
work.

2. Some of the HTTP actions are the well known (and lesser known)
operations: POST, GET, PUT, DELETE, CONNECT, HEAD, OPTIONS.

3. Android uses a mechanism quite similar to HTTP for the invocation of


work to be done.

4. INTENT is the Android’s name for the abstraction requesting actions.

5. Unlike HTTP a given Android’s INTENT could be resolved in more than


one potential way (for instance, we may have several SMS apps wanting
to process an incoming text‐message).
____ 2
1. Source: Hypertext Transfer Protocol ‐‐ HTTP/1.1 (1999). http://www.w3.org/Protocols/rfc2616/rfc2616‐sec9.html

1
11/1/2009

19. Android – Intent Filters

Intent Filters
INTENTS
• An intent is an abstract description of an operation to be performed.
• Its most significant use is in the launching of activities.
• The primary pieces of information in an intent areare: action & data.
data

ACTION DATA Misc


The general action to be The data to operate on, such as a person
performed, such as: record in the contacts database,
expressed as a URI.

_ ,
ACTION_EDIT, I am g
good for
f editingg a document
ACTION_VIEW, I am good for viewing a document
ACTION_MAIN, I am the first exec. Activ. of Application
ACTION_LAUNCHER Put me on the phone’s Menu_Pad
etc.

Source: http://developer.android.com/reference/android/content/Intent.html

19. Android – Intent Filters

Intent Filters
Parts of a Typical Intent
ACTION DATA MISC
Standard URI Category
CATEGORY_DEFAULT
ACTION_MAIN ACTION_TIME_TICK
ACTION_VIEW ACTION_TIME_CHANGED
CONTENTS such as: CATEGORY_BROWSABLE
CATEGORY_TAB
ACTION_ATTACH_DATA ACTION_TIMEZONE_CHANGED CATEGORY_ALTERNATIVE
ACTION_EDIT ACTION_BOOT_COMPLETED CATEGORY_SELECTED_ALTERNATIVE
ACTION_PICK ACTION_PACKAGE_ADDED
content://contacts/ CATEGORY_LAUNCHER
CATEGORY_INFO
ACTION_CHOOSER ACTION_PACKAGE_CHANGED content://contacts/1 CATEGORY_HOME
ACTION_GET_CONTENT ACTION_PACKAGE_REMOVED CATEGORY_PREFERENCE
ACTION_DIAL ACTION_PACKAGE_RESTARTED CATEGORY_TEST
ACTION_CALL ACTION_PACKAGE_DATA_CLEARED SCHEME such as:
ACTION_SEND ACTION_UID_REMOVED
ACTION_SENDTO ACTION_BATTERY_CHANGED MIME
ACTION_ANSWER ACTION_POWER_CONNECTED tel:123 Explicit type (a MIME type) of
ACTION_INSERT ACTION_POWER_DISCONNECTED
ACTION_DELETE ACTION_SHUTDOWN http://aaa.bbb.ccc the intent data.
ACTION_RUN
// @
mailto://[email protected]
ACTION_SYNC
ACTION_PICK_ACTIVITY ftp://aaa.bbb.ccc C
Component
ACTION_SEARCH
... Explicit name of a component
ACTION_WEB_SEARCH
ACTION_FACTORY_TEST pop:// class to use for the intent.
smtp:// Extras
ssl://
putExtra(String, Bundle)
Flags

2
11/1/2009

19. Android – Intent Filters

Intent Filters
Aside: MIME

“ … This set of documents, collectively called the


M lti
Multipurpose I t
Internet
t M
Mail
il Extensions,
E t i or MIME,
MIME redefines
d fi th
the
format of messages to allow for

(1) textual message bodies in character sets other than


US‐ASCII,

(1) an extensible set of different formats for non‐textual


message bodies,

(2) multi‐part message bodies, and

(3) textual header information in character sets other than


US‐ASCII.”
NOTE:
____ Current usage of MIME describes
Source: Multipurpose Internet Mail Extensions. (MIME) Part Two: Media Types.
Available at: http://tools.ietf.org/html/rfc2046 content type in general. 5

19. Android – Intent Filters

Intent Filters
Intent Resolution
When Intents are issued, Android looks for the most appropriated way of
responding to the request.

The decision of what to execute is based on how descriptive the call is:

Explicit Intents specify a particular component


( via setComponent(ComponentName) or setClass(Context, Class) ),
which provides the exact class to be run. This is a typical way for an
application to launch various internal activities it has as the user interacts
with the application.
application

Implicit Intents do not specified a particular component. However they


include enough information for the system to determine which of the
available components are in the is best category to run for that intent.

3
11/1/2009

19. Android – Intent Filters

Intent Filters
Intent Resolution

“The intent resolution mechanism basically revolves around


matching
t hi an Intent
I t t against
i t allll off the
th <intent‐filter>
i t t filt
descriptions in the installed application packages.”

19. Android – Intent Filters

Intent Filters
Intent Resolution

4
11/1/2009

19. Android – Intent Filters

Intent Filters
Intent Resolution
As shown in the previous illustration. Activity3 has issue a generic request for
help processing an incoming text‐message.

Assume the user has installed a “Fancy SMS” application to (perhaps) replace
the standard “HUMBLE SMS” app originally included in Android.

Upon the arrival of the implicit Intent, Android will (somehow) tell the user:
You have got a new text‐message. I have a FANCY and a HUMBLE SMS
application – which one you want me to execute? Make it a default?

Choosing candidates: For an activity to be eligible for execution it must:


1. Support the specified action
2. Support the indicated MIME type (if supplied)
3. Support all of the categories named in the intent.
_____________
RULE OF THUMB: Your Intents should be as specific as possible 9

19. Android – Intent Filters

Intent Filters
Example: Intent Filters
The Manifest tells the application (FancySms) is able to intercept incoming SMS
data using its SMSReceiver (potential alternative to the default SMS app.)
<?xml version="1.0" encoding="utf‐8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cis493.intentfilters" android:versionCode="1" android:versionName="1.0.0">
<uses‐permission android:name="android.permission.RECEIVE_SMS" />
<application android:icon="@drawable/icon" >
<activity android:name=".FancySms" >
<intent‐filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent‐filter>
/
</activity>
<receiver android:name="SMSReceiver" android:enabled="true" >
<intent‐filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent‐filter>
</receiver>
</application>
</manifest> 10

5
11/1/2009

19. Android – Intent Filters

Intent Filters
Comments on the example:

• The application consists of two components:


1 a common Activity called FancySms (acting as the main routine) and
1.
2. a background Service (BroadcastReceiver) called SMSService.

• The clause below indicates the application is allowed to receive SMS


<uses‐permission android:name="android.permission.RECEIVE_SMS" />

• The component SMSService has the filter


<intent‐filter>
<intent filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent‐filter>
that triggers its execution whenever a new SMS is received

• Other applications with the same filter can be also called by Android when
new SMS arrives (until a DEFAULT is chosen)
11

19. Android – Intent Filters

Intent Filters
Example: Intercepting Incoming SMS
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/mainLayout"
android:layout width="fill
android:layout_width= fill_parent
parent“ android:layout_height=
android:layout height="fill
fill_parent
parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:textSize="20px" android:textStyle="bold“ ndroid:background="#ff0000ff"
android:text="Intercepting SMS messages"
/>
<ScrollView
android:id="@+id/myScroller1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/theMessage"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="#ffffffff" android:padding="4px"
android:textSize="14px" android:textColor="#ff000000"
/>
</ScrollView>
</LinearLayout>

12

6
11/1/2009

19. Android – Intent Filters

Intent Filters
Example: Intercepting Incoming SMS

Note:
Test the following application
from the Eclipse’s DDMS
perspective. Select “Emulator
Control” > “Telephony Actions”.
Set phone no. to 5554, type a
message, click on Send.

Alternatively you may start


another emulator and send
SMS to 5554

13

19. Android – Intent Filters

Intent Filters
Example: Intercepting Incoming SMS
// FancySms: main screen - displays intercepted SMS
package cis493.intentfilters;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class FancySms extends Activity {


static TextView txtMsg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtMsg = (TextView)findViewById(R.id.theMessage);
}
}// class FancySms

14

7
11/1/2009

19. Android – Intent Filters

Intent Filters
Example: Intercepting Incoming SMS
// SMSReceiver: listens to broadcasted SMS_RECEIVED signals
package cis493.intentfilters;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// Android saves in a bundle the current text-message
// under name "pdus" and type: Object[]. Later we cast to
// SmsMessage[]. Jargon pdu stands for "protocol data unit"
Bundle bundle = intent.getExtras();

15

19. Android – Intent Filters

Intent Filters
Example: Intercepting Incoming SMS
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];

// Note: long sms are broken and transmitted into various pieces
String msg = "";
int smsPieces = messages.length;

for (int n = 0; n < smsPieces; n++) {


smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
// grab all pieces of the intercepted sms
msg += "\n" + (n + 1) + " -of- " + smsPieces + "\n"
+ "Sender:\t" + smsMessage[n].getOriginatingAddress() + "\n"
+ "Body: \n " + smsMessage[n].getMessageBody();
}

// show first part of intercepted (current) message


Toast toast = Toast.makeText(context, "FANCY >>> Received SMS: "
+ smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast.show();

cis493.intentfilters.FancySms.txtMsg.setText(msg);
}
}// class SMSReceiver 16

8
11/1/2009

19. Android – Intent Filters

Intent Filters

Questions

17

19. Android – Intent Filters

Intent Filters
JARGON:

PDU
i short
is h t ffor "P
"Protocol
t lD Data
t UUnit".
it" This
Thi represents
t an amountt off iinformation
f ti
delivered through a network layer.

VND
virtual network data (today typically represents a business card with name,
phone, email, etc). Originally registered as MIME vnd.abc intended for
transmission of abc folk melodies in emails
see:http://www.iana.org/assignments/media‐types/text/vnd.abc

18

9
23
Android
Notifications

Victor Matos
Cleveland State University

Notes are based on:


Android Developers
http://developer.android.com/index.html
20. Android - Notifications

Notifications
What is a Notification?

A notification is a short message briefly displayed on the status


line.

It typically announces the happening of an special event for


which a trigger has been set.

After opening the Notification Panel the user may choose to click
on a selection and execute an associated activity.

2
20. Android - Notifications

Notifications
What is a Notification?
Notification shown
on the status line

Drag down

Click on
Notification
Panel to
execute
associated
application

3
20. Android - Notifications

Notifications
Notification Manager
This class notifies the user of events that happen in the background.

Notifications can take different forms:

1. A persistent icon that goes in the status bar and is accessible through the
launcher, (when the user selects it, a designated Intent can be launched),

2. Turning on or flashing LEDs on the device, or

3. Alerting the user by flashing the backlight, playing a sound, or vibrating.

4
20. Android - Notifications

Notifications
Notification Manager

You do not instantiate this class directly; instead, retrieve it through


getSystemService ( String ).

Example:

String servName = Context.NOTIFICATION_SERVICE;

notificationManager = (NotificationManager) getSystemService (servName);

5
20. Android - Notifications

Notifications
Notification

This class represents how a persistent notification is to be presented to


the user using the NotificationManager.

public Notification (int icon, CharSequence tickerText, long when)

Parameters
icon The resource id of the icon to put in the status bar.
tickerText The text that flows by in the status bar when the notification
first activates.
when The time to show in the time field.
In the System.currentTimeMillis timebase.

6
20. Android - Notifications

Notifications
Notification - Methods

public void notify (int id, Notification notification)

Places a persistent notification on the status bar.

Parameters
id An identifier for this notification unique within
your application.

notification A Notification object describing how to notify the


user, other than the view you're providing.
Must not be null.

7
20. Android - Notifications

Notifications
Notification – Methods

public void setLatestEventInfo (


Context context, CharSequence contentTitle,
CharSequence contentText, PendingIntent contentIntent)

Sets the contentView field to be a view with the standard "Latest Event"
layout.

Parameters
context The context for your application / activity.
contentTitle The title that goes in the expanded entry.
contentText The text that goes in the expanded entry.
contentIntent The intent to launch when the user clicks the expanded
notification.

8
20. Android - Notifications

Notifications
Notification – Methods

public void cancel ( int id )


public void cancelAll ( )

Cancel a previously shown notification. If it's transient, the view will be


hidden. If it's persistent, it will be removed from the status bar.

Parameters
Id An identifier for this notification unique within your application.

9
20. Android - Notifications

Notifications
Example.
Produce a notification. Allow the user to click on the Notification Panel
and execute appropriate activity to attend the message.

10
20. Android - Notifications

Notifications
Example - Layouts
main.xml main2.xml
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
<LinearLayout
android:id="@+id/main2LinLayout"
android:id="@+id/myLinearLayout1"
android:layout_width="fill_parent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_height="fill_parent"
android:background="#ff660000"
android:background="#ff000066"
android:orientation="vertical"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/
xmlns:android="http://schemas.android.com/apk/res/android" >
android"
>
<TextView
<Button
android:id="@+id/widget29"
android:id="@+id/btnGo"
android:layout_width="251px"
android:layout_width="106px"
android:layout_height="69px"
android:layout_height="61px"
android:text="Hola this is screen 2 - Layout:main2.xml"
android:layout_margin="10px"
>
android:text=" Show Notification " >
</TextView>
</Button>
</LinearLayout>
<Button
android:id="@+id/btnStop"
android:layout_width="106px"
android:layout_height="61px"
android:layout_margin="10px"
android:text=" Cancel Notification " >
</Button>
</LinearLayout>
11
20. Android - Notifications

Notifications
Example – Manifest /drawable
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cis493.demos"
android:versionCode="1"
android:versionName="1.0"> btn_star_big_on_selected.png
<application android:icon="@drawable/icon"
android:label="@string/app_name">
Note:
<activity android:name=".NotifyDemo1" Obtain the icon from the folder
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" /> C:\Android\platforms\android-
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter> 1.x\data\res\drawable
</activity>

<activity android:name=".NotifyHelper" >


</activity>

</application>

<uses-sdk android:minSdkVersion="4" />

</manifest>

12
20. Android - Notifications

Notifications
Example – Create & Cancel a Notification

package cis493.demos;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

///////////////////////////////////////////////////////////////////////////////
public class NotifyDemo1 extends Activity {
Button btnGo;
Button btnStop;
int notificationId = 1;
NotificationManager notificationManager;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
13
20. Android - Notifications

Notifications
Example – Create & Cancel a Notification

btnGo = (Button)findViewById(R.id.btnGo);
btnGo.setOnClickListener(new OnClickListener() {

public void onClick(View v) {


//define a notification manager
String serName = Context.NOTIFICATION_SERVICE;
notificationManager = (NotificationManager)getSystemService(serName);

//define notification using: icon, text, and timing.


int icon = R.drawable.btn_star_big_on_selected;
String tickerText = "1. My Notification TickerText";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);

//configure appearance of the notification


String extendedTitle = "2. My Extended Title";
String extendedText = "3. This is an extended and very important message";

// set a Pending Activity to take care of the potential request the user
// may have by clicking on the notification asking for more explanations
Intent intent = new Intent(getApplicationContext(), NotifyHelper.class);
intent.putExtra("extendedText", extendedText);
intent.putExtra("extendedTitle", extendedTitle);
PendingIntent launchIntent =
PendingIntent.getActivity(getApplicationContext(),0,intent,0);
14
20. Android - Notifications

Notifications
Example – Create & Cancel a Notification

notification.setLatestEventInfo(getApplicationContext(),
extendedTitle, extendedText, launchIntent);

//trigger notification
notificationId = 1;
notificationManager.notify(notificationId, notification);

}//click
});

/////////////////////////////////////////////////////////////////////////////
btnStop = (Button)findViewById(R.id.btnStop);
btnStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//canceling a notification
notificationId = 1;
notificationManager.cancel(notificationId);
}
});

}//onCreate

}//NotifyDemo1

15
20. Android - Notifications

Notifications
Example - SubActivity – Attending the Notification
package cis493.demos;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class NotifyHelper extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);

Intent myData = getIntent();


// extract the extra-data in the Notification
String msg = myData.getStringExtra("extendedTitle") + "\n"
+ myData.getStringExtra("extendedText");

Toast.makeText(getApplicationContext(), msg, 1).show();


}
}
16
20. Android - Notifications

Notifications

Questions

17

You might also like