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_SCAN和BLUETOOTH_CONNECT权限,低版本则需要ACCESS_COARSE_LOCATION或ACCESS_FINE_LOCATION权限。 - 另外要确保你已经通过代码或AndroidManifest.xml注册了这个广播接收器,并且调用了
BluetoothAdapter.startDiscovery()启动扫描。
内容的提问来源于stack exchange,提问作者Torantula




