要查询已配对的设备,您可以使用 BluetoothAdapter 的方法 getBondedDevices() 来获取已配对的设备列表。然后,您可以将设备列表放入 ListView 中,使用 'android.R.layout.simple_list_item_2' 作为列表项的布局。

以下是一个示例代码,演示了如何查询已配对的设备并将它们显示在 ListView 中:

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter bluetoothAdapter;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        listView = findViewById(R.id.listView);

        // 检查设备是否支持蓝牙
        if (bluetoothAdapter == null) {
            // 设备不支持蓝牙
            return;
        }

        // 检查蓝牙是否已启用
        if (!bluetoothAdapter.isEnabled()) {
            // 如果蓝牙未启用,则请求启用蓝牙
            // 可以使用 Intent 来启动系统的蓝牙设置界面
            return;
        }

        // 获取已配对的设备列表
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        ArrayList<String> deviceList = new ArrayList<>();

        // 将设备名称和 MAC 地址添加到列表
        for (BluetoothDevice device : pairedDevices) {
            String deviceName = device.getName();
            String deviceAddress = device.getAddress();
            deviceList.add(deviceName + "\n" + deviceAddress);
        }

        // 将设备列表放入 ListView 中
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_2, deviceList);
        listView.setAdapter(adapter);
    }
}

在这个示例中,我们首先获取默认的蓝牙适配器,然后检查设备是否支持蓝牙和蓝牙是否已启用。然后,我们使用 getBondedDevices() 方法获取已配对的设备列表。接下来,我们将设备名称和 MAC 地址添加到设备列表中,并使用 ArrayAdapter 将设备列表放入 ListView 中。最后,我们使用布局 'android.R.layout.simple_list_item_2' 来定义每个列表项的布局。

请注意,您需要在布局文件中添加一个 ListView 组件,并将其 id 设置为 listView,以便与代码中的 findViewById 方法匹配。

Android 查询已配对蓝牙设备并显示在 ListView 中

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

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