[Andriod官方训练教程]管理Activity的生命活动之开始一个Activity
2013-02-01 20:13
585 查看
原文地址:https://developer.android.com/training/basics/activity-lifecycle/starting.html
--------------------------------------------------------------------------------------------------------------------
Unlikeotherprogrammingparadigmsinwhichappsarelaunchedwitha
specificcallbackmethodsthatcorrespondtospecificstagesofitslifecycle.Thereisasequenceofcallbackmethodsthatstartupanactivityandasequenceofcallbackmethodsthatteardownanactivity.
和其他以main()启动的编程范例不同,Android系统在一个Activity实例中初始化代码,它调用了一系列对应于生命周期中特定阶段的特定回调函数。一个activity由一个回调函数序列开始,并且以一系列回调函数结束。
Thislessonprovidesanoverviewofthemostimportantlifecyclemethodsandshowsyouhowtohandlethefirstlifecyclecallbackthatcreatesanewinstanceofyouractivity.
本课提供了一个有关最重要的生命周期函数的概览,向你展示怎样控制第一个生命周期回调函数(它用于创建你的activity的一个新的实例)。
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
itquicklycalls
其他的状态(Created和Started)是瞬时的,系统通过调用下一个生命周期回调函数,从它们快速地转移到另一个状态。也就是说,系统调用
That'sitforthebasicactivitylifecycle.Nowyou'llstartlearningaboutsomeofthespecificlifecyclebehaviors.
inyourappthatyou'vedeclaredtobethe"launcher"(or"main")activity.Thisistheactivitythatservesasthemainentrypointtoyourapp'suserinterface.
当从Home屏幕用户选择你的app图标时,系统将为你的app中声明为"launcher"(或者"main")activity的Activity调用
方法。这个activity承担了你的app的用户界面的主程序入口。
YoucandefinewhichactivitytouseasthemainactivityintheAndroidmanifestfile,
你可以定义哪个activity为mainactivity在Android的清单文件中,
Themainactivityforyourappmustbedeclaredinthemanifestwithan
category.Forexample:
这个mainactivity一定在清单中以一个MAINaction和
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
inthemanifestwiththisfilter.
注意:当你使用AndroidSDK工具创建一个Android项目时,默认的项目文件包含一个Activity类,并在清单使用这个filter被声明。
Ifeitherthe
categoryarenotdeclaredforoneofyouractivities,thenyourappiconwillnotappearintheHomescreen'slistofapps.
如果
都没有在你的activities中被声明,那么你的app图标将不会出现在Home屏幕的app列表中。
action,thesystemcreateseverynewinstanceof
method.
大多数apps包含了一些不同的activities来允许用户进行不同的行为。对于任何的一个activity,系统通过调用onCreate()方法创建每一个Activity
的实例。
Youmustimplementthe
oftheactivity.Forexample,yourimplementationof
variables.
你必须实现onCreate()方法,来执行基本的应用程序启动逻辑(只在activity的整个生命活动中发生一次)。例如,你的onCreate()
的实现应该定义了用户界面并且可能实例化一下类的变量。
Forexample,thefollowingexampleofthe
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
5)andhigheronly.Olderversionswillencounteraruntimeexception.
Oncethe
and
userwhen
followsandtheactivityremainsintheResumedstateuntilsomethingoccurstochangethat,suchaswhenaphonecallisreceived,theusernavigatestoanotheractivity,orthedevicescreenturnsoff.
一旦onCreate()完成执行,系统紧接着调用
Intheotherlessonsthatfollow,you'llseehowtheotherstartupmethods,[code]
onStart()and
lifecyclewhenusedtoresumetheactivityfromthePausedorStoppedstates.
在接下来的其他课程中,你将会看到其他的回调函数怎样开始方法,当需要从Paused或者Stopped状态重新开始时,onStart()和
Note:The
inthelatterlessonabout
RecreatinganActivity.
注意:onCreate()方法包含了一个叫做savedInstanceState的参数,这个我们将在接下来的关于Recreating
anActivity的课程中讨论
Figure2.Anotherillustrationoftheactivitylifecyclestructurewithanemphasisonthethreemaincallbacksthatthesystemcallsinsequencewhencreatinganewinstanceoftheactivity:
and
toadifferentactivity.
图2.另一个活动生命周期结构的说明,并强调了在创建一个新的活动实例时,系统按照顺序调用的三个主要的回调函数:onCreate(),
和
Thesystemcallsthismethodonyouractivityasthefinalsignalthatyouractivityinstanceisbeingcompletelyremovedfromthesystemmemory.
activity的第一个生命周期回调函数是onCreate(),而它的最后一个回调函数是
Mostappsdon'tneedtoimplementthismethodbecauselocalclassreferencesaredestroyedwiththeactivityandyouractivityshouldperformmostcleanupduring
and
orotherlong-runningresourcesthatcouldpotentiallyleakmemoryifnotproperlyclosed,youshouldkillthemduring
大多数apps不需要实现这个方法,因为随着你的activity,局部的类引用类型将随之销毁,并且你的activity在
@Override
publicvoidonDestroy(){
super.onDestroy();//Alwayscallthesuperclass
//StopmethodtracingthattheactivitystartedduringonCreate()停止方法追踪(该活动在onCreate()中开始)
android.os.Debug.stopMethodTracing();
}
Note:Thesystemcalls
and
fromwithinthe
youmightcall
todestroytheactivity.Inthiscase,thesystemimmediatelycalls
注意:除了一种情况外,系统在所有情况下,都是在已经调用了onPause()和
--------------------------------------------------------------------------------------------------------------------
Unlikeotherprogrammingparadigmsinwhichappsarelaunchedwitha
main()method,theAndroidsysteminitiatescodeinan
instancebyinvokingActivity
specificcallbackmethodsthatcorrespondtospecificstagesofitslifecycle.Thereisasequenceofcallbackmethodsthatstartupanactivityandasequenceofcallbackmethodsthatteardownanactivity.
和其他以main()启动的编程范例不同,Android系统在一个
Thislessonprovidesanoverviewofthemostimportantlifecyclemethodsandshowsyouhowtohandlethefirstlifecyclecallbackthatcreatesanewinstanceofyouractivity.
本课提供了一个有关最重要的生命周期函数的概览,向你展示怎样控制第一个生命周期回调函数(它用于创建你的activity的一个新的实例)。
UnderstandtheLifecycleCallbacks—理解生命周期回调函数
Duringthelifeofanactivity,thesystemcallsacoresetoflifecyclemethodsinasequencesimilartoasteppyramid.Thatis,eachstageoftheactivitylifecycleisaseparatesteponthepyramid.Asthesystemcreatesanewactivityinstance,eachcallbackmethodmovestheactivitystateonesteptowardthetop.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
,whichisquicklyfollowedbyonStart()
.onResume()
其他的状态(Created和Started)是瞬时的,系统通过调用下一个生命周期回调函数,从它们快速地转移到另一个状态。也就是说,系统调用
onCreate()后,它立刻调用 onStart(),然后再迅速调用 onResume()。
That'sitforthebasicactivitylifecycle.Nowyou'llstartlearningaboutsomeofthespecificlifecyclebehaviors.
SpecifyYourApp'sLauncherActivity——定义你自己的App的启动活动
WhentheuserselectsyourappiconfromtheHomescreen,thesystemcallsthemethodfortheonCreate()
Activity
inyourappthatyou'vedeclaredtobethe"launcher"(or"main")activity.Thisistheactivitythatservesasthemainentrypointtoyourapp'suserinterface.
当从Home屏幕用户选择你的app图标时,系统将为你的app中声明为"launcher"(或者"main")activity的
onCreate()
方法。这个activity承担了你的app的用户界面的主程序入口。
YoucandefinewhichactivitytouseasthemainactivityintheAndroidmanifestfile,
AndroidManifest.xml,whichisattherootofyourprojectdirectory.
你可以定义哪个activity为mainactivity在Android的清单文件中,
AndroidManifest.xml,这是你项目目录的根。
Themainactivityforyourappmustbedeclaredinthemanifestwithan
<intent-filter>thatincludesthe
actionandMAIN
LAUNCHER
category.Forexample:
这个mainactivity一定在清单中以一个
<intent-filter>声明,包含了
LAUNCHER
category。例如:
Note:WhenyoucreateanewAndroidprojectwiththeAndroidSDKtools,thedefaultprojectfilesincludean
classthat'sdeclaredActivity
inthemanifestwiththisfilter.
注意:当你使用AndroidSDK工具创建一个Android项目时,默认的项目文件包含一个
Ifeitherthe
actionorMAIN
LAUNCHER
categoryarenotdeclaredforoneofyouractivities,thenyourappiconwillnotappearintheHomescreen'slistofapps.
如果
action和MAIN
categoryLAUNCHER
都没有在你的activities中被声明,那么你的app图标将不会出现在Home屏幕的app列表中。
CreateaNewInstance——创建一个新的实例
Mostappsincludeseveraldifferentactivitiesthatallowtheusertoperformdifferentactions.Whetheranactivityisthemainactivitythat'screatedwhentheuserclicksyourappiconoradifferentactivitythatyourappstartsinresponsetoauseraction,thesystemcreateseverynewinstanceof
bycallingitsActivity
onCreate()
method.
大多数apps包含了一些不同的activities来允许用户进行不同的行为。对于任何的一个activity,系统通过调用
的实例。
Youmustimplementthe
methodtoperformbasicapplicationstartuplogicthatshouldhappenonlyoncefortheentirelifeonCreate()
oftheactivity.Forexample,yourimplementationof
shoulddefinetheuserinterfaceandpossiblyinstantiatesomeclass-scopeonCreate()
variables.
你必须实现
的实现应该定义了用户界面并且可能实例化一下类的变量。
Forexample,thefollowingexampleofthe
methodshowssomecodethatperformssomefundamentalsetupfortheactivity,suchonCreate()
asdeclaringtheuserinterface(definedinanXMLlayoutfile),definingmembervariables,andconfiguringsomeoftheUI.
例如,下面的
Caution:Usingthe
topreventoldersystem'sfromexecutingnewAPIsworksinthiswayonAndroid2.0(APIlevelSDK_INT
5)andhigheronly.Olderversionswillencounteraruntimeexception.
Oncethe
finishesexecution,thesystemcallstheonCreate()
onStart()
and
methodsinquicksuccession.YouractivityneverresidesintheCreatedorStartedstates.Technically,theactivitybecomesvisibletotheonResume()
userwhen
iscalled,butonStart()
quicklyonResume()
followsandtheactivityremainsintheResumedstateuntilsomethingoccurstochangethat,suchaswhenaphonecallisreceived,theusernavigatestoanotheractivity,orthedevicescreenturnsoff.
一旦
onStart()
和onResume()方法。你的activity不会停留在Created或者Started状态。技术上,活动在 onStart()调用后才变得对用户可见,但是 onResume()紧紧相随然后activity停留在Resumed状态直到某些事件发生来改变它,例如当接到一个电话,用户导航到另一个activity,或者设备屏幕关闭了。
Intheotherlessonsthatfollow,you'llseehowtheotherstartupmethods,[code]
,areusefulduringyouractivity'sonResume()
lifecyclewhenusedtoresumetheactivityfromthePausedorStoppedstates.
在接下来的其他课程中,你将会看到其他的回调函数怎样开始方法,当需要从Paused或者Stopped状态重新开始时,
onResume()在你的activity的生命周期中会很有用。
Note:The
methodincludesaparametercalledonCreate()
savedInstanceStatethat'sdiscussed
inthelatterlessonabout
RecreatinganActivity.
注意:
anActivity的课程中讨论
Figure2.Anotherillustrationoftheactivitylifecyclestructurewithanemphasisonthethreemaincallbacksthatthesystemcallsinsequencewhencreatinganewinstanceoftheactivity:
,onCreate()
,onStart()
and
.Oncethissequenceofcallbackscomplete,theactivityreachestheResumedstatewhereuserscaninteractwiththeactivityuntiltheyswitchonResume()
toadifferentactivity.
图2.另一个活动生命周期结构的说明,并强调了在创建一个新的活动实例时,系统按照顺序调用的三个主要的回调函数:
,onStart()
和
onResume()。一旦这个回调函数序列完成,activity便到达了Resumed状态,并且用户可以和其进行交互直到他们切换到另一个activity。
DestroytheActivity——销毁活动
Whiletheactivity'sfirstlifecyclecallbackis,itsverylastcallbackisonCreate()
.onDestroy()
Thesystemcallsthismethodonyouractivityasthefinalsignalthatyouractivityinstanceisbeingcompletelyremovedfromthesystemmemory.
activity的第一个生命周期回调函数是
onDestroy()。系统调用该方法作为一个最终信号,你的activity实例将要被完全从系统内存中清除。
Mostappsdon'tneedtoimplementthismethodbecauselocalclassreferencesaredestroyedwiththeactivityandyouractivityshouldperformmostcleanupduring
onPause()
and
.However,ifyouractivityincludesbackgroundthreadsthatyoucreatedduringonStop()
onCreate()
orotherlong-runningresourcesthatcouldpotentiallyleakmemoryifnotproperlyclosed,youshouldkillthemduring
.onDestroy()
大多数apps不需要实现这个方法,因为随着你的activity,局部的类引用类型将随之销毁,并且你的activity在
andonPause()
onStop()期间完成了大部分清理工作。但是,如果你的activity包含了后台线程(在 onCreate()中创建)或者其他长期执行的资源,如果没有合适地关闭就有可能造成内存泄露,你应该在 onDestroy()中结束它们。
publicvoidonDestroy(){
super.onDestroy();//Alwayscallthesuperclass
//StopmethodtracingthattheactivitystartedduringonCreate()停止方法追踪(该活动在onCreate()中开始)
android.os.Debug.stopMethodTracing();
}
Note:Thesystemcalls
afterithasalreadycalledonDestroy()
onPause()
and
inallsituationsexceptone:whenyoucallonStop()
finish()
fromwithinthe
method.Insomecases,suchaswhenyouractivityoperatesasatemporarydecisionmakertolaunchanotheractivity,onCreate()
youmightcall
fromwithinfinish()
onCreate()
todestroytheactivity.Inthiscase,thesystemimmediatelycalls
withoutcallinganyoftheotherlifecyclemethods.onDestroy()
注意:除了一种情况外,系统在所有情况下,都是在已经调用了
后再调用onStop()
onDestroy()。这种情况是:当你在 onCreate()中调用 finish()方法。在一些情况下,例如当你的activity运行为一个暂时的决策人来启动另一个activity,你可能在 onCreate()中调用 finish()来销毁该activity。在这种情况下,系统立刻调用 onDestroy(),不再调用其他任何生命周期函数。
相关文章推荐
- [Andriod官方训练教程]管理Activity的生命活动之开始一个Activity
- [Andriod官方训练教程]管理Activity的生命活动之停止和重启一个Activity
- [Andriod官方训练教程]管理Activity的生命活动之重新创建一个Activity
- [Andriod官方训练教程]管理Activity的生命活动之重新创建一个Activity
- [Andriod官方训练教程]管理Activity的生命活动之停止和重启一个Activity
- [Andriod官方训练教程]管理Activity的生命活动之停止和重启一个Activity
- [Andriod官方训练教程]管理Activity的生命活动之暂停和恢复一个Activity
- [Andriod官方训练教程]管理Activity的生命活动之暂停和恢复一个Activity
- [Andriod官方训练教程]创建你的第一个App之开始另一个Activity
- [Andriod官方训练教程]创建你的第一个App之开始另一个Activity
- [Andriod官方训练教程]使用Fragment创建一个动态的UI之与其他Fragments进行交互
- [Andriod官方训练教程]创建你的第一个App之创建一个Android项目
- [Andriod官方训练教程]使用Fragment创建一个动态的UI之与其他Fragments进行交互
- [Andriod官方训练教程]使用Fragment创建一个动态的UI之使用Support Library
- [Andriod官方训练教程]创建你的第一个App之创建一个简单的用户界面
- [Andriod官方训练教程]使用Fragment创建一个动态的UI之使用Support Library
- [Andriod官方训练教程]创建你的第一个App之创建一个简单的用户界面
- 二 管理生命活动周期 开始Activity
- [Andriod官方训练教程]使用Fragment创建一个动态的UI之与其他Fragments进行交互
- [Andriod官方训练教程]使用Fragment创建一个动态的UI之创建一个Fragment