在安卓上获取可用蓝牙设备列表

5
这个问题中,@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
            }           
        }
    };

然而,我不理解如何获得对找到设备的引用,这可以怎样做? 我没有评论原问题的权限,因此我选择在此处进行扩展。
2个回答

3
Android文档中的蓝牙指南解释了以下内容:
要接收有关每个发现设备的信息,您的应用程序必须为ACTION_FOUND意图注册BroadcastReceiver。系统会为每个设备广播此意图。该意图包含额外字段EXTRA_DEVICE和EXTRA_CLASS,它们分别包含BluetoothDevice和BluetoothClass。
示例代码也已包含在内:
@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
        }
    }
};
如果你在Android上使用蓝牙技术,我建议你认真阅读这篇指南。然后再读一遍;-)

非常感谢,我会遵循您的建议 ;) - Torantula
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) 中,我得到了空值。我是否漏掉了什么?我已经在 AndroidManifest 中添加了 ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATIONBLUETOOTHBLUETOOTH_ADMIN 权限,并确保已授予 ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION - Jan sebastian

2

那么,为了澄清一下,BluetoothDevice.EXTRA_DEVICE 是指类型为 BluetoothDevice 的已发现设备吗? - Torantula

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接