Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 972
Rami Avatar asked May 21 '12 09:05

Rami


People also ask

Where do I register and unregister broadcast receiver?

Receiver can be registered via the Android manifest file. You can also register and unregister a receiver at runtime via the Context. registerReceiver() and Context. unregisterReceiver() methods.

How do I register a broadcast receiver in manifest?

There are two ways to make a broadcast receiver known to the system: One is declare it in the manifest file with this element. The other is to create the receiver dynamically in code and register it with the Context. registerReceiver() method.

How many ways are there to register the broadcast receivers?

There are two ways to register your broadcast receiver: statically in the manifest, or dynamically in your activity.


1 Answers

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);
like image 124
David Wasser Avatar answered Oct 15 '22 17:10

David Wasser