Android 检查蓝牙状态
public void checkBtDeviceConnectionStates(Context context) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Log.e(TAG, "checkBtDeviceConnectionStates():蓝牙设备不支持 或 未开启蓝牙");
return;
}
@SuppressLint("MissingPermission") Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices != null && !pairedDevices.isEmpty()) {
for (BluetoothDevice device : pairedDevices) {
boolean a2dpState = bluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
@SuppressLint("MissingPermission") int connectionState = ((BluetoothA2dp) proxy).getConnectionState(device);
switch (connectionState) {
case BluetoothProfile.STATE_CONNECTED:
android.util.Log.d(TAG, "onServiceConnected: STATE_CONNECTED");
bluetoothConnected = true;
break;
case BluetoothProfile.STATE_CONNECTING:
android.util.Log.d(TAG, "onServiceConnected: STATE_CONNECTING");
break;
case BluetoothProfile.STATE_DISCONNECTED:
android.util.Log.d(TAG, "onServiceConnected: STATE_DISCONNECTED");
bluetoothConnected = false;
break;
case BluetoothProfile.STATE_DISCONNECTING:
android.util.Log.d(TAG, "onServiceConnected: STATE_DISCONNECTING");
break;
}
bluetoothAdapter.closeProfileProxy(profile, proxy);
}
}
@Override
public void onServiceDisconnected(int profile) {
bluetoothConnected = false;
}
}, BluetoothProfile.A2DP);
}
}
}