Android蓝牙获得连接设备

时间:2015-05-04 21:08:44

标签: android bluetooth android-bluetooth bluetooth-profile

如何获取适用于Android的所有连接蓝牙设备的列表,无论配置文件是什么?

或者,我发现您可以通过BluetoothManager.getConnectedDevices获取特定个人资料的所有连接设备。

我想我可以通过ACTION_ACL_CONNECTED / ACTION_ACL_DISCONNECTED 监听连接/断开连接来查看连接的设备......似乎容易出错

但我想知道是否有更简单的方法来获取所有连接蓝牙设备的列表。

2 个答案:

答案 0 :(得分:3)

要查看完整列表,这是一个两步操作:

  1. 获取当前配对设备的列表
  2. 扫描或发现范围内的所有其他人
  3. 获取当前配对设备的列表并进行迭代:

    Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice d: pairedDevices) {
            String deviceName = d.getName();
            String macAddress = d.getAddress();
            Log.i(LOGTAG, "paired device: " + deviceName + " at " + macAddress);
            // do what you need/want this these list items
        }
    }
    

    发现更复杂的操作。为此,您需要告诉BluetoothAdapter开始扫描/发现。当它找到东西时,它会发送你需要通过BroadcastReceiver接收的Intents。

    首先,我们将设置接收器:

    private void setupBluetoothReceiver()
    {
        BroadcastRecevier btReceiver = new BroadcastReciver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                handleBtEvent(context, intent);
            }
        };
        IntentFilter eventFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        // this is not strictly necessary, but you may wish
        //  to know when the discovery cycle is done as well
        eventFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        myContext.registerReceiver(btReceiver, eventFilter);
    }
    
    private void handleBtEvent(Context context, Intent intent)
    {
        String action = intent.getAction();
        Log.d(LOGTAG, "action received: " + action);
    
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.i(LOGTAG, "found device: " + device.getName());
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            Log.d(LOGTAG, "discovery complete");
        }
    }
    

    现在剩下的就是告诉BluetoothAdapter开始扫描:

    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    // if already scanning ... cancel
    if (btAdapter.isDiscovering()) {
        btAdapter.cancelDiscovery();
    }
    
    btAdapter.startDiscovery();
    

答案 1 :(得分:1)

这就是您获得“连接”设备的方式,而不仅仅是配对设备。无需进一步检查它的状态。

val btManager = view.getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
val connectedDevices = btManager.getConnectedDevices(GATT)