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

时间:2018-03-18 21:14:46

标签: java android bluetooth android-bluetooth

this question中,@ 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 个答案:

答案 0 :(得分:3)

The Bluetooth guide in the Android documentation解释了这一点:

  

为了接收有关发现的每个设备的信息,您的应用程序必须为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上使用蓝牙,我建议您仔细阅读该指南。然后再读一次; - )

答案 1 :(得分:2)

来自ACTION_FOUND documentation

  

始终包含额外字段EXTRA_DEVICEEXTRA_CLASS。如果可用,可以包含额外字段EXTRA_NAME和/或EXTRA_RSSI

EXTRA_DEVICE can be used to obtain the BluetoothDevice that was found通过以下代码:

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);