Does BroadcastReceiver.onReceive always run in the UI thread?

后端 未结 5 1367
星月不相逢
星月不相逢 2020-11-28 02:35

In my App, I create a custom BroadcastReceiver and register it to my Context manually via Context.registerReceiver. I also have an AsyncTask<

5条回答
  •  半阙折子戏
    2020-11-28 03:03

    Does BroadcastReceiver.onReceive always run in the UI thread?

    Usually, it all depends how you register it.

    If you register your BroadcastReceiver using:

    registerReceiver(BroadcastReceiver receiver, IntentFilter filter)
    

    It will run in the main activity thread(aka UI thread).

    If you register your BroadcastReceiver using a valid Handler running on a different thread:

    registerReceiver (BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)
    

    It will run in the context of your Handler

    For example:

    HandlerThread handlerThread = new HandlerThread("ht");
    handlerThread.start();
    Looper looper = handlerThread.getLooper();
    Handler handler = new Handler(looper);
    context.registerReceiver(receiver, filter, null, handler); // Will not run on main thread
    

    Details here & here.

提交回复
热议问题