您的位置:首页 > 其它

[Andriod官方训练教程]管理Activity的生命活动之开始一个Activity

2013-02-01 20:13 585 查看
原文地址:https://developer.android.com/training/basics/activity-lifecycle/starting.html

--------------------------------------------------------------------------------------------------------------------

Unlikeotherprogrammingparadigmsinwhichappsarelaunchedwitha
main()
method,theAndroidsysteminitiatescodeinan
Activity
instancebyinvoking
specificcallbackmethodsthatcorrespondtospecificstagesofitslifecycle.Thereisasequenceofcallbackmethodsthatstartupanactivityandasequenceofcallbackmethodsthatteardownanactivity.

和其他以main()启动的编程范例不同,Android系统在一个Activity实例中初始化代码,它调用了一系列对应于生命周期中特定阶段的特定回调函数。一个activity由一个回调函数序列开始,并且以一系列回调函数结束。

Thislessonprovidesanoverviewofthemostimportantlifecyclemethodsandshowsyouhowtohandlethefirstlifecyclecallbackthatcreatesanewinstanceofyouractivity.

本课提供了一个有关最重要的生命周期函数的概览,向你展示怎样控制第一个生命周期回调函数(它用于创建你的activity的一个新的实例)。

UnderstandtheLifecycleCallbacks—理解生命周期回调函数

Duringthelifeofanactivity,thesystemcallsacoresetoflifecyclemethodsinasequencesimilartoasteppyramid.Thatis,eachstageoftheactivitylifecycleisaseparatesteponthepyramid.Asthesystemcreatesanewactivityinstance,each
callbackmethodmovestheactivitystateonesteptowardthetop.Thetopofthepyramidisthepointatwhichtheactivityisrunningintheforegroundandtheusercaninteractwithit.

在一个activity的生命活动中,系统按照一定次序调用一系列核心的生命周期函数,这与一个梯形金字塔很相似。也就是说,activity生命活动中的每个阶段都是金字塔中的一个单独的步骤。当系统创建一个新的activity时,每个回调函数将朝着顶部,由一个活动状态转移到另一个活动状态。在金字塔的顶部,该activity在前台运行,用户可以和它进行交互。

Astheuserbeginstoleavetheactivity,thesystemcallsothermethodsthatmovetheactivitystatebackdownthepyramidinordertodismantletheactivity.Insomecases,theactivitywillmoveonlypartwaydownthepyramidandwait(suchaswhenthe
userswitchestoanotherapp),fromwhichpointtheactivitycanmovebacktothetop(iftheuserreturnstotheactivity)andresumewheretheuserleftoff.

当用户开始离开该activity时,系统调用另外一些方法,使得活动状态向金字塔下方转换以便拆除该activity。在一些情况下,该activity将仅仅部分向下移动然后等待(例如当用户切换到另一个app),在该点活activity可以返回金字塔顶部(如果用户返回该activity)并且从用户之前中断的地方重新开始。



Figure1.AsimplifiedillustrationoftheActivitylifecycle,expressedasasteppyramid.Thisshowshow,foreverycallbackusedtotaketheactivityasteptowardtheResumedstateatthetop,there'sacallbackmethod
thattakestheactivityastepdown.TheactivitycanalsoreturntotheresumedstatefromthePausedandStoppedstate.

图1.Activity生命周期的一个简要说明,以一个阶梯金字塔表示。这展示了,怎样利用回调函数使得一个activity向顶部的Resumed状态前进,并且怎样向下转换。该activity也可以从Paused和Stopped状态返回resumed状态。

Dependingonthecomplexityofyouractivity,youprobablydon'tneedtoimplementallthelifecyclemethods.However,it'simportantthatyouunderstandeachoneandimplementthosethatensureyourappbehavesthewayusersexpect.Implementingyouractivity
lifecyclemethodsproperlyensuresyourappbehaveswellinseveralways,includingthatit:

Doesnotcrashiftheuserreceivesaphonecallorswitchestoanotherappwhileusingyourapp.
Doesnotconsumevaluablesystemresourceswhentheuserisnotactivelyusingit.
Doesnotlosetheuser'sprogressiftheyleaveyourappandreturntoitatalatertime.
Doesnotcrashorlosetheuser'sprogresswhenthescreenrotatesbetweenlandscapeandportraitorientation.

