gpt4 book ai didi

安卓蓝牙获取连接设备

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:09:59 27 4
gpt4 key购买 nike

无论配置文件如何,我如何获取所有连接的 Android 蓝牙设备的列表?

或者,我看到您可以通过 BluetoothManager.getConnectedDevices 获取特定配置文件的所有连接设备。 .

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

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

最佳答案

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

  1. 获取当前配对设备的列表
  2. 扫描或发现范围内的所有其他对象

获取并迭代当前配对设备的列表:

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 接收的 Intent。

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

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();

关于安卓蓝牙获取连接设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30040014/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com