Skip to content Skip to sidebar Skip to footer

Register A Broadcast Receiver From A Service In A New Thread

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 thr

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

Post a Comment for "Register A Broadcast Receiver From A Service In A New Thread"