取决于你的activity的复杂性,你可能不需要实现所有的回调函数。但是,理解每个函数是非常重要的,并且实现这些可以保证你的app按照用户期望的方式运行。实现你的activity生命周期函数可以合适地保证你的app在一些方面表现良好,包括:

在使用你的app时,如果用户接到一个电话或是切换到另一个app,它不会crash。
在用户没有活跃地使用它时,它不会消耗系统资源。
如果用户离开你的app并且之后返回它时,它不会丢失用户进程。
当屏幕旋转时,它不会crash或是丢失用户进程。

Asyou'lllearninthefollowinglessons,thereareseveralsituationsinwhichanactivitytransitionsbetweendifferentstatesthatareillustratedinfigure1.However,onlythreeofthesestatescanbestatic.Thatis,theactivitycanexistinoneof
onlythreestatesforanextendedperiodoftime:

ResumedInthisstate,theactivityisintheforegroundandtheusercaninteractwithit.(Alsosometimesreferredtoasthe"running"state.)PausedInthisstate,theactivityispartiallyobscuredbyanotheractivity—theotheractivitythat'sintheforegroundissemi-transparentordoesn'tcovertheentirescreen.Thepausedactivitydoesnotreceiveuserinputandcannotexecuteanycode.StoppedInthisstate,theactivityiscompletelyhiddenandnotvisibletotheuser;itisconsideredtobeinthebackground.Whilestopped,theactivityinstanceandallitsstateinformationsuchasmembervariablesisretained,butitcannotexecuteanycode.
(第一句不翻译了)但是,只有3个状态是静态的。也就是说,一个activity在持续期间只能停留在以下三种状态中一种:

Resumed重新开始在该状态下,activity是处于前台的,并且用户可以与它进行交互。(有时同样表示为"running"状态)Paused暂停在该状态下,activity部分的被另一个activity所掩盖——另一个在前台的activity是半透明的或者没有占据整个屏幕。暂停的activity不再接受用户输入并且不可以执行任何代码。Stopped停止在该状态下,activity被完全隐藏并且对于用户是不可见的;它被认为是处于后台。当停止时,该activity实例和它的所有状态信息,例如成员变量将被保留,但是它不可以执行任何代码。
Theotherstates(CreatedandStarted)aretransientandthesystemquicklymovesfromthemtothenextstatebycallingthenextlifecyclecallbackmethod.Thatis,afterthesystemcalls
onCreate()
,
itquicklycalls
onStart()
,whichisquicklyfollowedby
onResume()
.

其他的状态(Created和Started)是瞬时的,系统通过调用下一个生命周期回调函数,从它们快速地转移到另一个状态。也就是说,系统调用
onCreate()后,它立刻调用onStart(),然后再迅速调用onResume()。


That'sitforthebasicactivitylifecycle.Nowyou'llstartlearningaboutsomeofthespecificlifecyclebehaviors.

SpecifyYourApp'sLauncherActivity——定义你自己的App的启动活动

WhentheuserselectsyourappiconfromtheHomescreen,thesystemcallsthe
onCreate()
methodforthe
Activity

inyourappthatyou'vedeclaredtobethe"launcher"(or"main")activity.Thisistheactivitythatservesasthemainentrypointtoyourapp'suserinterface.

当从Home屏幕用户选择你的app图标时,系统将为你的app中声明为"launcher"(或者"main")activity的Activity调用
onCreate()

方法。这个activity承担了你的app的用户界面的主程序入口。

YoucandefinewhichactivitytouseasthemainactivityintheAndroidmanifestfile,
AndroidManifest.xml
,whichisattherootofyourprojectdirectory.

你可以定义哪个activity为mainactivity在Android的清单文件中,
AndroidManifest.xml
,这是你项目目录的根。

Themainactivityforyourappmustbedeclaredinthemanifestwithan
<intent-filter>
thatincludesthe
MAIN
actionand
LAUNCHER

category.Forexample:

这个mainactivity一定在清单中以一个
<intent-filter>
声明,包含了MAINaction和
LAUNCHER

category。例如:

