zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

android生命周期深入分析(二)

Android 深入分析 生命周期
2023-06-13 09:14:42 时间

在Android中,多数情况下每个程序都是在各自独立的Linux进程中运行的。当一个程序或其某些部分被请求时,它的进程就“出生”了;当这个程序没有必要再运行下去且系统需要回收这个进程的内存用于其他程序时,这个进程就“死亡”了。可以看出,Android程序的生命周期是由系统控制而非程序自身直接控制。这和我们编写桌面应用程序时的思维有一些不同,一个桌面应用程序的进程也是在其他进程或用户请求时被创建,但是往往是在程序自身收到关闭请求后执行一个特定的动作(比如从main函数中return)而导致进程结束的。要想做好某种类型的程序或者某种平台下的程序的开发,最关键的就是要弄清楚这种类型的程序或整个平台下的程序的一般工作模式并熟记在心。在Android中,程序的生命周期控制就是属于这个范畴——我的个人理解:)

在Android系统中,当某个activity调用startActivity(myIntent)时,系统会在所有已经安装的程序中寻找其intentfilter和myIntent最匹配的一个activity,启动这个进程,并把这个intent通知给这个activity。这就是一个程序的“生”。比如我们在Homeapplication中选择“Webbrowser”,系统会根据这个intent找到并启动Webbrowser程序,显示Webbrowser的一个activity供我们浏览网页(这个启动过程有点类似我们在在个人电脑上双击桌面上的一个图标,启动某个应用程序)。在Android中,所有的应用程序“生来就是平等的”,所以不光Android的核心程序甚至第三方程序也可以发出一个intent来启动另外一个程序中的一个activity。Android的这种设计非常有利于“程序部件”的重用。

 一个Android程序的进程是何时被系统结束的呢?通俗地说,一个即将被系统关闭的程序是系统在内存不足(lowmemory)时,根据“重要性层次”选出来的“牺牲品”。一个进程的重要性是根据其中运行的部件和部件的状态决定的。各种进程按照重要性从高到低排列如下:
 1.前台进程。这样的进程拥有一个在屏幕上显示并和用户交互的activity或者它的一个IntentReciver正在运行。这样的程序重要性最高,只有在系统内存非常低,万不得已时才会被结束。
 2.可见进程。在屏幕上显示,但是不在前台的程序。比如一个前台进程以对话框的形式显示在该进程前面。这样的进程也很重要,它们只有在系统没有足够内存运行所有前台进程时,才会被结束。
 3.服务进程。这样的进程在后台持续运行,比如后台音乐播放、后台数据上传下载等。这样的进程对用户来说一般很有用,所以只有当系统没有足够内存来维持所有的前台和可见进程时,才会被结束。
 4.后台进程。这样的程序拥有一个用户不可见的activity。这样的程序在系统内存不足时,按照LRU的顺序被结束。
 5.空进程。这样的进程不包含任何活动的程序部件。系统可能随时关闭这类进程。
 

从某种意义上讲,垃圾收集机制把程序员从“内存管理噩梦”中解放出来,而Android的进程生命周期管理机制把用户从“任务管理噩梦”中解放出来。我见过一些NokiaS60用户和WindowsMobile用户要么因为长期不关闭多余的应用程序而导致系统变慢,要么因为不时查看应用程序列表而影响使用体验。Android使用Java作为应用程序API,并且结合其独特的生命周期管理机制同时为开发者和使用者提供最大程度的便利。

ActivitylifecycleActivity有三种基本状态
    Active:处于屏幕前景(当前task的栈顶Activity处于Active状态),同一时刻只能有一个Activity处于Active状态;Paused状态:处于背景画面画面状态,失去了焦点,但依然是活动状态;stopped:不可见,但依然保持所有的状态和内存信息。

可以调用finish()结束处理Paused或者stopped状态的Activity。

各种状态之间通过下列的函数调用转换

voidonCreate(BundlesavedInstanceState)
voidonStart()
voidonRestart()
voidonResume()
voidonPause()
voidonStop()
voidonDestroy()

Activity的生命周期可以分为三组:TheentirelifetimeofanactivityhappensbetweenthefirstcalltoonCreate()throughtoasinglefinalcalltoonDestroy().

ThevisiblelifetimeofanactivityhappensbetweenacalltoonStart()untilacorrespondingcalltoonStop().

