android生命周期深入分析(二)
在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。
各种状态之间通过下列的函数调用转换:Activity的生命周期可以分为三组:Theentirelifetimeofanactivityhappensbetweenthefirstcallto
voidonCreate(BundlesavedInstanceState)
voidonStart()
voidonRestart()
voidonResume()
voidonPause()
voidonStop()
voidonDestroy()
onCreate()
throughtoasinglefinalcalltoonDestroy()
.
Thevisiblelifetimeofanactivityhappensbetweenacallto
untilacorrespondingcalltoonStart()
.onStop()
Theforegroundlifetimeofanactivityhappensbetweenacallto
untilacorrespondingcalltoonResume()
.onPause()
保存Activity状态
Tocapturethatstatebeforetheactivityiskilled,youcanimplementan
methodfortheactivity.Androidcallsthismethodbeforemakingtheactivityvulnerabletobeingdestroyed—thatis,beforeonSaveInstanceState()
onPause()
iscalled.ItpassesthemethodaBundle
objectwhereyoucanrecordthedynamicstateoftheactivityasname-valuepairs.Whentheactivityisagainstarted,theBundleispassedbothtoonCreate()
andtoamethodthat"scalledafteronStart()
,
,sothateitherorbothofthemcanrecreatethecapturedstate.
onRestoreInstanceState()
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"sstartedbycalling
andstoppedbycallingContext.startService()
.ItcanstopitselfbycallingContext.stopService()
orService.stopSelf()
.OnlyoneService.stopSelfResult()
stopService()
callisneededtostoptheservice,nomatterhowmanytimesstartService()
wascalled.
Itcanbeoperatedprogrammaticallyusinganinterfacethatitdefinesandexports.ClientsestablishaconnectiontotheServiceobjectandusethatconnectiontocallintotheservice.Theconnectionisestablishedbycalling
,andisclosedbycallingContext.bindService()
.Multipleclientscanbindtothesameservice.Iftheservicehasnotalreadybeenlaunched,Context.unbindService()
bindService()
canoptionallylaunchit.
相关的方法:
voidonCreate()
voidonStart(Intentintent)
voidonDestroy()
TheonCreate()
andonDestroy()
methodsarecalledforallservices,whetherthey"restartedby
orContext.startService()
.However,Context.bindService()
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。
相关文章
- android 常用加密,分享一下Android各种类型的加密
- Android常用加密方式
- Android View 深度分析requestLayout、invalidate与postInvalidate「建议收藏」
- android deeplink流程,Android Deeplink探究[通俗易懂]
- delphixe5 android,Delphi XE5 Android手机端转换Ansi字符串
- mac 电脑android环境变量设置,mac上Android环境变量配置[通俗易懂]
- android declare-styleable 和style,Android 关于declare-styleable属性的写法….
- 【Android布局】在程序中设置android gravity 和 android layout Gravity属性
- Android preference_android studio preview
- Android触摸事件_android设置按钮点击事件
- android应用程序_chrome Android
- Android resource linking failed_android sdk location should not
- android跳转到相册需要权限,Android打开相册获取图片路径[通俗易懂]
- android线程间通信的几种方法_Android进程间和线程间通信方式
- Android 数据库加密 android-database-sqlcipher 开源版本编译过程
- 【Android 内存优化】Bitmap 硬盘缓存 ( Google 官方 Bitmap 示例 | DiskLruCache 开源库 | 代码示例 )
- 【Android FFMPEG 开发】Android 中执行 FFMPEG 指令 ( 集成 FFmpegAndroid 框架 )
- 【错误记录】Android Studio 编译报错 ( Could not find com.android.tools.build:gradle:4.2.1. )
- 【Android 插件化】现有的针对插件化恶意应用的解决方案 | 插件化应用开发推荐方案
- 【Android 逆向】substrate 框架 ( substrate 简介 | substrate 相关文档资料 )
- 【Android Gradle 插件】Module 目录下 build.gradle 配置文件 ( android 闭包块配置 | AppExtension 扩展类型参考文档 )
- 【Android Gradle 插件】自定义 Gradle 插件优化图片 ② ( 压缩 png、jpg 图片 | 使用 pngcrush 压缩工具压缩 png 图片 )
- 【Android Gradle 插件】自定义 Gradle 插件优化图片 ③ ( 识别 png 图片中的 alpha 通道信息 | png 图片的 IHDR 类型数据块 )
- 【错误记录】Android Studio 集成 ARoute 编译报错 ( 兼容 support 库和 androidx 库 | add ‘tools:replace=“android:appCo )
- Android RuntimePermissions运行时权限:批量权限申请详解手机开发
- android 之ndk开发详解手机开发
- 教你自己写Android第三方库详解手机开发
- Android中android:visibility的3中属性的剖析详解手机开发
- Android 在物联网方面能否像在移动终端一样成功?
- Connecting Android to Oracle: The Ultimate Guide for Seamless Integration.(android连接oracle)
- android生命周期深入分析(一)
- Android中的android:layout_weight使用详解
- android开发教程之handle实现多线程和异步处理
- Android中AutoCompleteTextView与MultiAutoCompleteTextView的用法
- Android实现下载文件功能的方法