BroadcastReceiver 使用goAsync 执行异步操作
2015-02-11 11:08
316 查看
BroadcastReceiver 生命周期
一个BroadcastReceiver 对象只有在被调用onReceive(Context, Intent)的才有效的,当从该函数返回后,该对象就无效的了,结束生命周期。
因此从这个特征可以看出,在所调用的onReceive(Context, Intent)函数里,不能有过于耗时的操作,不能使用线程来执行。对于耗时的操作,请start service来完成。因为当得到其他异步操作所返回的结果时,BroadcastReceiver 可能已经无效了。如果确实需要做的话,可以用goAsync方法,然后在新开一个线程去执行。
goAsync 官方文档:
This can be called by an application in {@link #onReceive} to allow
it to keep the broadcast active after returning from that function.
This does <em>not</em> change the expectation of being relatively
responsive to the broadcast (finishing it within 10s), but does allow
the implementation to move work related to it over to another thread
to avoid glitching the main UI thread due to disk IO.
代码示例:
public void onReceive(final Context context, final Intent intent) { final PendingResult result = goAsync(); wl.acquire(); AsyncHandler.post(new Runnable() { @Override public void run() { handleIntent(context, intent);//耗时操作 result.finish(); } }); }
public final class AsyncHandler { private static final HandlerThread sHandlerThread = new HandlerThread("AsyncHandler"); private static final Handler sHandler; static { sHandlerThread.start(); sHandler = new Handler(sHandlerThread.getLooper()); } public static void post(Runnable r) { sHandler.post(r); } private AsyncHandler() {} }
相关文章推荐
- BroadcastReceiver 使用goAsync 执行异步操作
- 使用Spring @Async异步执行方法的笔记
- 【Android 开发教程】使用IntentService执行异步操作
- 使用async 和 defer 属性异步加载执行JavaScript
- C# 线程知识--使用Task执行异步操作
- 使用async属性异步加载执行JavaScript
- C# 线程知识--使用ThreadPool执行异步操作
- C# 线程知识--使用Task执行异步操作
- spring使用Async实现异步或者延迟的操作
- "现在已经正在使用此 SocketAsyncEventArgs 实例进行异步套接字操作"的处理
- C# 线程知识--使用Task执行异步操作
- C# 线程知识--使用Task执行异步操作(转)
- HTML5特性:使用async属性异步加载执行JavaScript
- Android中使用Handler和异步任务(AsyncTack)来为UI线程执行费时操作
- 使用Spring @Async异步执行方法的笔记
- C# 使用APM执行受I/O限制的异步操作(转)
- CLR_via_C#.3rd 翻译[25.7 使用专用线程执行异步的计算限制操作]
- 多任务异步执行dispatch_group_async的使用
- nodejs中使用async来对异步操作进行同步,避免多个异步同时启动引发连接错误
- 使用Spring @Async异步执行方法的笔记