Android Activities and Tasks series – Intent flags
2011-03-23 14:35
375 查看
出处:http://blog.akquinet.de/2010/04/15/android-activites-and-tasks-series-intent-flags/Theprevious
post
oftheActivitiesandTasks
seriesgavean
introductiontotheconceptsbehindactivitiesandtasks.Wehaveseen
thatactivitiescorrespondtovisiblescreensintheUI,thatactivities
aregroupedasstackswithintasks,andtasksaresenttothe
backgroundandforegroundasatomicunits.Inthispostoftheseries,
wefocusonAndroid’sintent
conceptandaddressthefollowing
questions:Whatareintents
?Howdoweusethemtolaunch
activities?Whatoptions(flags)doesAndroidprovidetocustomize
this
launch?(e.g.intermsoftargettaskoractivityinstancecreation)Inordertoeaseunderstandingofintentsandtheirvariousflags,
akquinetModularandMobileSolutionsprovidesanAndroidapplicationto
experimentwithintentflags.Withit,youcanstartdifferenttypesof
activities,specifyingtheintentflagsyouwanttopass,andexamine
theeffects.InstallitbypointingyourAndroidbrowsertothis
URL
.
isadatastructurecontainingadescriptionofa
to-be-performedoperation.Thisoperationprimarilyconsistsofanaction
andofdata
tooperateon,althoughtherearevariousoptional
parameterstodescribetheoperationinmoredetail.Technically
speaking,thisactionisjustaconstant,eitherapre-definedonefrom
Android,likeACTION_VIEW
orACTION_EDIT
,oracustom
onethatwecandefineourselves.AnintentisalwayshandledbyanAndroidcomponent,namelyan
activity,aservice,abroadcastreceiveroracontentprovider.Inthis
blogpostseries,wewillfocusonactivitiesasintenthandlers.For
ourpurposes,anintentisusedtolaunchanactivity.Tocreateanintentandlaunchanactivitywithit,wecanwritethe
followingcodewithinourcaller
activity:
Inthisexample,wegivetwoparameterstotheIntentconstructor:Theaction
tobeperformed(hereview
)
andthecorrespondingdata
(hereawebpageURL).Then,we
simplypasstheIntent
objecttostartActivity(Intent)
.
Basically,whatwedohereistellingAndroidthatwewanttoviewthe
akquinethomepage.Androidwilllookforactivitiescapableofhandling
thatintent,whichinthiscaseisawebbrowseractivity
,and
startit.Notethatanyactivitycanbedeclaredcapableofhandling
certainintenttypesbydefiningintent
filtersintheapplication’sAndroidManifest.xmlfile.InsteadoflettingAndroidchooseasuitableactivity,anintentmay
alsonametheto-be-launchedtargetactivityexplicitly
by
specifyingthetargetactivity’sclass,likeso:Intentintent=newIntent(this,MyActivity.class);startActivity(intent);
Whenrun,thiscodesnippethasthefollowingconsequences:AnewinstanceofMyActivity
iscreatedTheinstanceispushedontopofthecurrenttask’sstack,whichis
theonethecallingactivityisin.Theactivityisstartedandbroughttotheforeground.
ontheintentinstancebeforepassingtheintenttostartActivity(Intent)
,
forexample:intent.addFlag(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);Thiswillbringanexistinginstanceofthecalledactivitytype
presentinthecurrentstacktotheforeground(ifthereissuchan
instance)insteadofcreatinganewinstance.Android2.0defines
variousintentflags,whicharenowexplainedinmoredetail.FLAG_ACTIVITY_BROUGHT_TO_FRONT
Thisflagissetbythesystemasanindicationthatanexisting
activitywithlaunchmodesingleTask
hasbeencalledand
reused.Activitylaunchmodesarediscussedinmoredetailinthenext
blogpost.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
Bringingatask
toforegroundafterusingflagCLEAR_WHEN_TASK_RESETThisflagmarksthecalledactivityandallactivitiesputontopof
ittobecleared(removedfromthestack)whenthetaskisreset.This
resetisperformedassoonasthetaskisbroughttotheforeground
usingFLAG_ACTIVITY_RESET_TASK_IF_NEEDED
,whichisalwaysset
bythesystemwhentheuserresumesataskfromthehomescreen,the
mainmenuorthelistofrecentlystartedactivites.Youcanusethistodefineapointinthetaskstackfromwhereall
startedactivitiesshouldbe“forgotten”oncethetaskissenttothe
background.FLAG_ACTIVITY_CLEAR_TOP
UsingflagCLEAR_TOPto
launchanactivityIfthereisalreadyaninstanceofthecalledactivitytypepresent
inthestack,thenthisinstanceisbroughttotheforegroundinsteadof
creatinganewinstance.Also,allactivitiesinthestackthatreside
ontopofthatinstanceareclearedfromthestack.Forexample,
assumingthatthecurrentactivitystackisABCDE
,launchingan
activityoftypeC
willclearactivitiesD
andE
fromthetaskandresultinthestackABC
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
Normally,whenlaunchinganactivityinanewtask
,the
targetactivityisshowninthelistofrecentlylaunchedactivities
(accessiblevialongpressofthehome
button).Forexample,
thisisthecasewhenlaunchingthebrowserfromyouractivitytorender
awebpage.Usingthisflag,wecansuppressthatbehavior,effectively
excludingthetargetactivityfromthelistofrecentlylaunched
activities.FLAG_ACTIVITY_FORWARD_RESULT
Bydefault,inorderforanactivityB
tobeableto
propagatearesultbacktothecallingactivityA
,AhastousethemethodstartActivityForResult(Intent)
insteadof
methodstartActivity(Intent)
tostartB
.WhenB
definesitsresultviasetResult(intresultCode)
andfinishes,
thecallbackmethodonActivityResult()
iscalledonA
wheretheresultcanberetrieved.Resulting
forwardingwithFlagFORWARD_RESULTSupposenowthatB
callsanotheractivityC
,which
definestheresult,andwewanttoforwardthatresultbacktoA
.
InordertoavoidhavingtopassresultsmanuallyfromB
toA
,
Androidprovidesthisflag.Inourexample,thismeansthatB
callsC
,specifying
theforwardflagandusingstartActivity(Intent)
.Cmaythendefinearesult,whichisforwardedbacktoAautomaticallyonceC
andB
arefinished.Thecallback
methodonActivityResult()
iscalledonA
butnot
calledontheintermediateactivityB
asB
only
forwardstheresultinsteadofexplicitlyhandlingit.NotethattheflagmayonlybeusedinconjunctionwithstartActivity(Intent)
,
notwithstartActivityForResult(Intent)
,becauseanactivity
usingthelattermethodmarkstheendofaforwardingchainandshould
handletheresultinitscallbackmethod.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
Thisflagissetbythesystemasanindicationthatanactivityhas
beenlaunchedfromthelistofrecentlylaunchedactivities.FLAG_ACTIVITY_MULTIPLE_TASK
ThisflaghasnoeffectunlessusedinconjunctionwithFLAG_ACTIVITY_NEW_TASK
.
Ifusedtogether,anewtaskisalwayscreatedandanewinstanceof
thecalledactivitytypebecomesthefirst(andatthattime,theonly)
elementofthattask.
FLAG_ACTIVITY_NEW_TASK
Ifthisflagisusedonitsown(withoutFLAG_ACTIVITY_MULTIPLE_TASK
),
anewtaskisonlycreatedifthereisnotalreadyataskpresentthat
thetargetactivityhasanaffinity
for(taskaffinitiesare
examinedmorecloselyinthenextblogpost).Ifsuchataskalready
exists,theactivityisputintothattaskinsteadofcreatinganew
one.Asallactivitiesspecifiedwithinthesameapplicationhaveadefault
affinitytoremaininthesametask(thiscanbecustomized),starting
anactivitydefinedinthesameapplicationasthecallingactivity
usingthisflagwillnotcreateanewtask,unlessFLAG_ACTIVITY_MULTIPLE_TASK
isspecifiedaswell.FLAG_ACTIVITY_NO_ANIMATION
IntroducedwithAndroid2.0,thisflagdisablestheusualanimation
accompaniedbyanactivitytransition.Forexample,thiscanbeusedto
callanactivitythatitselflaunchesanotheractivitywithoutfurther
userinteraction,resultinginonlyonetransitionanimationtobeshown
insteadoftwo.FLAG_ACTIVITY_NO_HISTORY
Thisflagimpliesthatthecalledactivityisnotkeptinthetask’s
stack.Whennavigatingaway,theusercannotreturntoit.Forexample,
thisisusefultolaunchactivitiesthatperformanimmediatedispatch
toanotheractivity.Thisactivityisconsequentlyskippediftheuser
pressestheback
buttonasitisnotkeptinthestack.FLAG_ACTIVITY_NO_USER_ACTION
Thisflagmaybeusedasanindicationthattheactivitytransition
isnotanactiondirectlyperformedbytheuserbutratheranautomatic
one.Forexample,thisistrueforthecall-inactivitythatis
automaticallylaunchedwhenthedevicereceivesaphonecall.
Technically,itmeansthattheinvocationofcallbackmethodonUserLeaveHint()
onthecalleractivityissuppressed.FLAG_ACTIVITY_REORDER_TO_FRONT
Startingan
activitywithFlagREORDER_TO_FRONTIfthereisalreadyaninstanceofthecalledactivitytypepresent
inthetaskstack,thatinstanceisbroughttotheforegroundwhilethe
restofthestackiskeptintact.Thiseffectivelyreordersthestack.
Forexample,assumingthatthecurrentactivitystackisABCDEF
,
launchinganactivityoftypeC
usingthisflagwillresultin
thenewstackABDEFC
.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
Thisflaghasnoeffectunlesstheintentcreatesanewtaskor
bringsanexistingtasktotheforeground.Inthatcase,thetaskis
reset,meaningthattaskaffinitiesareapplied(resultinginactivities
beingmovedfromortothistask)andthat,giventhatFLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
issetaswell,thetaskisclearedaccordingthatflag’s
specification.FLAG_ACTIVITY_SINGLE_TOP
Ifaninstanceofthetargetactivityisalreadyatthetopofthe
stack,nonewinstanceiscreated.
applicationtohelpyouunderstandtheeffectsoftheintentflags.It
letsyoustartexemplaryactivitiesusingarbitraryintentflagsand
inspecttheeffectsontheresultingtaskstack.
Youcandownloadthetoolhere
.
Thesourcecodeisalsoavailableongithub
.Alldescribedbehaviornotonlydependsonintentflagsspecified,
butalsoonattributesdefinedonthecalledactivitytype(inAndroidManifest.xml
),
includingtaskaffinitiesandlaunchmodes.Whileintentflagsare
specifiedbythecaller,launchmodesandaffinitiesarepropertiesof
thecallee.Thosewillbediscussedinthenext
post
ofthisseries.
post
oftheActivitiesandTasks
seriesgavean
introductiontotheconceptsbehindactivitiesandtasks.Wehaveseen
thatactivitiescorrespondtovisiblescreensintheUI,thatactivities
aregroupedasstackswithintasks,andtasksaresenttothe
backgroundandforegroundasatomicunits.Inthispostoftheseries,
wefocusonAndroid’sintent
conceptandaddressthefollowing
questions:Whatareintents
?Howdoweusethemtolaunch
activities?Whatoptions(flags)doesAndroidprovidetocustomize
this
launch?(e.g.intermsoftargettaskoractivityinstancecreation)Inordertoeaseunderstandingofintentsandtheirvariousflags,
akquinetModularandMobileSolutionsprovidesanAndroidapplicationto
experimentwithintentflags.Withit,youcanstartdifferenttypesof
activities,specifyingtheintentflagsyouwanttopass,andexamine
theeffects.InstallitbypointingyourAndroidbrowsertothis
URL
.
Intentsandactivitylaunching
Anintentisadatastructurecontainingadescriptionofa
to-be-performedoperation.Thisoperationprimarilyconsistsofanaction
andofdata
tooperateon,althoughtherearevariousoptional
parameterstodescribetheoperationinmoredetail.Technically
speaking,thisactionisjustaconstant,eitherapre-definedonefrom
Android,likeACTION_VIEW
orACTION_EDIT
,oracustom
onethatwecandefineourselves.AnintentisalwayshandledbyanAndroidcomponent,namelyan
activity,aservice,abroadcastreceiveroracontentprovider.Inthis
blogpostseries,wewillfocusonactivitiesasintenthandlers.For
ourpurposes,anintentisusedtolaunchanactivity.Tocreateanintentandlaunchanactivitywithit,wecanwritethe
followingcodewithinourcaller
activity:
Intentintent=
new
Intent(Intent.ACTION_VIEW,
Uri.parse(
"http://www.akquinet.com/
"
);startActivity(intent);
tobeperformed(hereview
)
andthecorrespondingdata
(hereawebpageURL).Then,we
simplypasstheIntent
objecttostartActivity(Intent)
.
Basically,whatwedohereistellingAndroidthatwewanttoviewthe
akquinethomepage.Androidwilllookforactivitiescapableofhandling
thatintent,whichinthiscaseisawebbrowseractivity
,and
startit.Notethatanyactivitycanbedeclaredcapableofhandling
certainintenttypesbydefiningintent
filtersintheapplication’sAndroidManifest.xmlfile.InsteadoflettingAndroidchooseasuitableactivity,anintentmay
alsonametheto-be-launchedtargetactivityexplicitly
by
specifyingthetargetactivity’sclass,likeso:Intentintent=newIntent(this,MyActivity.class);startActivity(intent);
iscreatedTheinstanceispushedontopofthecurrenttask’sstack,whichis
theonethecallingactivityisin.Theactivityisstartedandbroughttotheforeground.
Customizingthelaunchofactivitiesviaintentflags
ThedescribedbehaviorcanbemodifiedbyspecifyingintentflagsontheintentinstancebeforepassingtheintenttostartActivity(Intent)
,
forexample:intent.addFlag(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);Thiswillbringanexistinginstanceofthecalledactivitytype
presentinthecurrentstacktotheforeground(ifthereissuchan
instance)insteadofcreatinganewinstance.Android2.0defines
variousintentflags,whicharenowexplainedinmoredetail.FLAG_ACTIVITY_BROUGHT_TO_FRONT
Thisflagissetbythesystemasanindicationthatanexisting
activitywithlaunchmodesingleTask
hasbeencalledand
reused.Activitylaunchmodesarediscussedinmoredetailinthenext
blogpost.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
toforegroundafterusingflagCLEAR_WHEN_TASK_RESETThisflagmarksthecalledactivityandallactivitiesputontopof
ittobecleared(removedfromthestack)whenthetaskisreset.This
resetisperformedassoonasthetaskisbroughttotheforeground
usingFLAG_ACTIVITY_RESET_TASK_IF_NEEDED
,whichisalwaysset
bythesystemwhentheuserresumesataskfromthehomescreen,the
mainmenuorthelistofrecentlystartedactivites.Youcanusethistodefineapointinthetaskstackfromwhereall
startedactivitiesshouldbe“forgotten”oncethetaskissenttothe
background.FLAG_ACTIVITY_CLEAR_TOP
launchanactivityIfthereisalreadyaninstanceofthecalledactivitytypepresent
inthestack,thenthisinstanceisbroughttotheforegroundinsteadof
creatinganewinstance.Also,allactivitiesinthestackthatreside
ontopofthatinstanceareclearedfromthestack.Forexample,
assumingthatthecurrentactivitystackisABCDE
,launchingan
activityoftypeC
willclearactivitiesD
andE
fromthetaskandresultinthestackABC
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
Normally,whenlaunchinganactivityinanewtask
,the
targetactivityisshowninthelistofrecentlylaunchedactivities
(accessiblevialongpressofthehome
button).Forexample,
thisisthecasewhenlaunchingthebrowserfromyouractivitytorender
awebpage.Usingthisflag,wecansuppressthatbehavior,effectively
excludingthetargetactivityfromthelistofrecentlylaunched
activities.FLAG_ACTIVITY_FORWARD_RESULT
Bydefault,inorderforanactivityB
tobeableto
propagatearesultbacktothecallingactivityA
,AhastousethemethodstartActivityForResult(Intent)
insteadof
methodstartActivity(Intent)
tostartB
.WhenB
definesitsresultviasetResult(intresultCode)
andfinishes,
thecallbackmethodonActivityResult()
iscalledonA
wheretheresultcanberetrieved.
forwardingwithFlagFORWARD_RESULTSupposenowthatB
callsanotheractivityC
,which
definestheresult,andwewanttoforwardthatresultbacktoA
.
InordertoavoidhavingtopassresultsmanuallyfromB
toA
,
Androidprovidesthisflag.Inourexample,thismeansthatB
callsC
,specifying
theforwardflagandusingstartActivity(Intent)
.Cmaythendefinearesult,whichisforwardedbacktoAautomaticallyonceC
andB
arefinished.Thecallback
methodonActivityResult()
iscalledonA
butnot
calledontheintermediateactivityB
asB
only
forwardstheresultinsteadofexplicitlyhandlingit.NotethattheflagmayonlybeusedinconjunctionwithstartActivity(Intent)
,
notwithstartActivityForResult(Intent)
,becauseanactivity
usingthelattermethodmarkstheendofaforwardingchainandshould
handletheresultinitscallbackmethod.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
Thisflagissetbythesystemasanindicationthatanactivityhas
beenlaunchedfromthelistofrecentlylaunchedactivities.FLAG_ACTIVITY_MULTIPLE_TASK
ThisflaghasnoeffectunlessusedinconjunctionwithFLAG_ACTIVITY_NEW_TASK
.
Ifusedtogether,anewtaskisalwayscreatedandanewinstanceof
thecalledactivitytypebecomesthefirst(andatthattime,theonly)
elementofthattask.
FLAG_ACTIVITY_NEW_TASK
Ifthisflagisusedonitsown(withoutFLAG_ACTIVITY_MULTIPLE_TASK
),
anewtaskisonlycreatedifthereisnotalreadyataskpresentthat
thetargetactivityhasanaffinity
for(taskaffinitiesare
examinedmorecloselyinthenextblogpost).Ifsuchataskalready
exists,theactivityisputintothattaskinsteadofcreatinganew
one.Asallactivitiesspecifiedwithinthesameapplicationhaveadefault
affinitytoremaininthesametask(thiscanbecustomized),starting
anactivitydefinedinthesameapplicationasthecallingactivity
usingthisflagwillnotcreateanewtask,unlessFLAG_ACTIVITY_MULTIPLE_TASK
isspecifiedaswell.FLAG_ACTIVITY_NO_ANIMATION
IntroducedwithAndroid2.0,thisflagdisablestheusualanimation
accompaniedbyanactivitytransition.Forexample,thiscanbeusedto
callanactivitythatitselflaunchesanotheractivitywithoutfurther
userinteraction,resultinginonlyonetransitionanimationtobeshown
insteadoftwo.FLAG_ACTIVITY_NO_HISTORY
Thisflagimpliesthatthecalledactivityisnotkeptinthetask’s
stack.Whennavigatingaway,theusercannotreturntoit.Forexample,
thisisusefultolaunchactivitiesthatperformanimmediatedispatch
toanotheractivity.Thisactivityisconsequentlyskippediftheuser
pressestheback
buttonasitisnotkeptinthestack.FLAG_ACTIVITY_NO_USER_ACTION
Thisflagmaybeusedasanindicationthattheactivitytransition
isnotanactiondirectlyperformedbytheuserbutratheranautomatic
one.Forexample,thisistrueforthecall-inactivitythatis
automaticallylaunchedwhenthedevicereceivesaphonecall.
Technically,itmeansthattheinvocationofcallbackmethodonUserLeaveHint()
onthecalleractivityissuppressed.FLAG_ACTIVITY_REORDER_TO_FRONT
activitywithFlagREORDER_TO_FRONTIfthereisalreadyaninstanceofthecalledactivitytypepresent
inthetaskstack,thatinstanceisbroughttotheforegroundwhilethe
restofthestackiskeptintact.Thiseffectivelyreordersthestack.
Forexample,assumingthatthecurrentactivitystackisABCDEF
,
launchinganactivityoftypeC
usingthisflagwillresultin
thenewstackABDEFC
.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
Thisflaghasnoeffectunlesstheintentcreatesanewtaskor
bringsanexistingtasktotheforeground.Inthatcase,thetaskis
reset,meaningthattaskaffinitiesareapplied(resultinginactivities
beingmovedfromortothistask)andthat,giventhatFLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
issetaswell,thetaskisclearedaccordingthatflag’s
specification.FLAG_ACTIVITY_SINGLE_TOP
Ifaninstanceofthetargetactivityisalreadyatthetopofthe
stack,nonewinstanceiscreated.
Conclusion
TheakquinetMobileandModularSolutionsprovidesanAndroidapplicationtohelpyouunderstandtheeffectsoftheintentflags.It
letsyoustartexemplaryactivitiesusingarbitraryintentflagsand
inspecttheeffectsontheresultingtaskstack.
.
Thesourcecodeisalsoavailableon
.Alldescribedbehaviornotonlydependsonintentflagsspecified,
butalsoonattributesdefinedonthecalledactivitytype(inAndroidManifest.xml
),
includingtaskaffinitiesandlaunchmodes.Whileintentflagsare
specifiedbythecaller,launchmodesandaffinitiesarepropertiesof
thecallee.Thosewillbediscussedinthenext
post
ofthisseries.
相关文章推荐
- Android活动和任务(Activities and Tasks)
- [译]Android应用程序基础 >> 任务栈和亲属关系(Activities and Tasks)
- Android应用程序基础 >> 任务栈和亲属关系(Activities and Tasks)
- Android 开发文档 程序基础——Activities and Tasks
- Activities and Tasks
- Android任务和返回栈(Tasks and Back Stack)
- Android Notes 05 - Tasks and Back Stack
- Android Api Component---翻译任务和回退栈(Tasks and Back Stack)
- Android Dev Guide---Tasks and Back Stack(上)
- Android Task Killers: How do killing background tasks and services actually help?
- 7 great Android apps for notes and tasks
- (四)Activities and Tasks
- Android API Guides---Tasks and Back Stack
- 第三章:Creating Applications and activities-(七)介绍Android应用的class
- 第三章:Creating Applications and activities-(八)深入了解Android的Activities及本章总结
- Android 阅读Tasks and Back Stack文章后的重点摘抄
- Android Dev Guide---Tasks and Back Stack(下)
- AndroidAnnotations——BackgroundTasksAndActivityBinding后台任务和activity绑定
- 【Android】任务和返回栈(tasks and back stack)
- Develop系列-API Guides-应用组件-Activities-Tasks and Back Stack