Android 蓝牙配对设备查询及 ListView 显示
要查询已配对的设备,可以使用 Android 的 BluetoothAdapter 类的方法 getBondedDevices()。这个方法会返回一个 Set 类型的已配对设备列表。然后,你可以将这个列表传递给一个 ListView 适配器,以便在 ListView 中显示设备信息。
下面是一个示例代码:
// 获取 BluetoothAdapter 对象
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 查询已配对设备列表
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// 将设备列表转换为 ArrayList
ArrayList<BluetoothDevice> pairedDeviceList = new ArrayList<>(pairedDevices);
// 创建 ListView 适配器
ArrayAdapter<BluetoothDevice> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, pairedDeviceList);
// 设置 ListView 适配器
ListView listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
在上面的示例中,我们首先获取 BluetoothAdapter 对象,然后调用 getBondedDevices() 方法查询已配对设备列表。接下来,我们将设备列表转换为 ArrayList,并使用 ArrayAdapter 创建一个 ListView 适配器。最后,我们将适配器设置给 ListView,以便在界面中显示设备信息。
注意:为了运行这个示例,你需要在布局文件中添加一个 ListView 控件,并将其 id 设置为 'listView'。
原文地址: https://www.cveoy.top/t/topic/o6qm 著作权归作者所有。请勿转载和采集!