在 Android Studio 中配对蓝牙设备

Kir*_*415 2 java android bluetooth

我正在创建一个应通过蓝牙连接到特定设备的应用程序。

我希望我的应用程序与此设备连接,无论它是否已配对。

现在我有这个

private void findDevice() {
    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            if (device.getName().equals(DEVICE_NAME)) {
                bluetoothDevice = device;
                deviceFound = true;
                break;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但此功能仅连接到配对设备。如果我的设备尚未配对,我想配对它。不知道该怎么做。

有人可以给我任何建议吗?

nho*_*ass 5

首先请求BLUETOOTH_ADMIN许可。

然后使您的设备可被发现:

private void makeDiscoverable() {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);
        Log.i("Log", "Discoverable ");
    }
Run Code Online (Sandbox Code Playgroud)

然后创建一个BroadcastReceiver来监听来自系统的动作:

private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Message msg = Message.obtain();
            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
               //Found, add to a device list
            }           
        }
    };
Run Code Online (Sandbox Code Playgroud)

并通过注册此BoardcastReceiver开始搜索设备:

 private void startSearching() {
        Log.i("Log", "in the start searching method");
        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
        bluetoothAdapter.startDiscovery();
    }
Run Code Online (Sandbox Code Playgroud)

设备从BroadcastReceiver进入列表后,从列表中选择您的设备,然后createBond()执行以下操作:

 public boolean createBond(BluetoothDevice btDevice)  
    throws Exception  
    { 
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");  
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    } 
Run Code Online (Sandbox Code Playgroud)

然后使用上面的代码来管理绑定设备。