获取当前连接的蓝牙设备的名称

首先需要在清单文件添加权限:

    
    
    

获取当前连接蓝牙设备名称需要先获取已绑定或已匹配的蓝牙列表,然后再一个一个判断是否在连接状态,但是因为android现在将获取蓝牙设备连接状态的方法隐藏了,所以我们需要使用反射调用,下面是获取连接状态的源码:

 /**
     * Returns whether there is an open connection to this device.
     * 

Requires {@link android.Manifest.permission#BLUETOOTH}. * * @return True if there is at least one open connection to this device. * @hide (注意这个,已隐藏) */ @SystemApi @RequiresPermission(android.Manifest.permission.BLUETOOTH) public boolean isConnected() { final IBluetooth service = sService; if (service == null) { // BT is not enabled, we cannot be connected. return false; } try { return service.getConnectionState(this) != CONNECTION_STATE_DISCONNECTED; } catch (RemoteException e) { Log.e(TAG, "", e); return false; } }

明白了这个后就好办了,下面是获取当前连接的蓝牙设备名称的方法代码:

   private String getConnectedBtDevice() {
   		//获取蓝牙适配器
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //得到已匹配的蓝牙设备列表
        Set bondedDevices = bluetoothAdapter.getBondedDevices();
        if (bondedDevices != null && bondedDevices.size() > 0) {
            for (BluetoothDevice bondedDevice : bondedDevices) {
                try {
                	//使用反射调用被隐藏的方法
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    isConnectedMethod.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(bondedDevice, (Object[]) null);
                    Log.e("123", "isConnected:" + isConnected);
                    if (isConnected) {
                        return bondedDevice.getName();
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

你可能感兴趣的:(andorid,常用,安卓,android)