Obtaining a List of Available Bluetooth Devices on Android

时光毁灭记忆、已成空白 提交于 2019-12-02 03:54:44

问题


In this question, @nhoxbypass provides this method for the purpose of adding found Bluetooth devices to a list:

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
            }           
        }
    };

However, I do not understand how a reference to the found device can be obtained, how can this be done?

I do not have permission to comment on the original question, so I have chosen to extend it here.


回答1:


The Bluetooth guide in the Android documentation explains this:

In order to receive information about each device discovered, your application must register a BroadcastReceiver for the ACTION_FOUND intent. The system broadcasts this intent for each device. The intent contains the extra fields EXTRA_DEVICE and EXTRA_CLASS, which in turn contain a BluetoothDevice and a BluetoothClass, respectively.

This sample code is included as well:

@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
        }
    }
};

If you are working with Bluetooth on Android, I suggest to read that guide carefully. Then read it one more time ;-)




回答2:


From the ACTION_FOUND documentation:

Always contains the extra fields EXTRA_DEVICE and EXTRA_CLASS. Can contain the extra fields EXTRA_NAME and/or EXTRA_RSSI if they are available.

EXTRA_DEVICE can be used to obtain the BluetoothDevice that was found via code like:

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


来源:https://stackoverflow.com/questions/49352868/obtaining-a-list-of-available-bluetooth-devices-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!