I need to detect when wired headset or a bluetooth one is plugged/connected so I create and register two BroadcastReceiver
(s) like the following:
file ReceiverHeadsetWired.java
public class ReceiverHeadsetWired extends BroadcastReceiver {
ActivityMain main;
public ReceiverHeadsetWired(
ActivityMain activityMain
){
main = activityMain;
}
@Override
public void onReceive(
Context context,
Intent intent
) {
if (TextUtils.isEmpty(intent.getAction())) { return; }
if (Objects.equals(intent.getAction(), "android.intent.action.HEADSET_PLUG")) {
Log.d("[ReceiverHeadsetWired]", "onReceive()");
...
}
}
}
file ReceiverHeadsetBluetooth.java
public class ReceiverHeadsetBluetooth extends BroadcastReceiver {
ActivityMain main;
public ReceiverHeadsetBluetooth(
ActivityMain activityMain
){
main = activityMain;
}
@Override
public void onReceive(
Context context,
Intent intent
) {
if (TextUtils.isEmpty(intent.getAction())) { return; }
if (Objects.equals(intent.getAction(), "android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED")) {
Log.d("[ReceiverHeadsetBluetooth]", "onReceive()");
...
}
}
}
Both of them are dynamically registered in onCreate
method of MainActivity's Fragment and unregisterd onDestroy
.
@Override
public void onCreate(
Bundle savedInstanceState
) {
super.onCreate(savedInstanceState);
ActivityMain main = (ActivityMain) getActivity();
...
registerHeadsetWiredReceiver();
registerHeadsetBluetoothReceiver();
...
}
private void registerHeadsetWiredReceiver() {
wiredHeadsetReceiver = new ReceiverHeadsetWired(main);
IntentFilter hwFilter = new IntentFilter("android.intent.action.HEADSET_PLUG");
main.registerReceiver(wiredHeadsetReceiver, hwFilter);
}
private void registerHeadsetBluetoothReceiver() {
bluetoothHeadsetReceiver = new ReceiverHeadsetBluetooth(main);
IntentFilter hbFilter = new IntentFilter("android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED");
main.registerReceiver(bluetoothHeadsetReceiver, hbFilter);
}
Now the point is that at launch only the onReceive
of ReceiverHeadsetWired is called (Logcat shows the textline), but after app started both of them work as expected except a strange behaviour: the first time I connect a Bluetooth headset the related Log is written twice.
In other words when app is launched if a wired headset is plugged it will be detected but a connected bluetooth one won't.
Does anybody knows what's the problem?
Thanks in advance