Broadcastreceiverlifecycle---广播接收组件生命周期

Abroadcastreceiverhassinglecallbackmethod:--翻译:广播接收组件只有唯一一个回调方法:

void onReceive(Context curContext, Intent broadcastMsg)

Whenabroadcastmessagearrivesforthereceiver,AndroidcallsitsonReceive()广播接收组件methodandpassesittheIntentobjectcontainingthemessage.Thebroadcastreceiverisconsideredtobeactiveonlywhileitisexecutingthismethod.WhenonReceive()returns,itisinactive.

当消息接受者接到广播消息,Android将立刻调用广播接收组件实例的onReceive()方法,同时,消息封装在intent对象中以参数的方式传入该方法,该方法执行过程中,该广播接收组件实例的状态是活动状态。广播接收组件实例的onReceive()一旦执行完毕,广播接收组件实例的状态变为非活动状态。

Aprocesswithanactivebroadcastreceiverisprotectedfrombeingkilled.Butaprocesswithonlyinactivecomponentscanbekilledbythesystematanytime,whenthememoryitconsumesisneededbyotherprocesses.

翻译:活动状态的广播接收组件实例所属的进程是受系统保护的,不会被系统关闭的。但是对于非活动状态的广播接收组件实例所属的进程而言,一旦出现系统资源缺乏,为了腾出必要内存空间,系统随时可以杀死该进程。

Thispresentsaproblemwhentheresponsetoabroadcastmessageistimeconsumingand,therefore,somethingthatshouldbedoneinaseparatethread,awayfromthemainthreadwhereothercomponentsoftheuserinterfacerun.IfonReceive()spawnsthethreadandthenreturns,theentireprocess,includingthenewthread,isjudgedtobeinactive(unlessotherapplicationcomponentsareactiveintheprocess),puttingitinjeopardyofbeingkilled.ThesolutiontothisproblemisforonReceive()tostartaserviceandlettheservicedothejob,sothesystemknowsthatthereisstillactiveworkbeingdoneintheprocess.

翻译:需要注意的是,如果说对广播消息的响应是耗时操作的话(onReceive()方法中的代码),就需要考虑脱离主线程、以独立线程方式执行对消息的响应处理,这样可以避免阻塞现象的发生(寄宿在主线程之上的其他组件实例与用户交互过程被阻塞)。如果在onReceive()方法中在当前进程中创建一个独立的线程,该方法执行完毕后,当前进程可能被系统就认定为惰性进程(如果此时进程中的其他组件实例都处于惰性状态),当前进程是随时可能被系统关闭的。对这个问题的解决方式是:在onReceive()方法中以服务的方式来处理对消息的响应,这样可以使得系统认为当前进程依然是活动状态,避免被系统杀死。

Thenextsectionhasmoreonthevulnerabilityofprocessestobeingkilled.