要在Android Studio中列出配对设备,可以使用以下代码示例:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter pairedDevicesAdapter;
private ArrayList pairedDevicesList;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化BluetoothAdapter
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 初始化配对设备列表
pairedDevicesList = new ArrayList<>();
pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, pairedDevicesList);
ListView pairedDevicesListView = findViewById(R.id.paired_devices_listview);
pairedDevicesListView.setAdapter(pairedDevicesAdapter);
// 检查设备是否支持蓝牙
if (bluetoothAdapter == null) {
// 设备不支持蓝牙
// 可以在这里做相应的处理
return;
}
// 检查蓝牙是否已启用
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
} else {
// 蓝牙已启用,列出配对设备
listPairedDevices();
}
}
private void listPairedDevices() {
// 获取已配对设备列表
Set pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesList.add(device.getName() + "\n" + device.getAddress());
}
}
pairedDevicesAdapter.notifyDataSetChanged();
}
}
这段代码将在布局中的ListView中显示已配对设备的名称和地址。确保在layout文件中有一个ListView元素,并将其id设置为paired_devices_listview
。
注意:在使用蓝牙功能之前,请确保在AndroidManifest.xml文件中添加了相应的权限。