BroadcastReceiver.PendingResult

[url]http://developer.android.com/reference/android/content/BroadcastReceiver.PendingResult.html[/url]
State for a result that is pending for a broadcast receiver. Returned by goAsync() while in BroadcastReceiver.onReceive(). This allows you to return from onReceive() without having the broadcast terminate; you must call finish() once you are done with the broadcast. This allows you to process the broadcast off of the main thread of your app.

Note on threading: the state inside of this class is not itself thread-safe, however you can use it from any thread if you properly sure that you do not have races. Typically this means you will hand the entire object to another thread, which will be solely responsible for setting any results and finally calling finish().

[url]http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#broadcastreceiver_asynchronousprocessing[/url]

1.4. Asynchronous processing

Before API level 11, you could not perform any asynchronous operation in the onReceive() method, because once the onReceive() method had been finished, the Android system was allowed to recycle that component. If you have potentially long running operations, you should trigger a service instead.

Since Android API 11 you can call the goAsync() method. This method returns an object of the PendingResult type. The Android system considers the receiver as alive until you call the PendingResult.finish() on this object. With this option you can trigger asynchronous processing in a receiver. As soon as that thread has completed, its task calls finish() to indicate to the Android system that this component can be recycled.



private static Handler sAsyncHandler;

static {
final HandlerThread thread = new HandlerThread("DownloadReceiver");
thread.start();
sAsyncHandler = new Handler(thread.getLooper());
}

if (Intent.ACTION_UID_REMOVED.equals(action)) {
final PendingResult result = goAsync();
sAsyncHandler.post(new Runnable() {
@Override
public void run() {
handleUidRemoved(context, intent);
result.finish();
}
});

private void handleUidRemoved(Context context, Intent intent) {
final ContentResolver resolver = context.getContentResolver();

final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
final int count = resolver.delete(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, Constants.UID + "=" + uid, null);

if (count > 0) {
Slog.d(TAG, "Deleted " + count + " downloads owned by UID " + uid);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值