Sei sulla pagina 1di 15

10/18/2011

1
Android
12-2
Intents
Part2
InterProcessCommunicationUsingBundles
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
AndroidDevelopers
http://developer.android.com/index.html
12.Android Intents Part2
Intents
AndroidIntents
An activity usually presents a single visual user interface from which a number of Anactivity usuallypresentsasinglevisualuserinterfacefromwhichanumberof
actionscouldbeperformed.
Movingfromoneactivitytoanotherisaccomplishedbyhavingthecurrent
activitystartthenextonethroughsocalledintents.
Intent
{action+data}
Activity1
22
{action data}
requestCode
requestResult
[optionaldata ]
Activity1
startActivityForResult

onActivityResult()

Activity2
onResult()

10/18/2011
2
12.Android Intents Part2
Intents
AndroidBundles
MostprogramminglanguagessupportthenotionofIPC methodcalling with
argumentsflowingbirectionallyfromthecallertotheinvokedmethod.
Inandroidthecallingactivityissuesaninvocationtoanotheractivityusingan
Intent object.
NotablyinAndroid,thecallerdoesnotstopwaitingfor
the called activity to return results Instead a listening
33
thecalledactivitytoreturnresults.Insteadalistening
method[onActivityResult(...)]shouldbeused.
IPCInterProcessCommunication
12.Android Intents Part2
Intents
AndroidBundles
NormallytheIPCexpressionsactualparameterlist,and
formalparameterlist areusedtodesignatedthesignatureof
particpatingarguments,andthecurrentlysupplieddata.
Insteadofusingthetraditionalformal/actualparameterlists,
AndroidreliesontheconceptofIntentstoestablishInterprocess
44
communication.
Intentsoptionallycarryanamedactuallistorbundle fordata
exchange.
10/18/2011
3
12.Android Intents Part2
Intents
AndroidBundles
TheAndroidBundle containerisasimplemechanismusedtopassdatabetween
activities.
ABundle isatypesafecollectionof<name,value> pairs.
ThereisasetofputXXX andgetXXX methodstostoreandretrieve(singleand
array)valuesofprimitivedatatypesfrom/tothebundles.Forexample
55
Bundle myBundle = new Bundle();
myBundle.putDouble ("var1", 3.1415);
...
Double v1 = myBundle.getDouble("var1");
12.Android Intents Part2
Intents
AndroidIntents&Bundles
Activity1:Sender Activity2:Receiver
IntentmyIntentA1A2=newIntent(Activity1.this,
Activity2.class);
BundlemyBundle1=newBundle();
myBundle1.putInt("val1",123);
myIntentA1A2.putExtras(myBundle1);
startActivityForResult(myIntentA1A2,1122);
y y
INTENT
requestCode (1122)
Senderclass/Receiverclass
66
requestCode (1122)
resultCode
Extras:{val1=123 }
10/18/2011
4
12.Android Intents Part2
Intents
AndroidIntents&Bundles
Activity1:Sender Activity2:Receiver y y
INTENT
C d (1122)
Senderclass/Receiverclass
IntentmyCallerIntent2=getIntent();
BundlemyBundle =myCallerIntent.getExtras();
int val1=myBundle.getInt("val1");
77
requestCode (1122)
resultCode
Extras:{val1=123 }
12.Android Intents Part2
Intents
AndroidIntents&Bundles
Activity1:Sender Activity2:Receiver y y
INTENT
C d (1122)
Senderclass/Receiverclass
myBundle.putString("val1",456);
myCallerIntent.putExtras(myBundle);
setResult(Activity.RESULT_OK,
myCallerIntent);
88
requestCode (1122)
resultCode (OK)
Extras:{val1=456}
10/18/2011
5
12.Android Intents Part2
Intents
AndroidBundlesAvailableat:http://developer.android.com/reference/android/os/Bundle.html
Example of Public Methods
void clear()
Removes all elements fromthe mapping of this Bundle.

Object clone() Object clone()
Clones the current Bundle.

boolean containsKey(String key)
Returns trueif 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 valuefor thegiven key.

void putString(String key, String value)
Inserts a String valueinto themapping 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

99
existing valuefor thegiven key.
void putStringArrayList(String key, ArrayList<String>value)
Inserts an ArrayList valueinto themapping of this Bundle, replacing any
existing valuefor thegiven key.

