Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BroadcastReceiver onReceive() thread safe?

Tags:

android

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;
       }
      }
like image 906
Manish Avatar asked Sep 06 '13 16:09

Manish


1 Answers

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.

like image 124
CommonsWare Avatar answered Sep 19 '22 16:09

CommonsWare