Android9.0连接多个蓝牙设备,获取正在使用的设备信息

Android 9.0之后,支持一台手机可以同时连接多个蓝牙设备。以一台手机连接2个蓝牙耳机为例,关于如何获取多个设备的列表,可以参考下面代码。

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.getProfileProxy(this, new BluetoothProfile.ServiceListener() {
    @Override
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        List mDevices = proxy.getConnectedDevices();
        if (mDevices != null && mDevices.size() > 0) {
            for (BluetoothDevice device : mDevices) {
                if (device != null) {
                    Log.e(TAG, "device name: " + device.getName());
                }
            }
        }
    }

    @Override
    public void onServiceDisconnected(int profile) {

    }
}, BluetoothProfile.HEADSET);

重点是如何获取正在使用的设备信息呢?在BluetoothHeadset(蓝牙耳机)类中,可以看到下面方法:
Android9.0连接多个蓝牙设备,获取正在使用的设备信息_第1张图片
这个方法就是获取正在使用的设备信息,但是被hide了,需要反射,在上面代码的基础上加上反射即可:

BluetoothA2dp a2dp = null;
if (proxy instanceof BluetoothA2dp) {
    a2dp = (BluetoothA2dp) proxy;
    try {
        Class bluetoothA2dp = Class.forName("android.bluetooth.BluetoothA2dp");
        Method getActiveDevice = bluetoothA2dp.getMethod("getActiveDevice");
        BluetoothDevice device =
                (BluetoothDevice) getActiveDevice.invoke(a2dp);
        String name = device.getName();
        Log.e(TAG, "active device name: " + name);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

上面的方法是主动获取当前正在使用的设备,如果是在设置里面更改使用的设备,我们马上就可以接受到这个信息呢,这里可以监听系统的广播,这个广播也在BluetoothHeadset类中,同样被hide了,如下
Android9.0连接多个蓝牙设备,获取正在使用的设备信息_第2张图片
不过,这个不用反射,我们在代码中只需要用字符串代替即可,代码如下:

IntentFilter filter = new IntentFilter();
filter.addAction("android.bluetooth.headset.profile.action.ACTIVE_DEVICE_CHANGED");
registerReceiver(new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "onReceive action = " + intent.getAction());
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Log.e(TAG, "onReceive bundle = " + bundle);
            BluetoothDevice device = bundle.getParcelable(BluetoothDevice.EXTRA_DEVICE);
        }
    }
}, filter);

你可能感兴趣的:(android,bluetooth,蓝牙)