因此从这个特征可以看出,在所调用的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() {}
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。