Android BroadcastReceiver onReceive() called twice on android 4.0

前端 未结 15 2283
梦谈多话
梦谈多话 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:00

    I have found the reason for this issue.

    Basically when we register the receiver for BLUETOOTH_STATE_CHANGE then if we are Turning ON the bluetooth then its onReceive() method will call twice for the following two Bluetooth States:

    STATE 1: STATE_TURNING_ON Indicates the local Bluetooth adapter is turning on.

    STATE 2: STATE_ON Indicates the local Bluetooth adapter is on, and ready for use.

    Same while Turing OFF the bluetooth then its onReceive() method will again call twice for the following two Bluetooth States:

    STATE 1: STATE_TURNING_OFF Indicates the local Bluetooth adapter is turning off.

    STATE 2: STATE_OFF Indicates the local Bluetooth adapter is off.

    So basically we can handle this situation in the following way:

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action != null && action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_ON) {
    
                // When Bluetooth adapter is on, and ready for use
                //DO YOUR CODE HERE FOR "BLUETOOTH ON" CASE
    
    
            }
            else if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
    
                //When local Bluetooth adapter is off
                //DO YOUR CODE HERE FOR "BLUETOOTH OFF" CASE
    
            }
    
        }
    } 
    

    After looking to your code(@girlOnSledge), it seems that if you will follow the above procedure, your code will also work fine in that case.

提交回复
热议问题