<activityandroid:name=".MainActivity"android:label="@string/app_name"> <intent-filter> <actionandroid:name="android.intent.action.MAIN"/> <categoryandroid:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity>
Note:WhenyoucreateanewAndroidprojectwiththeAndroidSDKtools,thedefaultprojectfilesincludean
Activity
classthat'sdeclared
inthemanifestwiththisfilter.

注意:当你使用AndroidSDK工具创建一个Android项目时,默认的项目文件包含一个Activity类,并在清单使用这个filter被声明。

Ifeitherthe
MAIN
actionor
LAUNCHER

categoryarenotdeclaredforoneofyouractivities,thenyourappiconwillnotappearintheHomescreen'slistofapps.

如果
MAIN
action和
LAUNCHER
category
都没有在你的activities中被声明,那么你的app图标将不会出现在Home屏幕的app列表中。

CreateaNewInstance——创建一个新的实例

Mostappsincludeseveraldifferentactivitiesthatallowtheusertoperformdifferentactions.Whetheranactivityisthemainactivitythat'screatedwhentheuserclicksyourappiconoradifferentactivitythatyourappstartsinresponsetoauser
action,thesystemcreateseverynewinstanceof
Activity
bycallingits
onCreate()

method.

大多数apps包含了一些不同的activities来允许用户进行不同的行为。对于任何的一个activity,系统通过调用onCreate()方法创建每一个Activity
的实例。

Youmustimplementthe
onCreate()
methodtoperformbasicapplicationstartuplogicthatshouldhappenonlyoncefortheentirelife
oftheactivity.Forexample,yourimplementationof
onCreate()
shoulddefinetheuserinterfaceandpossiblyinstantiatesomeclass-scope
variables.

你必须实现onCreate()方法,来执行基本的应用程序启动逻辑(只在activity的整个生命活动中发生一次)。例如,你的onCreate()
的实现应该定义了用户界面并且可能实例化一下类的变量。

Forexample,thefollowingexampleofthe
onCreate()
methodshowssomecodethatperformssomefundamentalsetupfortheactivity,such
asdeclaringtheuserinterface(definedinanXMLlayoutfile),definingmembervariables,andconfiguringsomeoftheUI.

例如,下面的onCreate()方法的例子展示了一下代码,它执行了一些关于activity的基本设置,例如声明用户界面(在一个XML布局文件中定义),定义成员变量,并且配置了一些UI。

TextViewmTextView;//Membervariablefortextviewinthelayout布局中的一个文本编辑框的成员变量 @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); //SettheuserinterfacelayoutforthisActivity设置用户界面 //Thelayoutfileisdefinedintheprojectres/layout/main_activity.xmlfile布局文件定义在项目中的res/layout/main_activity.xml文件 setContentView(R.layout.main_activity); //InitializememberTextViewsowecanmanipulateitlater初始化成员TextView以便后面我们可以操纵它 mTextView=(TextView)findViewById(R.id.text_message); //Makesurewe'rerunningonHoneycomborhighertouseActionBarAPIs确保我们正运行在Honeycomb或是更高来使用ActionBarAPIs if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){ //Forthemainactivity,makesuretheappiconintheactionbar对于mainactivity,确保app图标在actionbar中 //doesnotbehaveasabutton不是表现为一个按键 ActionBaractionBar=getActionBar(); actionBar.setHomeButtonEnabled(false); } }

Caution:Usingthe
SDK_INT
topreventoldersystem'sfromexecutingnewAPIsworksinthiswayonAndroid2.0(APIlevel
5)andhigheronly.Olderversionswillencounteraruntimeexception.

Oncethe
onCreate()
finishesexecution,thesystemcallsthe
onStart()

and
onResume()
methodsinquicksuccession.YouractivityneverresidesintheCreatedorStartedstates.Technically,theactivitybecomesvisibletothe
userwhen
onStart()
iscalled,but
onResume()
quickly
followsandtheactivityremainsintheResumedstateuntilsomethingoccurstochangethat,suchaswhenaphonecallisreceived,theusernavigatestoanotheractivity,orthedevicescreenturnsoff.

