您的位置:首页 > 移动开发 > Android开发

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
.

Intentsandactivitylaunching

Anintent
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:
Intentintent=

new

Intent(Intent.ACTION_VIEW,


Uri.parse(

"http://www.akquinet.com/
"

);
startActivity(intent);
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.

Customizingthelaunchofactivitiesviaintentflags

Thedescribedbehaviorcanbemodifiedbyspecifyingintentflags
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.

Conclusion

TheakquinetMobileandModularSolutionsprovidesanAndroid
applicationtohelpyouunderstandtheeffectsoftheintentflags.It
letsyoustartexemplaryactivitiesusingarbitraryintentflagsand
inspecttheeffectsontheresultingtaskstack.
IntentFlagsTool-MainscreenIntentFlagsTool-SelectingFlags
Youcandownloadthetoolhere
.
Thesourcecodeisalsoavailableongithub
.Alldescribedbehaviornotonlydependsonintentflagsspecified,
butalsoonattributesdefinedonthecalledactivitytype(inAndroidManifest.xml
),
includingtaskaffinitiesandlaunchmodes.Whileintentflagsare
specifiedbythecaller,launchmodesandaffinitiesarepropertiesof
thecallee.Thosewillbediscussedinthenext
post
ofthisseries.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: