`

BroadcastReceiver.PendingResult

阅读更多
http://developer.android.com/reference/android/content/BroadcastReceiver.PendingResult.html
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().

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

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);
        }
    }




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics