Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Android's BroadcastReceivers started in a new thread?

If I have an inner class that extends BroadcastReceiver within my Service class, should I care about synchronization, when the BroadcastReceiver class reads/writes to objects from the Service class? Or to put it in another way: Are BroadacstReceiver's onReceive() Methods started in an extra thread?

like image 396
Flow Avatar asked Mar 22 '11 16:03

Flow


People also ask

What is the life cycle of broadcast receivers in Android?

When a broadcast message arrives for the receiver, Android calls its onReceive() method and passes it the Intent object containing the message. The broadcast receiver is considered to be active only while it is executing this method. When onReceive() returns, it is inactive.

Which thread broadcast receivers will work in Android?

Broadcast Receiver by default runs on Main Thread only.

How do I know if my broadcast receiver is registered?

A simple solution to this problem is to call the registerReceiver() in your Custom Application Class. This will ensure that your Broadcast receiver will be called only one in your entire Application lifecycle.


2 Answers

The onReceive() method is always called on the main thread (which is also referred to as "UI thread"), unless you requested it to be scheduled on a different thread using the registerReceiver() variant:

Context.registerReceiver(BroadcastReceiver receiver,                          IntentFilter filter,                          String broadcastPermission,                          Handler scheduler) 
like image 176
Nick Pelly Avatar answered Sep 20 '22 12:09

Nick Pelly


Are Android's BroadcastReceivers started in a new thread?

Usually but not always, it all depends on 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.

like image 21
Caner Avatar answered Sep 20 '22 12:09

Caner