Register a broadcast receiver from a service in a new thread

时间秒杀一切 提交于 2019-12-06 07:20:15

问题


I have a broadcastreciever which start a long operation (uploading process). In the code of a service started from the Activity class, I need to register this receiver in a new thread.

I have checked this post Are Android's BroadcastReceivers started in a new thread? but I need a more concrete example about using Context.registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)

Actually I need to know how to create a new thread from a service and to register the receiver and attached to this thread.

Thank you very much. RA


回答1:


In your service's onCreate():

private Handler handler; // Handler for the separate Thread

HandlerThread handlerThread = new HandlerThread("MyNewThread");
handlerThread.start();
// Now get the Looper from the HandlerThread so that we can create a Handler that is attached to
//  the HandlerThread
// NOTE: This call will block until the HandlerThread gets control and initializes its Looper
Looper looper = handlerThread.getLooper();
// Create a handler for the service
handler = new Handler(looper);
// Register the broadcast receiver to run on the separate Thread
registerReceiver (myReceiver, intentFilter, broadcastPermission, handler);


来源:https://stackoverflow.com/questions/10682241/register-a-broadcast-receiver-from-a-service-in-a-new-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!