TheforegroundlifetimeofanactivityhappensbetweenacalltoonResume()untilacorrespondingcalltoonPause().

 

保存Activity状态

Tocapturethatstatebeforetheactivityiskilled,youcanimplementanonSaveInstanceState()methodfortheactivity.Androidcallsthismethodbeforemakingtheactivityvulnerabletobeingdestroyed—thatis,beforeonPause()iscalled.ItpassesthemethodaBundleobjectwhereyoucanrecordthedynamicstateoftheactivityasname-valuepairs.Whentheactivityisagainstarted,theBundleispassedbothtoonCreate()andtoamethodthat"scalledafteronStart(),onRestoreInstanceState(),sothateitherorbothofthemcanrecreatethecapturedstate.

UnlikeonPause()andtheothermethodsdiscussedearlier,onSaveInstanceState()andonRestoreInstanceState()arenotlifecyclemethods.Theyarenotalwayscalled.BecauseonSaveInstanceState()isnotalwayscalled,youshoulduseitonlytorecordthetransientstateoftheactivity,nottostorepersistentdata.UseonPause()forthatpurposeinstead.启动另一个Activity的过程Thecurrentactivity"sonPause()methodiscalled.Next,thestartingactivity"sonCreate(),onStart(),andonResume()methodsarecalledinsequence.Then,ifthestartingactivityisnolongervisibleonscreen,itsonStop()methodiscalled.service生命周期

Aservicecanbeusedintwoways:Itcanbestartedandallowedtorununtilsomeonestopsitoritstopsitself.Inthismode,it"sstartedbycallingContext.startService()andstoppedbycallingContext.stopService().ItcanstopitselfbycallingService.stopSelf()orService.stopSelfResult().OnlyonestopService()callisneededtostoptheservice,nomatterhowmanytimesstartService()wascalled.

Itcanbeoperatedprogrammaticallyusinganinterfacethatitdefinesandexports.ClientsestablishaconnectiontotheServiceobjectandusethatconnectiontocallintotheservice.TheconnectionisestablishedbycallingContext.bindService(),andisclosedbycallingContext.unbindService().Multipleclientscanbindtothesameservice.Iftheservicehasnotalreadybeenlaunched,bindService()canoptionallylaunchit.

相关的方法:

voidonCreate()
voidonStart(Intentintent)
voidonDestroy()

TheonCreate()andonDestroy()methodsarecalledforallservices,whetherthey"restartedbyContext.startService()orContext.bindService().However,onStart()iscalledonlyforservicesstartedbystartService().

Ifaservicepermitsotherstobindtoit,thereareadditionalcallbackmethodsforittoimplement:

IBinderonBind(Intentintent)
booleanonUnbind(Intentintent)
voidonRebind(Intentintent)

 

Broadcastreceiverlifecycle

只有一个方法:voidonReceive(ContextcurContext,IntentbroadcastMsg)

Aprocesswithanactivebroadcastreceiverisprotectedfrombeingkilled.Butaprocesswithonlyinactivecomponentscanbekilledbythesystematanytime,whenthememoryitconsumesisneededbyotherprocesses.

Thispresentsaproblemwhentheresponsetoabroadcastmessageistimeconsumingand,therefore,somethingthatshouldbedoneinaseparatethread,awayfromthemainthreadwhereothercomponentsoftheuserinterfacerun.IfonReceive()spawnsthethreadandthenreturns,theentireprocess,includingthenewthread,isjudgedtobeinactive(unlessotherapplicationcomponentsareactiveintheprocess),puttingitinjeopardyofbeingkilled.ThesolutiontothisproblemisforonReceive()tostartaserviceandlettheservicedothejob,sothesystemknowsthatthereisstillactiveworkbeingdoneintheprocess.进程的生命周期

Android根据其重要性在内存不足的时候移去重要性最低的进程。重要性由高到低为:

    前台进程可见进程服务进程后台进程空进程

注意:Becauseaprocessrunningaserviceisrankedhigherthanonewithbackgroundactivities,anactivitythatinitiatesalong-runningoperationmightdowelltostartaserviceforthatoperation,ratherthansimplyspawnathread—particularlyiftheoperationwilllikelyoutlasttheactivity.比如播放MP3的时候就要启动一个service。