void remove(String key)
Removes any entry with thegiven key fromthemapping of this Bundle.

int size()
Returns thenumber of mappings contained in thisBundle.

12.Android Intents Part2


Intents
Tutorial1.ActivityExcahange
Activity1collectstwovaluesfromitsUIandcallsActivity2tocomputethe
sumofthem.TheresultissentbackfromActivity2toActivity1.
10 10
10/18/2011
6
12.Android Intents Part2
Intents
Tutorial1.ActivityExcahange
Step1. CreateGUIforActivity1(main1.xml)
<?xmlversion="1.0"encoding="utf8"?>
<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:text="Activity1"
android:textSize="22sp"
android:background="#ff0000ff" android:background #ff0000ff
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<EditText
android:hint="Enterfirstvalue(asigneddouble)"
android:id="@+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal|numberSigned|number"/>
<EditText
android:hint="Secondvalue(apositiveinteger)"
android:id="@+id/EditText02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number"/>
<Button
11 11
<Button
android:text="AddValues"
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:background="#ff0000ff"
android:text="Sumis..."
android:textSize="28sp"
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Note.Theelementandroid:inputStyle
indicatesthefirstvaluecouldbenumeric,with
optionaldecimalsandsign.
12.Android Intents Part2
Intents
Tutorial1.ActivityExcahange
Step2. CreateGUIforActivity2(main2.xml)
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff888888">
<TextView <TextView
android:text="Activity2"
android:textSize="22sp"
android:background="#ff0000ff"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<EditText
android:text="Datareveived..."
android:id="@+id/etDataReceived"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:text="Done Callback"
android:id="@+id/btnDone"
12 12
android:id @+id/btnDone
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
10/18/2011
7
12.Android Intents Part2
Intents
Tutorial1.ActivityExcahange
Step3. Activity1.Afterclickingthebuttondata,fromUIisputinabundleandsentto
Activity2.Alistenerremainsalertwaitingforresultstocomefromthecalledactivity.
package cis493.matos.intent2b;
//Activity1:gettwoinputvaluesfromuser,puttheminabumble.callActivity2toaddthetwonumbers,showresult
import ...;
public class Activity1 extends Activity { public class Activity1extends Activity{
EditText txtVal1;
EditText txtVal2;
TextView lblResult;
ButtonbtnAdd;
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
txtVal1 =(EditText)findViewById(R.id.EditText01);
txtVal2 =(EditText)findViewById(R.id.EditText02);
lblResult =(TextView)findViewById(R.id.TextView01);
btnAdd =(Button)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new OnClickListener(){
@Override
public void onClick(Viewv){
//getvaluesfromtheUI
Doublev1=Double.parseDouble(txtVal1.getText().toString());
Double v2 = Double.parseDouble(txtVal2.getText().toString());
13 13
Doublev2 Double.parseDouble(txtVal2.getText().toString());
//createintenttocallActivity2
IntentmyIntentA1A2=new Intent(Activity1.this, Activity2.class);
//createacontainertoshipdata
BundlemyData =new Bundle();
//add<key,value>dataitemstothecontainer
myData.putDouble("val1",v1);
myData.putDouble("val2",v2);
//attachthecontainertotheintent
myIntentA1A2.putExtras(myData);
//callActivity2,tellyourlocallistenertowaitforresponse
startActivityForResult(myIntentA1A2,101);
}
});
}//onCreate
12.Android Intents Part2
Intents
Tutorial1.ActivityExcahangecont.
Step3.Activity1.Afterclickingthebuttondata,fromUIisputinabundleandsentto
Activity2.Alistenerremainsalertwaitingforresultstocomefromthecalledactivity.
//////////////////////////////////////////////////////////////////////////////
//locallistenerreceivingcallbacksfromotheractivities
@Override
protected void onActivityResult(int requestCode,int resultCode,Intentdata){
super.onActivityResult(requestCode,resultCode,data);
try {
if ((requestCode ==101)&&(resultCode ==Activity.RESULT_OK)){
BundlemyResults =data.getExtras();
Doublevresult =myResults.getDouble("vresult");
lblResult.setText("Sumis" +vresult);
}
}
catch (Exceptione){
lbl l (" bl " d " " l d )
14 14
lblResult.setText("Problems " +requestCode +"" +resultCode);
}
}//onActivityResult
}//Activity1
10/18/2011
8
12.Android Intents Part2
Intents
Tutorial1.ActivityExcahangecont.
Step4. Activity2.CalledfromActivity1.Extractsinputdatafromthebundleattachedto
theintent.Performslocalcomputation.Addsresulttobundle.ReturnsOKsignal.
package cis493.matos.intent2b;
import ...;
//returnsendinganOKsignaltocallingactivity
setResult(Activity.RESULT_OK,myLocalIntent);
//experiment:removecomment
public class Activity2extends Activityimplements OnClickListener{
EditText dataReceived;
ButtonbtnDone;
@Override
protected void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
dataReceived =(EditText)findViewById(R.id.etDataReceived);
btnDone =(Button)findViewById(R.id.btnDone);
btnDone.setOnClickListener(this);
//pickcallmadetoActivity2viaIntent
IntentmyLocalIntent =getIntent();
//lookintothebundlesenttoActivity2fordataitems
BundlemyBundle =myLocalIntent.getExtras();
Double v1 = myBundle.getDouble("val1");
//finish();
}//onCreate
@Override
public void onClick(Viewv){
//closecurrentscreen terminateActivity2
finish();
}//onClick
}//Activity2
15 15
Doublev1 myBundle.getDouble( val1 );
Doublev2=myBundle.getDouble("val2");
//operateontheinputdata
DoublevResult =v1+v2;
//forillustrationpurposes.showdatareceived&result
dataReceived.setText("Datareceivedis\n"
+"val1=" +v1+"\nval2=" +v2
+"\n\nresult=" +vResult);
//addtothebundlethecomputedresult
myBundle.putDouble("vresult",vResult);
//attachupdatedbumbletoinvokingintent
myLocalIntent.putExtras(myBundle);
12.Android Intents Part2
Intents
Tutorial1.ActivityExcahangecont.
Step5. Updatetheapplicationsmanifest.Addnew<activity>tagforActivity2
<?xml ver si on=" 1. 0" encodi ng=" ut f - 8" ?>
<mani f est xml ns: andr oi d=" ht t p: / / schemas. andr oi d. com/ apk/ r es/ andr oi d"
package=" ci s493. mat os. i nt ent 2b"
andr oi d: ver si onCode=" 1"
andr oi d: ver si onName=" 1. 0" >
<appl i cat i on andr oi d: i con=" @dr awabl e/ i con" andr oi d: l abel =" @st r i ng/ app_name" >
<act i vi t y andr oi d: name=" . Act i vi t y1"
andr oi d: l abel =" @st r i ng/ app_name" >
<i nt ent - f i l t er >
<act i on andr oi d: name=" andr oi d. i nt ent . act i on. MAI N" / >
<cat egor y andr oi d: name=" andr oi d. i nt ent . cat egor y. LAUNCHER" / >
</ i nt ent - f i l t er >
</ act i vi t y>
<act i vi t y
andr oi d: name=" . Act i vi t y2" >
</ act i vi t y>
/
add
16 16
</ appl i cat i on>
<uses- sdk andr oi d: mi nSdkVer si on=" 4" / >
</ mani f est >
10/18/2011
9
12.Android Intents Part2
Intents
Tutorial2::Activity1invokesActivity2usinganIntent.Abundleconatingasetof
differentdatatypes issentbackandforthbetweenbothactivities(see12IntentDemo3.zip).
Thisexampleissimilartoprevious.
Youmaywanttoskipit.
17 17
//Activity1:Invokingauserdefinedsubactivitysendingandreceivingresultsfromthesubactivity
package cis493.intents3;
12.Android Intents Part2
Intents
Tutorial2:Activity1invokesActivity2usinganIntent.Abundleconatingasetof
differentdatatypes issentbackandforthbetweenbothactivities(see12IntentDemo3.zip).
import ...;
public class Activity1extends Activity{
TextView label1;
TextView label1Returned;
ButtonbtnCallActivity2;
//arbitraryinterprocess communicationID(justanickname!)
private final int IPC_ID =(int)(10001*Math.random());
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
l b l1 (T tVi ) fi dVi B Id(R id l b l1) label1 =(TextView)findViewById(R.id.label1);
label1Returned =(TextView)findViewById(R.id.label1Returned);
btnCallActivity2 =(Button)findViewById(R.id.btnCallActivity2);
btnCallActivity2.setOnClickListener(new Clicker1());
//fordemonstrationpurposes showintoplabel
label1.setText("Activity1(sending...)\n\n"
+"RequestCode ID:" +IPC_ID +"\n"
+"myString1:HelloAndroid" +"\n"
+"myDouble1:3.141592" +"\n"
+"myIntArray:{123}");
}catch (Exceptione){
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}//onCreate
18 18
10/18/2011
10
private class Clicker1implements OnClickListener {
public void onClick(Viewv){
try {
12.Android Intents Part2
Intents
Tutorial2:Activity1invokesActivity2usinganIntent.Abundleconatingasetof
differentdatatypes issentbackandforthbetweenbothactivities(see12IntentDemo3.zip).
//createanIntenttotalktoActivity2
IntentmyIntentA1A2=new Intent(Activity1.this,
Activity2.class);
//prepareaBundleandaddthedatapiecestobesent
BundlemyData =new Bundle();
myData.putInt("myRequestCode",IPC_ID);
myData.putString("myString1","HelloAndroid");
myData.putDouble("myDouble1",3.141592);
int []myLittleArray ={1,2,3};
myData.putIntArray("myIntArray1",myLittleArray);
//bindtheBundleandtheIntentthattalkstoActivity2
myIntentA1A2.putExtras(myData);
//callActivity2andwaitforresults
startActivityForResult(myIntentA1A2,IPC_ID);
}catch (Exceptione){
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}//onClick
}//Clicker1
19 19
@Override
protected void onActivityResult(int requestCode,int resultCode,Intentdata){
super.onActivityResult(requestCode,resultCode,data);
{
12.Android Intents Part2
Intents
Tutorial2:Activity1invokesActivity2usinganIntent.Abundleconatingasetof
differentdatatypes issentbackandforthbetweenbothactivities(see12IntentDemo3.zip).
try {
//checkthattheseresultsareforus
if (IPC_ID ==requestCode){
//Activity2isover seewhathappened
if (resultCode ==Activity.RESULT_OK){
//good wehavesomedatasentbackfromActivity2
BundlemyReturnedData =data.getExtras();
StringmyReturnedString1=myReturnedData.getString("myReturnedString1");
DoublemyReturnedDouble1=myReturnedData.getDouble("myReturnedDouble1");
StringmyReturnedString2=myReturnedData.getString("myCurrentTime");
//displayinthebottomlabel
label1Returned.setText(
"requestCode:" +requestCode +"\n"
+"resultCode:" +resultCode +"\n"
+"returnedString1:" +myReturnedString1+"\n"
+"returnedDouble:" +Double.toString(myReturnedDouble1)+"\n"
+"returnedString2:" +myReturnedString2);
}else {
//userpressedtheBACKbutton
label1.setText("SelectionCANCELLED!");
}//if
}
}catch (Exceptione){
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}//try
}//onActivityResult
}//AndroIntent1
20 20
10/18/2011
11
12.Android Intents Part2
Intents
Tutorial2:Activity2iscalledtocooperatewithActivity1.Dataistransferredinabundle
//Activity2.Thissubactivity receivesabundleofdata,performssomeworkonthedataand,returnsresultstoActivity1.
package cis493.intents3;
import ; import ...;
public class Activity2extends Activity{
TextView label2;
TextView spyBox;
ButtonbtnCallActivity1;
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
//bindUIvariablestoJavacode
label2 =(TextView)findViewById(R.id.label2);
spyBox =(TextView)findViewById(R.id.spyBox);
btnCallActivity1 =(Button)findViewById(R.id.btnCallActivity1);
btnCallActivity1.setOnClickListener(new Clicker1());
// l l h dl h b ll d!
21 21
//createalocalIntenthandler wehavebeencalled!
IntentmyLocalIntent =getIntent();
//grabthedatapackagewithallthepiecessenttous
BundlemyBundle =myLocalIntent.getExtras();
//extracttheindividualdatapartsofthebundle
int int1=myBundle.getInt("myRequestCode");
Stringstr1=myBundle.getString("myString1");
double dob1=myBundle.getDouble("myDouble1");
int[]arr1=myBundle.getIntArray("myIntArray1");
12.Android Intents Part2
Intents
Tutorial2:Activity2iscalledtocooperatewithActivity1.Dataistransferredinabundle
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//WhatifIdon'tknowthekeynames?
//whatcameinthebundle?.Thisfragmentshowshowtouse
//bundlemethodstoextractitsdata.Needtoknow
//ANDROIDTYPES:
// class [I (array integers) //class[I(arrayintegers)
//class[J(arraylong)
//class[D(arraydoubles)
//class[F(arrayfloats)
//classjava.lang.xxx (wherexxx=Integer,Double,...)
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Stringspy="\nSPY>>\n";
Set<String>myKeyNames =myBundle.keySet();
for (StringkeyName :myKeyNames){
Serializable keyValue =myBundle.getSerializable(keyName);
StringkeyType =keyValue.getClass().toString();
if (keyType.equals("classjava.lang.Integer")){
keyValue =Integer.parseInt(keyValue.toString());
}
else if (keyType.equals("classjava.lang.Double")){
keyValue =Double.parseDouble(keyValue.toString());
}
22 22
}
else if (keyType.equals("classjava.lang.Float")){
keyValue =Float.parseFloat(keyValue.toString());
}
else if (keyType.equals("class[I")){
int[]arrint =myBundle.getIntArray(keyName);
int n=arrint.length;
keyValue =arrint[n1];//showonlythelast!
}
else {
keyValue =(String)keyValue.toString();
}
spy+=keyName +":" +keyValue +"" +keyType +"\n" ;
}
spyBox.append(spy);
10/18/2011
12
12.Android Intents Part2
Intents
Tutorial2:Activity2iscalledtocooperatewithActivity1.Dataistransferredinabundle
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//dosomethingwiththedatahere(forexample...)
StringstrArr ="{";
int sumIntValues =0;
for (int i=0;i<arr1.length;i++){
sumIntValues += arr1[i]; sumIntValues arr1[i];
strArr +=Integer.toString(arr1[i])+"";
}
strArr +="}theirsumis=" +sumIntValues;
//showarrivingdatainGUIlabel2
label2.append("\n\nActivity2(receiving...)\n\n" +
"Caller'srequestCode ID:" +int1+"\n" +
"myString1:" +str1+"\n" +
"myDouble1:" +Double.toString(dob1)+"\n" +
"myIntArray1:" +strArr);
//nowgobacktomyActivity1withsomenewdatamadehere
double someNumber =sumIntValues +dob1;
myBundle.putString("myReturnedString1","AdiosAndroid");
myBundle.putDouble("myReturnedDouble1",someNumber);
myBundle.putString("myCurrentTime",new Date().toLocaleString());
myLocalIntent putExtras(myBundle);
23 23
myLocalIntent.putExtras(myBundle);
//alldone!
setResult(Activity.RESULT_OK,myLocalIntent);
}//onCreate
private class Clicker1implements OnClickListener {
public void onClick(Viewv){
//clearActivity2screensoActivity1couldbeseen
finish();
}//onClick
}//Clicker1
}//Activity2
<?xml version="1.0" encoding="utf8"?> android:layout width="fill parent"
12.Android Intents Part2
Intents
Tutorial2:Activity2iscalledtocooperatewithActivity1.Dataistransferredin
abundle
Layout:main.xml
<?xmlversion 1.0 encoding utf 8 ?>
<LinearLayout
android:id="@+id/linLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#ff555555">
<TextView
android:id="@+id/caption1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffff3300"
android:padding="4sp"
android:text="Activity1"
android:textSize="20px"
android:layout_width fill_parent
android:layout_height="wrap_content"
android:background="#ff0033cc"
android:text="DatatobesenttoSubActivity:"
android:layout_margin="4dip"
android:textStyle="bold|normal">
</TextView>
<Button
android:id="@+id/btnCallActivity2"
android:layout_width="149px"
android:layout_height="wrap_content"
android:text="CallActivity2"
android:textStyle="bold"
android:padding="6sp"
>
</Button> android:textSize 20px
android:textStyle="bold"
android:textColor="#ff000000"
>
</TextView>
<TextView
android:id="@+id/widget107"
android:layout_width="fill_parent"
android:layout_height="2sp"
>
</TextView>
<TextView
android:id="@+id/label1"
</Button>
<TextView
android:id="@+id/label1Returned"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff0033cc"
android:text="DatareturnedbyActivity2"
android:layout_margin="4dip"
android:textStyle="bold|normal">
</TextView>
</LinearLayout>
24 24
10/18/2011
13
<?xml version="1.0" encoding="utf8"?> android:layout height="wrap content"
12.Android Intents Part2
Intents
Tutorial2:Activity2iscalledtocooperatewithActivity1.Dataistransferredin
abundle
Layout:main2.xml
<?xmlversion 1.0 encoding utf 8 ?>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#ffffff77">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffff9900"
android:padding="4sp"
android:text="Activity2"
android:textSize="20px"
android:textStyle="bold"
android:layout_height wrap_content
android:background="#ff0033cc"
android:text="DataReceivedfromActivity1..."
android:textStyle="normal"
android:layout_margin="7dip">
</TextView>
<Button
android:id="@+id/btnCallActivity1"
android:layout_width="149px"
android:layout_height="wrap_content"
android:padding="6sp"
android:text="CallBack Activity1"
android:textStyle="bold"
>
</Button>
android:textStyle bold
>
</TextView>
<TextView
android:id="@+id/widget107"
android:layout_width="fill_parent"
android:layout_height="2sp"
>
</TextView>
<TextView
android:id="@+id/label2"
android:layout_width="fill_parent"
<TextView
android:id="@+id/spyBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff0033cc"
android:text="(SPY)DataReceivedfromActivity1..."
android:textStyle="normal"
android:layout_margin="7dip">
</TextView>
</LinearLayout>
25 25
12.Android Intents Part2
Intents
AppendixA.BundlingComplexObjects
ExtendingTutorial2toallowActivity1tocreatealocalobject
andpassittoActivity2intotheIPCbundleasserializeddata.
Step1.CreateanObject.MakesureitimplementsSerializable interface.
package cis493.intents3;
import java.io.Serializable;
public class Personimplements Serializable {
private static final long serialVersionUID =1L;
private StringfirstName;
private StringlastName;
26 26
public Person(StringfirstName,StringlastName){
super();
this.firstName =firstName;
this.lastName =lastName;
}
public StringgetFullName(){
return firstName +"" +lastName;
}
}//Person
10/18/2011
14
12.Android Intents Part2
Intents
AppendixA.BundlingComplexObjects
ExtendingTutorial2toallowActivity1tocreatealocalobjectandpassit
toActivity2intotheIPCbundleasserializeddata.
St 2 M dif A ti it 1 C t i t f th P l d dd it t th Step2.ModifyActivity1.CreateaninstanceofthePersonclassandaddittothe
bundleusingthemethodputSerializable (key,object);
//prepareaBundleandaddthedatapiecestobesent
BundlemyData =new Bundle();
... ...
//creatinganobjectandpassingitintothebundle
Personp1=new Person("Maria","Macarena");
myData.putSerializable("person",p1);
27 27
//bindtheBundleandtheIntentthattalkstoActivity2
myIntentA1A2.putExtras(myData);
//callActivity2andwaitforresults
startActivityForResult(myIntentA1A2,IPC_ID);
12.Android Intents Part2
Intents
AppendixA.BundlingComplexObjects
ExtendingTutorial2toallowActivity1tocreatealocalobjectandpassit
toActivity2intotheIPCbundleasserializeddata.
St 3 M dif A ti it 2 C t th i t f th P l i th Step3.ModifyActivity2.CapturetheinstanceofthePersonclassusingthe
methodgetSerializable (key);
//createalocalIntenthandler wehavebeencalled!
IntentmyLocalIntent =getIntent();
//grabthedatapackagewithallthepiecessenttous
BundlemyBundle =myLocalIntent.getExtras();
//extracttheindividualdatapartsofthebundle
... ...
Person p (Person) myBundle getSerializable("person");
28 28
Personp=(Person)myBundle.getSerializable("person");
Stringpval =p.getFullName();
... ...
Note:Theobjectpersonhasacomplexclasstypereceivedas:
classpackageName.Person
10/18/2011
15
12.Android Intents
Intents
Questions?
29 29 29

Potrebbero piacerti anche