代码之家  ›  专栏  ›  技术社区  ›  Torantula

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

  •  4
  • Torantula  · 技术社区  · 6 年前

    在里面 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 回复  |  直到 6 年前
        1
  •  3
  •   janos slartidan    6 年前

    The Bluetooth guide in the Android documentation 解释如下:

    为了接收有关发现的每个设备的信息,应用程序必须为ACTION\u FOUND intent注册一个BroadcastReceiver。系统为每个设备广播此意图。intent包含额外字段extra\u DEVICE和extra\u 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上使用蓝牙,我建议您仔细阅读该指南。然后再读一遍;-)

        2
  •  2
  •   stkent    6 年前

    ACTION_FOUND documentation :

    始终包含额外字段 EXTRA_DEVICE EXTRA_CLASS . 可以包含额外字段 EXTRA_NAME 和/或 EXTRA_RSSI 如果可用。

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

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