Vitto Russo
Vitto Russo

Reputation: 29

BroadcastReceiver Conflict

I'm currently trying to manage 2 different Bluetooth Low Energy peripherals via different Fragments in the same activity.

The problem i'm currently having is that the broadcast receiver is triggered in both fragments by the same 1 peripheral.

Both fragments have different classes and method names since i pretend to do different things with the incoming data.

This is the BroadcastReceiver method:

private final BroadcastReceiver mGattUpdateReceiver2 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("OnReceive2");
            final String action = intent.getAction();
            if (BluetoothLeServiceHeart.ACTION_GATT_CONNECTED.equals(action)) {
                mConnected2 = true;
                updateConnectionState(R.string.connected);
            } else if (BluetoothLeServiceHeart.ACTION_GATT_DISCONNECTED.equals(action)) {
                mConnected2 = false;
                updateConnectionState(R.string.disconnected);
                clearUI();
            } else if (BluetoothLeServiceHeart.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                displayGattServices2(mBluetoothLeService2.getSupportedGattServices());
            } else if (BluetoothLeServiceHeart.ACTION_DATA_AVAILABLE.equals(action)) {
                displayData(intent.getStringExtra(BluetoothLeServiceHeart.EXTRA_DATA));
            }
        }
    };

I guess my question is, am i suppose to have different BroadcastReceivers for each one? if so how would i go around it. Or is there something i am fundamentally doing wrong?

Upvotes: 0

Views: 132

Answers (1)

Micer
Micer

Reputation: 8979

You should create only 1 BroadcastReceiver class. If you need to differentiate between the call from fragment1 and fragment2, you can put extra to calling intent. In example:

// fragment1
intent.putExtra("key","fragment1");
context.sendBroadcast(intent);

// fragment2
intent.putExtra("key","fragment2");
context.sendBroadcast(intent);

Then on onReceive:

String value = getIntent().getExtras().getString("key");
if (value.equals("fragment1") {
    // called from fragment1
} else {
    // called from fragment2
}

Upvotes: 1

Related Questions