BroadcastReceiver 使用goAsync 执行异步操作

from: http://blog.csdn.net/u012414584/article/details/43731799

BroadcastReceiver 生命周期 
一个BroadcastReceiver 对象只有在被调用onReceive(Context, Intent)的才有效的,当从该函数返回后,该对象就无效的了,结束生命周期。

一个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.

  代码示例:

[java]  view plain  copy
  1. public void onReceive(final Context context, final Intent intent) {  
  2.         final PendingResult result = goAsync();  
  3.         wl.acquire();  
  4.         AsyncHandler.post(new Runnable() {  
  5.             @Override  
  6.             public void run() {  
  7.                 handleIntent(context, intent);//耗时操作  
  8.                result.finish();  
  9.             }  
  10.         });  
  11.     }  


[java]  view plain  copy
  1. public final class AsyncHandler {  
  2.     private static final HandlerThread sHandlerThread = new HandlerThread("AsyncHandler");  
  3.     private static final Handler sHandler;  
  4.   
  5.     static {  
  6.         sHandlerThread.start();  
  7.         sHandler = new Handler(sHandlerThread.getLooper());  
  8.     }  
  9.   
  10.     public static void post(Runnable r) {  
  11.         sHandler.post(r);  
  12.     }  
  13.   
  14.     private AsyncHandler() {}  
  15. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值