Sei sulla pagina 1di 28

10/11/2011

1
Android
12
Android
Intents
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
AndroidDevelopers
http://developer.android.com/index.html
12.Android Intents
Intents
AndroidActivities
AnAndroidapplicationcouldincludeanynumberofactivities.
Anactivity usesthesetContentView(...)methodtoexpose(usually)a
singleUIfromwhichanumberofactionscouldbeperformed.
Activitiesareindependentofeachother;howevertheyusually
cooperateexchangingdataandactions.
Typically,oneoftheactivitiesisdesignatedasthefirstone(main)that
should be presented to the user when the application is launched
22
shouldbepresentedtotheuserwhentheapplicationislaunched.
Movingfromoneactivitytoanotherisaccomplishedbyaskingthe
currentactivitytoexecuteanintent.
Activitiesinteractwitheachotherinanasynchronous mode.
10/11/2011
2
12.Android Intents
Intents
AndroidActivities
AndroidApplication
MainActivity
SubActivity1
intents
results
333
SubActivityn
extras
12.Android Intents
Intents
Takenfrom:http://code.google.com/android/reference/android/content/Intent.html
Intentsareinvokedusingthefollowingoptions
startActivity (intent) launchesan Activity
sendBroadcast (intent) sendsanintenttoanyinterested
BroadcastReceiver components
startService(intent) communicatewithabackground Service.
44
( )
or
bindService(intent,)
g
10/11/2011
3
12.Android Intents
Intents
Takenfrom:http://code.google.com/android/reference/android/content/Intent.html
ThemainargumentsofanIntentare:
1. Action Thebuiltinactiontobeperformed,such
as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN,
orusercreatedactivity
2. Data Theprimarydatatooperateon,suchasaphone
numbertobecalled(expressedasa Uri).
55
Intent:{action+data}
Optionalresults
Activity1 Activity2
12.Android Intents
Intents
Takenfrom:http://code.google.com/android/reference/android/content/Intent.html
Typicallyanintentiscalledasfollows:
Intent myActivity =newIntent (action,data);
startActivity (myActivity);
Primarydata(asanURI)
tel://
http://
666
Builtin
or
usercreated
activity
sendto://
10/11/2011
4
12.Android Intents
Intents
Takenfrom:http://code.google.com/android/reference/android/content/Intent.html
Examples ofaction/datapairsare:
ACTION_DIAL tel:123
Displaythephonedialerwiththegivennumberfilledin.
ACTION_VIEW http://www.google.com
ShowGooglepageinabrowserview.NotehowtheVIEWactiondoeswhatisconsideredthe
mostreasonablethingforaparticularURI.
ACTION_EDIT content://contacts/people/2
Edit information about the person whose identifier is "2".
77
Editinformationaboutthepersonwhoseidentifieris 2 .
ACTION_VIEW content://contacts/people/2
Usedtostartanactivitytodisplay2nd person.
ACTION_VIEW content://contacts/ people/
Displayalistofpeople,whichtheusercanbrowsethrough.Selectingaparticular
persontoviewwouldresultinanewintent
12.Android Intents
Intents
BuiltinStandardActions
ListofstandardactionsthatIntentscanuseforlaunchingactivities(usuallythrough
startActivity(Intent).
ACTION_MAIN
ACTION_VIEW
ACTION_ATTACH_DATA
ACTION_EDIT
ACTION_PICK
ACTION_CHOOSER
ACTION_GET_CONTENT
ACTION DIAL
ACTION_ANSWER
ACTION_INSERT
ACTION_DELETE
ACTION_RUN
ACTION_SYNC
ACTION_PICK_ACTIVITY
ACTION_SEARCH
ACTION WEB SEARCH
888
ACTION_DIAL
ACTION_CALL
ACTION_SEND
ACTION_SENDTO
ACTION_WEB_SEARCH
ACTION_FACTORY_TEST
Foralistofactionssee:
http://developer.android.com/reference/android/content/Intent.html
10/11/2011
5
12.Android Intents
Intents
ACTION_AIRPLANE_MODE_CHANGED
ACTION_ALL_APPS
ACTION_ANSWER
ACTION_ATTACH_DATA
ACTION_BATTERY_CHANGED
ACTION_BATTERY_LOW
ACTION_EDIT
ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE
ACTION_FACTORY_TEST
ACTION_GET_CONTENT
ACTION_GTALK_SERVICE_CONNECTED
ACTION_MEDIA_SCANNER_STARTED
ACTION_MEDIA_SHARED
ACTION_MEDIA_UNMOUNTABLE
ACTION_MEDIA_UNMOUNTED
ACTION_MY_PACKAGE_REPLACED
ACTION_NEW_OUTGOING_CALL
ACTION_SCREEN_OFF
ACTION_SCREEN_ON
ACTION_SEARCH
ACTION_SEARCH_LONG_PRESS
ACTION_SEND
ACTION_SENDTO
ACTION_BATTERY_OKAY
ACTION_BOOT_COMPLETED
ACTION_BUG_REPORT
ACTION_CALL
ACTION_CALL_BUTTON
ACTION_CAMERA_BUTTON
ACTION_CHOOSER
ACTION_CLOSE_SYSTEM_DIALOGS
ACTION_CONFIGURATION_CHANGED
ACTION_GTALK_SERVICE_DISCONNECTED
ACTION_HEADSET_PLUG
ACTION_INPUT_METHOD_CHANGED
ACTION_INSERT
ACTION_INSERT_OR_EDIT
ACTION_LOCALE_CHANGED
ACTION_MAIN
ACTION_MANAGE_PACKAGE_STORAGE
ACTION_MEDIA_BAD_REMOVAL
ACTION_PACKAGE_ADDED
ACTION_PACKAGE_CHANGED
ACTION_PACKAGE_DATA_CLEARED
ACTION_PACKAGE_FIRST_LAUNCH
ACTION_PACKAGE_INSTALL
ACTION_PACKAGE_REMOVED
ACTION_PACKAGE_REPLACED
ACTION_PACKAGE_RESTARTED
ACTION_PASTE
ACTION_SEND_MULTIPLE
ACTION_SET_WALLPAPER
ACTION_SHUTDOWN
ACTION_SYNC
ACTION_SYSTEM_TUTORIAL
ACTION_TIMEZONE_CHANGED
ACTION_TIME_CHANGED
ACTION_TIME_TICK
ACTION_UID_REMOVED
999
Foralistofactionssee:
http://developer.android.com/reference/android/content/Intent.html
ACTION_CREATE_SHORTCUT
ACTION_DATE_CHANGED
ACTION_DEFAULT
ACTION_DELETE
ACTION_DEVICE_STORAGE_LOW
ACTION_DEVICE_STORAGE_OK
ACTION_DIAL
ACTION_DOCK_EVENT
ACTION_MEDIA_BUTTON
ACTION_MEDIA_CHECKING
ACTION_MEDIA_EJECT
ACTION_MEDIA_MOUNTED
ACTION_MEDIA_NOFS
ACTION_MEDIA_REMOVED
ACTION_MEDIA_SCANNER_FINISHED
ACTION_MEDIA_SCANNER_SCAN_FILE
ACTION_PICK
ACTION_PICK_ACTIVITY
ACTION_POWER_CONNECTED
ACTION_POWER_DISCONNECTED
ACTION_POWER_USAGE_SUMMARY
ACTION_PROVIDER_CHANGED
ACTION_REBOOT
ACTION_RUN
ACTION_UMS_CONNECTED
ACTION_UMS_DISCONNECTED
ACTION_USER_PRESENT
ACTION_VIEW
ACTION_VOICE_COMMAND
ACTION_WALLPAPER_CHANGED
ACTION_WEB_SEARCH
12.Android Intents
Intents
Takenfrom:http://code.google.com/android/reference/android/content/Intent.html
Example
Displaythephonedialerwiththegivennumberfilledin.
Intent myAct i vi t y2 = new Intent ( Intent.ACTION_DIAL,
Uri.parse( "tel:555-1234"));
st ar t Act i vi t y( myAct i vi t y2) ;
10 10
10/11/2011
6
12.Android Intents
Intents
Takenfrom:http://code.google.com/android/reference/android/content/Intent.html
Intents SecondaryAttributes
Inadditiontotheprimary action/dataattributes,therearea p y / ,
numberofsecondaryattributesthatyoucanalsoinclude
withanintent,suchas:
1. Category 2.Components
3.Type 4.Extras
Example:DoingaGooglesearchlookingforgolfclubs
11 11
Intent i nt ent = new Intent ( Intent.ACTION_WEB_SEARCH ) ;
i nt ent . putExtra( Sear chManager . QUERY,
" st r ai ght hi t t i ng gol f cl ubs" ) ;
startActivity( i nt ent ) ;
ApparentlytheGoogleanswerisnone
Secondarydata
12.Android Intents
Intents
Takenfrom:http://code.google.com/android/reference/android/content/Intent.html
Intents SecondaryAttributes
Example:Sendingatextmessage(usingextraattributes)
Intent i nt ent = new Intent( Intent.ACTION_SENDTO,
Ur i . par se( " sms: 5551234" ) ) ;
i nt ent putExtra( " sms body" " ar e we pl ayi ng gol f next Sat ur day?" ) ;
12 12
i nt ent . putExtra( " sms_body" , " ar e we pl ayi ng gol f next Sat ur day?" ) ;
st ar t Act i vi t y( i nt ent ) ;
address,sms_bodyarekeywords
10/11/2011
7
12.Android Intents
Intents
Takenfrom:http://code.google.com/android/reference/android/content/Intent.html
Intents SecondaryAttributes
Example:ShowingPictures(usingextraattributes)
Intent myI nt ent = new Intent();
myI nt ent . setType( "i mage/ pi ct ur es/ *") ;
13 13
myI nt ent . setAction(I nt ent . ACTION_GET_CONTENT);
st ar t Act i vi t y( myI nt ent ) ;
12.Android Intents
Intents
1.ACompleteExample:Activity1displaysaninterfacetoacceptaphonenumberand
requests(builtin)Activity2tomakethecall.
<?xml ver si on="1.0" encoding="utf-8"?>
<Li near Layout xml ns: andr oi d="http://schemas.android.com/apk/res/android"
andr oi d: or i ent at i on="vertical"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="fill_parent" >
<Text Vi ew
andr oi d: i d="@+id/label1"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: backgr ound="#ff0000cc"
andr oi d: t ext ="This is Activity1"
andr oi d: t ext St yl e="bold"
andr oi d: t ext Si ze="20sp" />
<Edi t Text
andr oi d: i d="@+id/text1"
andr oi d: l ayout wi dt h="fill parent"
14 14
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="54px"
andr oi d: t ext ="tel:555-1234"
andr oi d: t ext Si ze="18sp" />
<But t on
andr oi d: i d="@+id/btnCallActivity2"
andr oi d: l ayout _wi dt h="149px"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: t ext ="Make Phone Call"
andr oi d: t ext St yl e="bold" />
</ Li near Layout >
10/11/2011
8
12.Android Intents
Intents
1.ACompleteExample:Activity1displaysaninterfacetoacceptaphonenumberand
requests(builtin)Activity2tomakethecall.
15 15
12.Android Intents
Intents
1.ACompleteExample:Activity1displaysaninterfacetoacceptaphonenumberand
requests(builtin)Activity2tomakethecall.
/ / I nt ent Demo1 I nt ent : maki ng a phone cal l / / I nt ent Demo1_I nt ent : maki ng a phone cal l
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 {
Te t Vi e l abel 1
16 16
Text Vi ew l abel 1;
Edi t Text t ext 1;
But t on bt nCal l Act i vi t y2;
10/11/2011
9
12.Android Intents
Intents
1.ACompleteExample:Activity1displaysaninterfacetoacceptaphonenumberand
requests(builtin)Activity2tomakethecall.
@Over r i de
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
set Cont ent Vi ew( R. l ayout . main);
l abel 1 = ( Text Vi ew) f i ndVi ewByI d( R. i d. label1);
t ext 1 = ( Edi t Text ) f i ndVi ewByI d( R. i d. text1);
bt nCal l Act i vi t y2 = ( But t on) f i ndVi ewByI d( R. i d. btnCallActivity2);
bt nCal l Act i vi t y2. set OnCl i ckLi st ener ( new ClickHandler());
}
17 17
}
catch (Exception e) {
Toast . makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}/ / onCr eat e
12.Android Intents
Intents
1.ACompleteExample:Activity1displaysaninterfacetoacceptaphonenumberand
requests(builtin)Activity2tomakethecall.
)private class ClickHandler implements OnClickListener {
@ i @Over r i de
public void onClick(View v) {
try {
/ / myAct i vi t y2 pl aces a phone cal l
/ / f or ACTI ON_CALL or ACTI ON_DI AL
/ / use ' t el : ' f or mat t ed dat a: " t el : 555- 1234"
/ / f or ACTI ON_VI EWuse dat a: " ht t p: / / www. yout ube. com"
/ / ( you al so need I NTERNET per mi ssi on - see Mani f est )
String myData = text1.getText().toString();
Intent myActivity2 = new Intent(Intent.ACTION_DIAL,
18 18
_
Uri.parse(myData));
startActivity(myActivity2);
}
catch (Exception e) {
Toast . makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}/ / onCl i ck
}/ / Cl i ckHandl er
}/ / I nt ent Demo1
10/11/2011
10
12.Android Intents
Intents
1.ACompleteExample:Activity1displaysaninterfacethatacceptsfromtheusera
phonenumberandrequests(builtin)Activity2tomakethecall.
<?xml ver si on="1.0" encoding="utf-8"?>
<mani f est xml ns: andr oi d="http://schemas.android.com/apk/res/android"
package="cis493.intents"
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="@drawable/icon"
android:label="@string/app_name">
<act i vi t y andr oi d: name=".IntentDemo1
andr oi d: l abel ="@string/app_name">
<i nt ent - f i l t er >
<act i on andr oi d: name="android.intent.action.MAIN" />
Action/category
19 19
<cat egor y andr oi d: name="android.intent.category.LAUNCHER" />
</ i nt ent - f i l t er >
</ act i vi t y>
</ appl i cat i on>
<uses- sdk andr oi d: mi nSdkVer si on="3" />
</ mani f est >
12.Android Intents
Intents
BuiltinStandardBroadcast Actions
ListofstandardactionsthatIntents canuseforreceivingbroadcasts(usually
throughregisterReceiver(BroadcastReceiver,IntentFilter) ora<receiver> tag
i if t) inamanifest).
ACTION_TIME_TICK
ACTION_TIME_CHANGED
ACTION_TIMEZONE_CHANGED
ACTION_BOOT_COMPLETED
ACTION_PACKAGE_ADDED
ACTION_PACKAGE_CHANGED
ACTION PACKAGE REMOVED
20 20
ACTION_PACKAGE_REMOVED
ACTION_UID_REMOVED
ACTION_BATTERY_CHANGED
10/11/2011
11
12.Android Intents
Intents
MoreExamples: UsingStandardActions
CallImmediatelyy
Modifythecomplete example1replacing
themethodClickHandlerwith
thefollowingcode
St r i ng myDat a = "tel:555-1234";
21 21
I nt ent myAct i vi t y2 = new Intent(Intent.ACTION_CALL,
Ur i . parse(myData));
st ar t Act i vi t y( myAct i vi t y2) ;
NeedsPermission:
<usespermissionandroid:name="android.permission.CALL_PHONE"/>
12.Android Intents
Intents
MoreExamples: UsingStandardActions
ShowallyourContacts y
Modifythecomplete example1replacing
themethodClickHandlerwith
thefollowingcode
St r i ng myDat a = "content://contacts/people/";
22 22
St r i ng myDat a = "content://contacts/people/";
I nt ent myAct i vi t y2 = new Intent(Intent.ACTION_VIEW,
Ur i . parse(myData));
st ar t Act i vi t y( myAct i vi t y2) ;
10/11/2011
12
12.Android Intents
Intents
MoreExamples: UsingStandardActions
ShowaParticularContact(ID=2) ( )
Modifythecomplete example1replacing
themethodClickHandlerwith
thefollowingcode
St r i ng myDat a = "content://contacts/people/8";
23 23
St r i ng myDat a = "content://contacts/people/8";
I nt ent myAct i vi t y2 = new Intent(Intent.ACTION_VIEW,
Ur i . parse(myData));
st ar t Act i vi t y( myAct i vi t y2) ;
12.Android Intents
Intents
MoreExamples: UsingStandardActions
EditaParticularContact(ID=8) ( )
Modifythecomplete example1replacing
themethodClickHandlerwith
thefollowingcode
St r i ng myDat a = "content://contacts/people/8";
24 24
St r i ng myDat a = "content://contacts/people/8";
I nt ent myAct i vi t y2 = new Intent(Intent.ACTION_EDIT,
Ur i . parse(myData));
st ar t Act i vi t y( myAct i vi t y2) ;
10/11/2011
13
12.Android Intents
Intents
MoreExamples: UsingStandardActions
ViewaWebpage p g
Modifythecomplete example1replacing
themethodClickHandlerwith
thefollowingcode
St r i ng myDat a = "http://www.youTube.com";
25 25
I nt ent myAct i vi t y2 = new Intent(Intent.ACTION_VIEW,
Ur i . parse(myData));
st ar t Act i vi t y( myAct i vi t y2) ;
Caution.AddtotheManifestarequesttousetheInternet:
<uses- per mi ssi on andr oi d: name="android.permission.INTERNET" />
12.Android Intents
Intents
MoreExamples: UsingStandardActions
GeoMappinganAddress pp g
ProvideageoCode expressionholdingastreet
address(orplace,suchasgoldengateca)
Replacespaceswith+.
St r i ng geoCode =
"geo: 0, 0?q=1860+east +18t h+st r eet +cl evel and+oh" ;
26 26
I nt ent i nt ent = new Intent(Intent.ACTION_VIEW,
Ur i . parse(geoCode));
st ar t Act i vi t y( i nt ent ) ;
ModifytheManifestaddingthefollowingrequests:
<uses- per mi ssi on andr oi d: name=" andr oi d. per mi ssi on. ACCESS_COARSE_LOCATI ON" / >
<uses- per mi ssi on andr oi d: name=" andr oi d. per mi ssi on. I NTERNET" / >
10/11/2011
14
12.Android Intents
Intents
MoreExamples: UsingStandardActions
GeoMappingCoordinates(latitude,longitude) pp g ( , g )
ProvideageoCode holdinglatitudeand
longitude(alsoanaddittional zoom?z=xxwith
xxinrange1..23)
St r i ng geoCode =
"geo:41.5020952,-81.6789717";
27 27
I nt ent i nt ent = new Intent(Intent.ACTION_VIEW,
Ur i . parse(geoCode));
st ar t Act i vi t y( i nt ent ) ;
ModifytheManifestaddingthefollowingrequests:
<uses- per mi ssi on andr oi d: name=" andr oi d. per mi ssi on. ACCESS_COARSE_LOCATI ON" / >
<uses- per mi ssi on andr oi d: name=" andr oi d. per mi ssi on. I NTERNET" / >
MoreExamples
//Gettingdrivingdirections:howtogofromloaction AtolocationB?
Intentintent=newIntent(android.content.Intent.ACTION_VIEW,
U i ("htt // l / ? dd 9 938083 84 054430&d dd 9 926392 84 055964"))
12.Android Intents
Intents
Uri.parse("http://maps.google.com/maps?saddr=9.938083,84.054430&daddr=9.926392,84.055964"));
startActivity(intent);
28
10/11/2011
15
MoreExamples
//useamnemonictoarticulateanaddress
StringthePlace ="ClevelandStateUniversity";
Intent intent new Intent(android content Intent ACTION VIEW
12.Android Intents
Intents
Intentintent =newIntent(android.content.Intent.ACTION_VIEW,
Uri.parse("geo:0,0?q=("+thePlace +")"));
startActivity(intent);
29
12.Android Intents
Intents
MoreExamples: UsingStandardActions
GeoMapping GoogleStreetView pp g g
geoCode Uristructure:
google.streetview:cbll=lat,lng&cbp=1,
yaw,,pitch,zoom&mz=mapZoom
Reference:http://developer.android.com/guide/appendix/gappintents.html
St r i ng geoCode =
"google.streetview:cbll=41.5020952,81.6789717&cbp=1,270,,45,1&mz=1";
30 30
I nt ent i nt ent = new Intent(Intent.ACTION_VIEW,
Ur i . parse(geoCode));
st ar t Act i vi t y( i nt ent ) ;
ModifytheManifestaddingthefollowingrequests:
<uses- per mi ssi on andr oi d: name=" andr oi d. per mi ssi on. ACCESS_COARSE_LOCATI ON" / >
<uses- per mi ssi on andr oi d: name=" andr oi d. per mi ssi on. I NTERNET" / >
10/11/2011
16
12.Android Intents
Intents
MoreExamples: UsingStandardActions
LaunchingtheMusicPlayer g y
Reference:http://developer.android.com/guide/appendix/gappintents.html
/ / l aunch musi c pl ayer
Intent myAct i vi t y2 =
31 31
Intent myAct i vi t y2
new Intent("android.intent.action.MUSIC_PLAYER");
st ar t Act i vi t y( myAct i vi t y2) ;
12.Android Intents
Intents
MoreExamples: UsingStandardActions
PlayingasongstoredintheSDcard y g g
Reference:http://developer.android.com/guide/appendix/gappintents.html
/ / pl ay song "amar cor d. mp3" saved i n t he SD
Intent myAct i vi t y2 =
new Intent( andr oi d. cont ent . I nt ent . ACTI ON_VI EW) ;
32 32
Ur i dat a = Ur i . parse("file:///sdcard/amarcord.mp3");
St r i ng t ype = " audi o/ mp3";
myAct i vi t y2. set Dat aAndType( dat a, t ype) ;
st ar t Act i vi t y( myAct i vi t y2) ;
10/11/2011
17
12.Android Intents
Intents
MoreExamples: UsingStandardActions
SendingMMS g
Addpicture#1fromSDtoMMS
Reference:http://developer.android.com/guide/appendix/gappintents.html
/ / send mms at t ach pi ct ur e #1 t o i t
Ur i ur i = Ur i . parse("content://media/external/images/media/1") ;
33 33
I nt ent myAct i vi t y2 = new Intent(Intent.ACTION_SEND);
myAct i vi t y2. put Ext r a( " addr ess" , " 555- 1234") ;
myAct i vi t y2. put Ext r a( " sms_body" , " some t ext message goes her e" ) ;
myAct i vi t y2. put Ext r a( I nt ent . EXTRA_STREAM, uri);
myAct i vi t y2. set Type( "i mage/ png" ) ;
st ar t Act i vi t y( myAct i vi t y2) ;
12.Android Intents
Intents
MoreExamples: UsingStandardActions
SendingEmail g
Reference:http://developer.android.com/guide/appendix/gappintents.html
/ / send emai l
Ur i ur i = Ur i . parse("mailto:v.matos@csuohio.edu");
I nt ent myAct i vi t y2 = new Intent(Intent.ACTION_SENDTO, uri);
34 34
/ / you may ski p t he next t wo pi eces [ subj ect / t ext ]
myAct i vi t y2. put Ext r a( I nt ent . EXTRA_SUBJECT,
"subject goes here");
myAct i vi t y2. put Ext r a( I nt ent . EXTRA_TEXT,
"The email's body goes here");
st ar t Act i vi t y( myAct i vi t y2) ;
10/11/2011
18
12.Android Intents
Intents
MoreExamples: UsingStandardActions
SettingSystem g y
Reference:http://developer.android.com/reference/android/provider/Settings.html
Intent i nt ent = new Intent(
35 35
(
andr oi d. pr ovi der . Set t i ngs. ACTION_SETTINGS);
st ar t Act i vi t y( i nt ent ) ;
12.Android Intents
Intents
MoreExamples: UsingStandardActions
SettingSystemLocale: g y
Language&Keyboard
Reference:http://developer.android.com/reference/android/provider/Settings.html
I nt ent i nt ent = new Intent(
android.provider.Settings.ACTION_LOCALE_SETTINGS);
36 36
st ar t Act i vi t y( i nt ent ) ;
10/11/2011
19
37
12.Android Intents
Intents
StartingActivitiesandGettingResults
ThestartActivity(Intent) methodisusedtostartanewactivity,which y( ) y,
willbeplacedatthetopoftheactivitystack.Thecallerhowever
continuestoexecuteinitsownthread.
Sometimesyouwanttogetaresultback
fromthecalledsubactivitywhenitends.
F l t t ti it th t l t th i k
38 38
Forexample,youmaystartanactivitythatlettheuserpickaperson
fromalistofcontacts;whenitends,itreturnsthepersonthatwas
selected.
10/11/2011
20
12.Android Intents
Intents
StartingActivitiesandGettingResults
Inordertogetresultsbackfromthecalledactivityweusethemethod g y
startActivityForResult (Intent,requestCodeID )
WhererequestCodeID isanarbitraryvalueyouchoosetoidentifythe
call.
The result sent by the subactivity could be picked up through the
39 39
Theresultsentbythesub activitycouldbepickedupthroughthe
Listenerlikeasynchronousmethod
onActivityResult (requestCodeID,resultCode,Intent)
12.Android Intents
Intents
StartingActivitiesandGettingResults
Beforeaninvokedactivityexits,itcancallsetResult (resultCode)
toreturnaterminationsignalbacktoitsparent.
Itisconvenienttosupplyaresultcode,whichcanbethestandardresults
Activity.RESULT_CANCELED,Activity.RESULT_OK,
oranycustomvalues.
Allofthisinformationcanbecapturebackontheparent's
40 40
onActivityResult (int requestCodeID,int resultCode,Intentdata)
Ifachildactivityfailsforanyreason(suchascrashing),theparentactivitywill
receivearesultwiththecodeRESULT_CANCELED.
10/11/2011
21
12.Android Intents
Intents
StartingActivitiesandGettingResults
Intent:{action+data+requestCodeID }
Activity1
startActivityForResult

Activity2
41 41
requestCodeID
resultCode
optionaldata
__________________
onActivityResult()

_________________
onResult()

12.Android Intents
Intents
Example2.Letsplaygolf Callforateetime.
1. Showallcontactsandpickaparticularone(Intent.ACTION_PICK).
2. ForasuccessfulinteractionthemainactivityacceptsthereturnedURI
id tif i th t t ll ( t t // t t / l / ) identifyingthepersonwewanttocall(content://contacts/people/n).
3. Nicelyshowtheselectedcontactsentryallowingcalling,texting,
emailingactions(Intent.ACTION_VIEW).
Usersmain
Activity1
BuiltinActivity2
(showcontactlist)
Intent.ACTION_PICK
ContactsUri
42 42
Activity1
BuiltinActivity3
(showselected
contact)
Intent.ACTION_VIEW
Call
Sendtextmessage
Sendemail
10/11/2011
22
12.Android Intents
Intents
Example2.Letsplaygolf Callforateetime.
Cont.
43 43
Intent.ACTION_PICK Intent.ACTION_VIEW MainActivity
12.Android Intents
Intents
Example2(cont.)Letsplaygolf Callforateetime
44 44
Placethecall SelectedcontactsURI Terminatethecall
10/11/2011
23
12.Android Intents
Intents
Example2.Callingasubactivity,receivingresults.
/ / I nt ent Demo2_I nt ent : maki ng a phone cal l
/ / r ecei vi ng r esul t s f r oma sub- act i vi t y / / g y
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 {
Text Vi ew l abel 1;
45 45
Text Vi ew l abel 1;
Edi t Text t ext 1;
But t on bt nCal l Act i vi t y2;
12.Android Intents
Intents
Example2.Callingasubactivity,receivingresults.
@Over r i de
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
set Cont ent Vi ew( R. l ayout . main);
l abel 1 = ( Text Vi ew) f i ndVi ewByI d( R. i d. label1);
t ext 1 = ( Edi t Text ) f i ndVi ewByI d( R. i d. text1);
bt nCal l Act i vi t y2 = ( But t on) f i ndVi ewByI d( R. i d. btnPickContact);
bt nCal l Act i vi t y2. set OnCl i ckLi st ener ( new ClickHandler());
}
catch (Exception e) {
46 46
catch (Exception e) {
Toast . makeText(getBaseContext(),
e. get Message( ) , Toast . LENGTH_LONG).show();
}
}/ / onCr eat e
10/11/2011
24
12.Android Intents
Intents
Example2.Callingasubactivity,receivingresults.
private class ClickHandler implements OnClickListener {
@O i d @Over r i de
public void onClick(View v) {
try {
/ / myDat a r ef er t o: cont ent : / / cont act s/ peopl e/
St r i ng myDat a = t ext 1. get Text ( ) . t oSt r i ng( ) ;
/ / you may al so t r y ACTI ON_VI EWi nst ead
I nt ent myAct i vi t y2 = new Intent(Intent.ACTION_PICK,
Ur i . parse(myData));
/ / st ar t myAct i vi t y2.
/ / Tel l i t t hat our r equest CodeI D ( or ni ckname) i s 222
47 47
st ar t Act i vi t yFor Resul t ( myAct i vi t y2, 222) ;
/ / Toast . makeText ( get Appl i cat i onCont ext ( ) ,
/ / " I can' t wai t f or you", 1) . show( ) ;
}
catch (Exception e) {
l abel 1. set Text ( e. get Message( ) ) ;
}
}/ / onCl i ck
}/ / Cl i ckHandl er
12.Android Intents
Intents
Example2.Callingasubactivity,receivingresults.
@Over r i de
protected void onActivityResult(int requestCode,
Listener
p y ( q ,
int resultCode,
I nt ent dat a) {
super.onActivityResult(requestCode, resultCode, data);
try {
/ / use r equest Code t o f i nd out who i s t al ki ng back t o us
switch (requestCode){
case (222): {
/ / 222 i s our f r i endl y cont act - pi cker act i vi t y
if (resultCode == Activity.RESULT_OK) {
St r i ng sel ect edCont act = dat a. get Dat aSt r i ng( ) ;
/ / i t wi l l r et ur n an URI t hat l ooks l i ke:
Listener
48 48
/ / i t wi l l r et ur n an URI t hat l ooks l i ke:
/ / cont ent : / / cont act s/ peopl e/ n
/ / wher e n i s t he sel ect ed cont act s' I D
l abel 1. set Text ( sel ect edCont act . t oSt r i ng( ) ) ;
/ / show a ' ni ce' scr een wi t h t he sel ect ed cont act
I nt ent myAct 3 = new Intent (Intent.ACTION_VIEW,
Ur i . parse(selectedContact));
st ar t Act i vi t y( myAct 3) ;
}
10/11/2011
25
12.Android Intents
Intents
Example2.Callingasubactivity,receivingresults.
else {
/ / user pr essed t he BACK but t on / / p
l abel 1. set Text ( " Sel ect i on CANCELLED "
+ r equest Code + " " + r esul t Code) ;
}
break;
}
}/ / swi t ch
}
catch (Exception e) {
Toast . makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
49 49
}
}/ / onAct i vi t yResul t
}/ / I nt ent Demo2
12.Android Intents
Intents
Example2.Callingasubactivity,receivingresults.
<?xml ver si on="1.0" encoding="utf-8"?>
<Li near Layout xml ns: andr oi d="http://schemas.android.com/apk/res/android"
andr oi d: or i ent at i on="vertical" andr oi d: or i ent at i on vertical
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="fill_parent >
<Text Vi ew
andr oi d: i d="@+id/label1"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: backgr ound="#ff0000cc"
andr oi d: t ext ="This is Activity1"
andr oi d: t ext St yl e="bold"
andr oi d: t ext Si ze="20sp/ >
<Edi t Text
andr oi d: i d="@+id/text1"
50 50
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="54px"
andr oi d: t ext ="content://contacts/people/"
andr oi d: t ext Si ze="18sp / >
<But t on
andr oi d: i d="@+id/btnPickContact"
andr oi d: l ayout _wi dt h="149px"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: t ext ="Pick a Contact"
andr oi d: t ext St yl e="bold / >
</ Li near Layout >
10/11/2011
26
12.Android Intents
Intents
Example3.ShowingPicturesandVideo Callingasubactivity,receivingresults.
private void showSoundTracks() {
I nt ent myI nt ent = new Intent();
Allvideosandallstillimages
I nt ent myI nt ent new Intent();
myI nt ent . set Type( " vi deo/ *, i mages/ *" ) ;
myI nt ent . set Act i on( I nt ent . ACTION_GET_CONTENT);
st ar t Act i vi t yFor Resul t ( myI nt ent , 0) ;
}/ / showSoundTr acks
@Over r i de
protected void onActivityResult(int requestCode, int resultCode, I nt ent i nt ent ) {
super.onActivityResult(requestCode, resultCode, intent);
if ((requestCode == 0) && (resultCode == Activity.RESULT_OK)) {
51 51
St r i ng sel ect edI mage = i nt ent . get Dat aSt r i ng( ) ;
Toast . makeText(this, selectedImage, 1).show();
/ / show a ' ni ce' scr een wi t h t he sel ect ed i mage
I nt ent myAct 3 = new Intent(Intent.ACTION_VIEW, Uri. parse(selectedImage));
st ar t Act i vi t y( myAct 3) ;
}
}/ / onAct i vi t yResul t
12.Android Intents
Intents
Example3.ShowingPicturesandVideo Callingasubactivity,receivingresults.
video
52 52
10/11/2011
27
12.Android Intents
Intents
Example4.Showing/PlayingSoundTracks Callingasubactivity,receivingresults.
private void showSoundTracks() {
I nt ent myI nt ent = new Intent();
myI nt ent . set Type( " audi o/ mp3" ) ;
myI nt ent . set Act i on( I nt ent . ACTION GET CONTENT); y ( _ _ );
st ar t Act i vi t yFor Resul t ( myI nt ent , 0) ;
}/ / showSoundTr acks
Thereturnedstringvalueissimilartothefollowing
content://media/external/audio/media/14
ACTION_VIEWonthatUriwouldproducearesult
similartotheimageontheright
53 53
12.Android Intents
Intents
Questions?
54 54 54
10/11/2011
28
12.Android Intents
Intents
BuiltinStandardBroadcast Actions
ListofstandardactionsthatIntents canuseforreceivingbroadcasts(usually
throughregisterReceiver(BroadcastReceiver,IntentFilter) ora<receiver> tag
i if t) inamanifest).
ACTION_TIME_TICK
ACTION_TIME_CHANGED
ACTION_TIMEZONE_CHANGED
ACTION_BOOT_COMPLETED
ACTION_PACKAGE_ADDED
ACTION_PACKAGE_CHANGED
ACTION PACKAGE REMOVED
55 55 55
ACTION_PACKAGE_REMOVED
ACTION_UID_REMOVED
ACTION_BATTERY_CHANGED
12.Android Intents
Intents
Appendix:GettingPermissions
56 56 56
Becomes:
<usespermissionandroid:name="android.permission.CALL_PHONE"></usespermission>

Potrebbero piacerti anche