我正在开发一个应用程序,我需要知道是否连接了蓝牙耳机。我创建了一个广播接收器,如果我们在应用程序打开时连接到蓝牙耳机,它会接收广播意图。另一方面,如果连接到蓝牙设备然后启动应用程序,我没有收到任何蓝牙设备连接的广播。我想知道在应用程序启动时是否连接了任何蓝牙耳机。以下是我的广播接收器和清单。
public class BluetoothDeviceConnectionReciver extends BroadcastReceiver {
static OnBluetoothDeviceStateChangeLisener onBluetoothStateChangedListener;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//int headsetAudioState = intent.getIntExtra("android.bluetooth.headset.extra.AUDIO_STATE", -2);
//Toast.makeText(context, "New Test", Toast.LENGTH_SHORT).show();
//BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("headsetAudioState","in broadcast");
if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
int bluetoothHeadsetState = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,
BluetoothHeadset.STATE_DISCONNECTED);
Log.i("headsetAudioState",bluetoothHeadsetState+" ");
//Device found
if (bluetoothHeadsetState == BluetoothHeadset.STATE_CONNECTED) {
if (onBluetoothStateChangedListener != null)
onBluetoothStateChangedListener.OnBluetoothHeadsetConnected();
Log.i("headsetAudioState",bluetoothHeadsetState+" connected");
}
if(bluetoothHeadsetState == BluetoothHeadset.STATE_DISCONNECTED){
if (onBluetoothStateChangedListener != null)
onBluetoothStateChangedListener.OnBluetoothHeadsetDisconnected();
Log.i("headsetAudioState",bluetoothHeadsetState+" disconnected");
}
}
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Device is now connected
if (onBluetoothStateChangedListener != null)
onBluetoothStateChangedListener.OnBluetoothHeadsetConnected();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//Done searching
} else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//Device is about to disconnect
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Device has disconnected
if (onBluetoothStateChangedListener != null)
onBluetoothStateChangedListener.OnBluetoothHeadsetDisconnected();
}
}
public void setOnBluetoothStateChangeListener(OnBluetoothDeviceStateChangeLisener listener){
onBluetoothStateChangedListener = listener;
}
public interface OnBluetoothDeviceStateChangeLisener{
void OnBluetoothHeadsetConnected();
void OnBluetoothHeadsetDisconnected();
}
}
清单.xml
.....
.....
.....
<receiver android:name=".BluetoothDeviceConnectionReciver">
<intent-filter>
<action android:name="android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED"/>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>
</receiver>
.....
.....
我想知道是否还有其他我应该听的意图。或者请让我知道实现预期目标还有哪些其他选择。
PS:连接的设备应该是耳机,因为我打算使用蓝牙耳机的麦克风。