Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

3.7. 蓝牙设备管理

3.7.1. 进入蓝牙设置界面

			
if (!bluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}			
			
			

3.7.2. 通过发送广播处理蓝牙

			
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
registerReceiver(bluetoothReceiver, filter);			
			
			

3.7.3. 蓝牙禁用/启用

			
	public static void bluetoothManager() {

        if (ActivityCompat.checkSelfPermission(MainApplication.getContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null) {
              bluetoothAdapter.disable();
        }
    }					
			
			

3.7.4. 获取蓝牙设备

			
		if (ActivityCompat.checkSelfPermission(MainApplication.getContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);			
			
			

3.7.5. 查询已绑定设备

			
	public static void bluetoothManager() {

        if (ActivityCompat.checkSelfPermission(MainApplication.getContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//            if (bluetoothAdapter != null) {
//                bluetoothAdapter.disable();
//            }
        if (bluetoothAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
            bondedDevices.forEach(bluetoothDevice -> {
                Log.d(TAG, "bluetoothManager " + bluetoothDevice.getName());
            });
        }

    }