获取 Android 上可用的蓝牙设备列表

Tor*_*ula 5 java android bluetooth android-bluetooth

在这个问题中,@nhoxbypass 提供了此方法,用于将找到的蓝牙设备添加到列表中:

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)

但是,我不明白如何获得对找到的设备的引用,这该怎么做?

我无权对原始问题发表评论,所以我选择在这里扩展它。

Sto*_*ica 3

Android 文档中的蓝牙指南对此进行了解释:

为了接收有关发现的每个设备的信息,您的应用程序必须为 ACTION_FOUND 意图注册一个 BroadcastReceiver。系统为每个设备广播此意图。该意图包含额外的字段 EXTRA_DEVICE 和 EXTRA_CLASS,它们又分别包含蓝牙设备和蓝牙类。

还包含此示例代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...

    // Register for broadcasts when a device is discovered.
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);
}

// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Discovery has found a device. Get the BluetoothDevice
            // object and its info from the Intent.
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); // MAC address
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

如果您在 Android 上使用蓝牙,我建议您仔细阅读该指南。然后再读一遍;-)