Is onReceive()
method of BroadcastReceiver
thread safe or I need to implement synchronization on my own?
If I have any class level variable which is being used inside the onReceive()
method, and the onReceive()
method is called multiple times very quickly, would it cause an issue?
public class MyBroadCastReceiver extends BroadcastReceiver {
boolean isFirstTrigger = true;
@Override
public void onReceive(Context context, Intent arg1) {
if(isFirstTrigger)
{
//Do something time consuming
isFirstTrigger = false;
}
}
Is onReceive() method of BroadcastReceiver thread safe or I need to implement synchronization on my own?
It will only ever be called on the main application thread. Hence, it is thread-safe with respect to anything else running on the main application thread.
If I have any class level variable which is being used inside the onReceive() method, and the onReceive() method is called multiple times very quickly, would it cause an issue?
If the BroadcastReceiver
is registered in the manifest, a new instance is created for each broadcast. This is why you do not normally see data members on a BroadcastReceiver
.
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