Android BroadcastReceiver onReceive() called twice on android 4.0

前端 未结 15 2215
梦谈多话
梦谈多话 2020-12-29 20:38

I faced to one problem on android 4.0.3 (on 4.1.2 it works fine). I have in my Activity BroadcastReceiver. When I send a broadcast, method onReceive() called always twice. P

相关标签:
15条回答
  • 2020-12-29 21:07

    I have just had this problem and I found a solution that wasn't mentioned in any of the existed answers, so I would like to share it.

    I register the BroadcastReceiver just once in onCreate

    However, I was registering it like this:

    LocalBroadcastManager.getInstance(this).registerReceiver(new MyBroadcastReceiver(), mStatusIntentFilter);
    

    In other words, I was constructing the boradcastReceiver instance inside the registerReceiver call.

    But when I construct the BroadcastReceiver in a separate statement the problem was solved. Like this:

    MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
    
    LocalBroadcastManager.getInstance(this).registerReceiver(myBroadcastReceiver , mStatusIntentFilter);
    

    Very weird workaround, maybe it's a bug that will be fixed later.

    0 讨论(0)
  • 2020-12-29 21:09

    Usually onReceive is being called twice since people are registering the broadcast in 2 locations, Most likely you are registering in your onCreate and in your onResume. (Choose one spot to register).

    Although you might have done it probably a dozen of times - it is always recommended to take another glance at the Activity Life Cycle.

    0 讨论(0)
  • 2020-12-29 21:09

    I was calling sendBroadcast(intent) multiple times in my Service class

    Removing one of them fixed the problem.

    0 讨论(0)
提交回复
热议问题