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
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.
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.
There are two ways to register your broadcast receiver: statically in the manifest, or dynamically in your activity.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With