在Android Studio中配对蓝牙设备

Kirchhoff1415:

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

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

现在我有这个

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;
            }
        }
    }
}

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

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

nhoxbypass:

首次请求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 ");
    }

然后创建一个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
            }           
        }
    };

并通过注册以下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();
    }

设备从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();  
    } 

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章