You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android获取可用蓝牙设备列表:如何获取发现设备的引用?

获取Android蓝牙扫描发现的设备引用

别着急,我来帮你搞定这个问题!其实获取已发现蓝牙设备的引用非常简单,你只需要从广播的Intent中提取携带的BluetoothDevice对象就可以了。以下是补充完整后的代码示例:

private BroadcastReceiver myReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
        String action = intent.getAction(); 
        if(BluetoothDevice.ACTION_FOUND.equals(action)){ 
            // 从Intent中获取发现的蓝牙设备对象
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            
            if (device != null) {
                // 获取设备的关键信息,比如名称和MAC地址
                String deviceName = device.getName();
                String deviceMac = device.getAddress();
                
                // 将设备添加到预定义的列表中
                // 假设你已经声明了:List<BluetoothDevice> deviceList = new ArrayList<>();
                deviceList.add(device);
                
                // 如果要更新UI(比如刷新ListView),记得切换到主线程操作
                runOnUiThread(() -> {
                    yourDeviceAdapter.notifyDataSetChanged();
                });
            }
        }
    } 
};

关键细节说明:

  • 当系统扫描到蓝牙设备时,会发送带有BluetoothDevice.ACTION_FOUND动作的广播,这个广播的Intent里默认携带了发现的设备实例,对应的键是BluetoothDevice.EXTRA_DEVICE
  • 调用intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)就能拿到BluetoothDevice的引用,通过这个对象你可以获取设备的名称、MAC地址等核心信息。
  • 注意:如果设备名称返回null,通常是因为该蓝牙设备未设置名称,或者你的应用没有申请足够的蓝牙权限——Android 12及以上版本需要申请BLUETOOTH_SCANBLUETOOTH_CONNECT权限,低版本则需要ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION权限。
  • 另外要确保你已经通过代码或AndroidManifest.xml注册了这个广播接收器,并且调用了BluetoothAdapter.startDiscovery()启动扫描。

内容的提问来源于stack exchange,提问作者Torantula

火山引擎 最新活动