【问题标题】:Pair a bluetooth device in Android Studio在 Android Studio 中配对蓝牙设备
【发布时间】:2023-03-19 15:35:01
【问题描述】:

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

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

现在我有这个

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

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

有人能给我一些建议吗?

【问题讨论】:

  • 您是否请求了 BLUETOOTH_ADMIN 权限?
  • 是的,我确实要求
  • 老实说,我在理解该主题的代码方面存在问题。我对 Android 工作室完全陌生。
  • im 使用 SetpairedDevice = bluetoothAdapter.getBondedDevices();获取所有已绑定的设备,然后只需比较它们的名称即可找到我愿意连接的设备。但是为未绑定的设备创建相同的列表时遇到问题。

标签: java android bluetooth


【解决方案1】:

第一次请求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();  
    } 

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

【讨论】:

  • 伙计,非常感谢,似乎合法。但是广播接收器有问题。 Android Studio 说我无法解析符号“BroadcastReciever”。我在谷歌上搜索答案,但找不到一个:(
  • @Kirchhoff1415 什么问题?
  • 好的,知道了,我错过了 import android.content.BroadcastReceiver;部分
  • 那么你成功了吗?
  • 好的,我遇到了“创建键”功能的问题。我得到无法使用“方法”和“调用”解析符号我已经复制了来自stackoverflow.com/questions/14228289/… 的所有导入,但它没有帮助:(
猜你喜欢
  • 1970-01-01
  • 2011-12-15
  • 1970-01-01
  • 2016-09-26
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多