Android 查询并显示已配对蓝牙设备
要查询已配对的设备,可以使用 BluetoothAdapter 的方法 getBondedDevices()。这将返回一个 Set
然后,您可以将这些设备的名称和地址显示在 ListView 中。为此,您可以创建一个 ArrayAdapter,将设备的名称和地址作为数据源。然后,将该 ArrayAdapter 设置为 ListView 的适配器。
以下是一个示例代码,演示如何查询已配对的设备并在 ListView 中显示它们的名称和地址:
// 获取 BluetoothAdapter 实例
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 查询已配对的设备
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
// 创建一个 ArrayList 来存储设备的名称和地址
ArrayList<String> deviceList = new ArrayList<>();
for (BluetoothDevice device : bondedDevices) {
String deviceName = device.getName();
String deviceAddress = device.getAddress();
String deviceInfo = deviceName + '\n' + deviceAddress;
deviceList.add(deviceInfo);
}
// 创建一个 ArrayAdapter 来显示设备列表
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_2, android.R.id.text1, deviceList);
// 设置 ListView 的适配器
ListView listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
请注意,上述代码中的 R.id.listView 指的是代表 ListView 的布局文件中的 ListView 元素的 ID。您需要根据您的布局文件进行适当的更改。
原文地址: https://www.cveoy.top/t/topic/o6ri 著作权归作者所有。请勿转载和采集!