6

onReceive()线程方法是安全的BroadcastReceiver还是我需要自己实现同步?

如果我有任何在方法内部使用的类级别变量onReceive(),并且该onReceive()方法被快速调用多次,它会导致问题吗?

public class MyBroadCastReceiver extends BroadcastReceiver {

    boolean isFirstTrigger = true;

    @Override
    public void onReceive(Context context, Intent arg1) {
      if(isFirstTrigger)
       {
        //Do something time consuming
        isFirstTrigger = false;
       }
      }
4

1 回答 1

7

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.

于 2013-09-06T16:54:12.283 回答