一旦onCreate()完成执行,系统紧接着调用
onStart()
onResume()方法。你的activity不会停留在Created或者Started状态。技术上,活动在onStart()调用后才变得对用户可见,但是onResume()紧紧相随然后activity停留在Resumed状态直到某些事件发生来改变它,例如当接到一个电话,用户导航到另一个activity,或者设备屏幕关闭了。


Intheotherlessonsthatfollow,you'llseehowtheotherstartupmethods,[code]
onStart()and
onResume()
,areusefulduringyouractivity's
lifecyclewhenusedtoresumetheactivityfromthePausedorStoppedstates.

在接下来的其他课程中,你将会看到其他的回调函数怎样开始方法,当需要从Paused或者Stopped状态重新开始时,onStart()和
onResume()在你的activity的生命周期中会很有用。


Note:The
onCreate()
methodincludesaparametercalled
savedInstanceState
that'sdiscussed
inthelatterlessonabout
RecreatinganActivity.

注意:onCreate()方法包含了一个叫做savedInstanceState的参数,这个我们将在接下来的关于Recreating
anActivity的课程中讨论



Figure2.Anotherillustrationoftheactivitylifecyclestructurewithanemphasisonthethreemaincallbacksthatthesystemcallsinsequencewhencreatinganewinstanceoftheactivity:
onCreate()
,
onStart()
,
and
onResume()
.Oncethissequenceofcallbackscomplete,theactivityreachestheResumedstatewhereuserscaninteractwiththeactivityuntiltheyswitch
toadifferentactivity.

图2.另一个活动生命周期结构的说明,并强调了在创建一个新的活动实例时,系统按照顺序调用的三个主要的回调函数:onCreate(),
onStart()
,
onResume()。一旦这个回调函数序列完成,activity便到达了Resumed状态,并且用户可以和其进行交互直到他们切换到另一个activity。




DestroytheActivity——销毁活动

Whiletheactivity'sfirstlifecyclecallbackis
onCreate()
,itsverylastcallbackis
onDestroy()
.
Thesystemcallsthismethodonyouractivityasthefinalsignalthatyouractivityinstanceisbeingcompletelyremovedfromthesystemmemory.

activity的第一个生命周期回调函数是onCreate(),而它的最后一个回调函数是
onDestroy()。系统调用该方法作为一个最终信号,你的activity实例将要被完全从系统内存中清除。


Mostappsdon'tneedtoimplementthismethodbecauselocalclassreferencesaredestroyedwiththeactivityandyouractivityshouldperformmostcleanupduring
onPause()

and
onStop()
.However,ifyouractivityincludesbackgroundthreadsthatyoucreatedduring
onCreate()

orotherlong-runningresourcesthatcouldpotentiallyleakmemoryifnotproperlyclosed,youshouldkillthemduring
onDestroy()
.

大多数apps不需要实现这个方法,因为随着你的activity,局部的类引用类型将随之销毁,并且你的activity在
onPause()
and
onStop()期间完成了大部分清理工作。但是,如果你的activity包含了后台线程(在onCreate()中创建)或者其他长期执行的资源,如果没有合适地关闭就有可能造成内存泄露,你应该在onDestroy()中结束它们。




@Override
publicvoidonDestroy(){
super.onDestroy();//Alwayscallthesuperclass

//StopmethodtracingthattheactivitystartedduringonCreate()停止方法追踪(该活动在onCreate()中开始)
android.os.Debug.stopMethodTracing();
}
Note:Thesystemcalls
onDestroy()
afterithasalreadycalled
onPause()

and
onStop()
inallsituationsexceptone:whenyoucall
finish()

fromwithinthe
onCreate()
method.Insomecases,suchaswhenyouractivityoperatesasatemporarydecisionmakertolaunchanotheractivity,
youmightcall
finish()
fromwithin
onCreate()

todestroytheactivity.Inthiscase,thesystemimmediatelycalls
onDestroy()
withoutcallinganyoftheotherlifecyclemethods.

注意:除了一种情况外,系统在所有情况下,都是在已经调用了onPause()和
onStop()
后再调用
onDestroy()。这种情况是:当你在onCreate()中调用finish()方法。在一些情况下,例如当你的activity运行为一个暂时的决策人来启动另一个activity,你可能在onCreate()中调用finish()来销毁该activity。在这种情况下,系统立刻调用onDestroy(),不再调用其他任何生命周期函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