要查询已配对的设备,并在 list view 中显示设备的名称和地址,你可以按照以下步骤进行操作:

  1. 在 AndroidManifest.xml 文件中添加以下权限:
<uses-permission android:name='android.permission.BLUETOOTH'/>
<uses-permission android:name='android.permission.BLUETOOTH_ADMIN'/>
  1. 在你的 Activity 中创建一个 BluetoothAdapter 对象,用于进行蓝牙操作:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  1. 确保蓝牙已启用。如果蓝牙未启用,可以使用以下代码请求用户启用蓝牙:
if (!bluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
  1. 使用以下代码获取已配对的设备列表:
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
  1. 遍历已配对的设备列表,并将设备的名称和地址添加到一个 List 中:
List<String> deviceList = new ArrayList<>();
for (BluetoothDevice device : pairedDevices) {
    deviceList.add(device.getName() + "\n" + device.getAddress());
}
  1. 创建一个 ArrayAdapter 对象,并将设备列表传递给它:
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, deviceList);
  1. 将 ArrayAdapter 与一个 ListView 绑定,并在界面上显示设备列表:
ListView listView = findViewById(R.id.list_view);
listView.setAdapter(adapter);

这样,你就可以查询已配对的设备,并在 list view 中显示设备的名称和地址了。请确保在布局文件中添加一个 ListView 控件,并将其 id 设置为“list_view”。

Android 蓝牙配对设备查询与显示

原文地址: https://www.cveoy.top/t/topic/o6rh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录