Unit III
Unit III
Android
Intents
Victor Matos
Cleveland State University
Intents
Android Activities
An Android application could include any number of activities.
• Typically, one of the activities is designated as the first one (main) that
should be presented to the user when the application is launched.
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
4
12. Android – Intents
Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html
Activity-1 Activity-2
Optional results
5
12. Android – Intents
Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html
startActivity (myActivity);
6
12. Android – Intents
Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html
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.
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.
9
12. Android – Intents
Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html
intent.putExtra(SearchManager.QUERY,
"straight hitting golf clubs");
Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html
intent.putExtra("address", "555-1234");
intent.putExtra("sms_body", "remember to buy bread and milk");
startActivity(intent);
Intents
Taken from: http://code.google.com/android/reference/android/content/Intent.html
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.*;
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)
Intents
1. A Complete Example: Activity1 displays an interface to accept a phone number and
requests (built-in) Activity2 to make the call.
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
startActivity(myActivity2);
Needs Permission:
<uses-permission android:name="android.permission.CALL_PHONE" />
20
12. Android – Intents
Intents
More Examples: Using Standard Actions
startActivity(myActivity2);
21
12. Android – Intents
Intents
More Examples: Using Standard Actions
startActivity(myActivity2);
22
12. Android – Intents
Intents
More Examples: Using Standard Actions
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
startActivity(myActivity2);
Intents
More Examples: Using Standard Actions
String geoCode =
"geo:0,0?q=1860+east+18th+street+cleveland+oh";
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(geoCode));
startActivity(intent);
Intents
More Examples: Using Standard Actions
String geoCode =
"geo:41.5020952,-81.6789717";
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(geoCode));
startActivity(intent);
Intents
More Examples: Using Standard Actions
String geoCode =
"google.streetview:cbll=41.5020952,-81.6789717&cbp=1,270,,45,1&mz=1";
Intents
More Examples: Using Standard Actions
Intent myActivity2 =
new Intent("android.intent.action.MUSIC_PLAYER");
startActivity(myActivity2);
28
12. Android – Intents
Intents
More Examples: Using Standard Actions
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
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);
startActivity(myActivity2);
31
12. Android – Intents
Intents
More Examples: Using Standard Actions
Setting System
Reference: http://developer.android.com/reference/android/provider/Settings.html
startActivity(intent);
32
12. Android – Intents
Intents
More Examples: Using Standard Actions
android.provider.Settings.ACTION_LOCALE_SETTINGS);
startActivity(intent);
33
34
12. Android – Intents
Intents
Starting Activities and Getting Results
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
36
12. Android – Intents
Intents
Starting Activities and Getting Results
• 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
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.
Intents
Example2 (cont.) Let’s play golf - Call for a tee-time
Intents
Example2. Calling a sub-activity, receiving results.
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.
// 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());
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);
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
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
Intents
Android Intents
An activity usually presents a single visual user interface from which a number of
actions could be performed.
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.
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.
4
12. Android – Intents – Part 2
Intents
Android Bundles
The Android Bundle container is a simple mechanism used to pass data between
activities.
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
5
12. Android – Intents – Part 2
Intents
Android Intents & Bundles
myIntentA1A2.putExtras(myBundle1); INTENT
Sender class / Receiver class
startActivityForResult(myIntentA1A2, 1122);
requestCode (1122)
resultCode
6
12. Android – Intents – Part 2
Intents
Android Intents & Bundles
7
12. Android – Intents – Part 2
Intents
Android Intents & Bundles
myLocalIntent.putExtras(myBundle);
setResult(Activity.RESULT_OK, myLocalIntent);
INTENT
Sender class / Receiver class
requestCode (1122)
resultCode (OK)
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);
Intents
Tutorial. Activity Excahange
Step5. Update the application‘s manifest. Add new <activity> tag for “Activity2“
<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.
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).
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
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) {
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.*;
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());
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 += " }";
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
Intent Filters
An Analogy: Requesting Actions Using HTTP and Android
2. Some of the HTTP actions are the well known (and lesser known)
operations: POST, GET, PUT, DELETE, CONNECT, HEAD, OPTIONS.
1
11/1/2009
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_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
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
Intent Filters
Aside: MIME
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:
3
11/1/2009
Intent Filters
Intent Resolution
Intent Filters
Intent Resolution
4
11/1/2009
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?
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
Intent Filters
Comments on the example:
• Other applications with the same filter can be also called by Android when
new SMS arrives (until a DEFAULT is chosen)
11
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
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.
13
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;
14
7
11/1/2009
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;
@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
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;
cis493.intentfilters.FancySms.txtMsg.setText(msg);
}
}// class SMSReceiver 16
8
11/1/2009
Intent Filters
Questions
17
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
Notifications
What is a Notification?
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.
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),
4
20. Android - Notifications
Notifications
Notification Manager
Example:
5
20. Android - Notifications
Notifications
Notification
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
Parameters
id An identifier for this notification unique within
your application.
7
20. Android - Notifications
Notifications
Notification – Methods
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
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>
</application>
</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() {
// 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Notifications
Questions
17