BroadcastReceiver 10秒 ANR

在 Android中,程序的响应(Responsive)被活动管理器(Activity Manager)和窗口管理器(Window Manager)这两个系统服务所监视,当BroadcastReceiver在10秒内没有执行完毕,Android会认为该程序无响应,所以在 BroadcastReceiver里不能做一些比较耗时的操作,否则会弹出ANR(Application No Response)的对话框。如果需要完成一项比较耗时的工作,应该通过发送Intent给Service,由Service来完成,而不是使用子线程的方法来解决,因为BroadcastReceiver的生命周期很短(在onReceive()执行后BroadcastReceiver的实例就会被销毁),子线程可能还没有结束BroadcastReceiver就先结束了。如果BroadcastReceiver结束了,它的宿主进程还在运行,那么 子线程还会继续执行。但宿主进程此时很容易在系统需要内在时被优先杀死。因为它属于空进程(没有任何活动组件的进程)。

每次广播消息到来时,都会创建BroadcastReceiver实例来执行onReceive()方法。


广播接收者(BroadcastReceiver)用于接收广播Intent,广播Intent的发送是通过调用 Context.sendBroadcast()、Context.sendOrdeedBroadcast()、 context.sendStickyBroadcast()来实现的,通常一个广播Intent可以被订阅了此Intent的多个广播接收者所接收,这 个特性跟JMS中的Topic消息接收者类似,要实现一个广播接收者方法如下:

onReceive的生命周期为10秒,所以里面的操作不能超过10秒

 

This method is called when the BroadcastReceiver is receiving an Intent broadcast. During this time you can use the other methods on BroadcastReceiver to view/modify the current result values. This method is always called within the main thread of its process, unless you explicitly asked for it to be scheduled on a different thread using registerReceiver(BroadcastReceiver, IntentFilter, String, android.os.Handler). When it runs on the main thread you should never perform long-running operations in it (there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed). You cannot launch a popup dialog in your implementation of onReceive().

 

你可能感兴趣的:(thread,android,manager,service,application,methods)