java - 是否可以仅显示已配对、开启且在范围内的蓝牙设备的 Activity 列表,而不是显示所有先前配对的设备?

标签 java android bluetooth arduino android-bluetooth

我目前正在开发一个 Android 应用程序,该应用程序连接到具有蓝牙 SPP 功能的 arduino 微处理器。我的应用程序显示所有以前配对的蓝牙设备,但我想知道是否可以只显示当前已打开的配对设备?我到处寻找答案,但尚未找到,希望这是可能的。

最佳答案

您需要创建一个BluetoothAdapter,并向BluetoothDevice.ACTION_FOUND 注册一个BroadcastReceiver将找到的设备存储在某种列表中。

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, intentFilter);
bluetoothAdapter.startDiscovery();

...
private ArrayList<BluetoothDevice> devices = new ArrayList<>();
private final BroadcastReceiver receiver = new BroadcastReceiver(){
    public void onReceive(Context context, Intent intent){
        String action = intent.getAction();
        if(action.equals(BluetoothAdapter.ACTION_FOUND)){
            BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            devices.add(bluetoothDevice);
        }
    }
};

您还可以将接收器注册到 BluetoothDevice.ACTION_DISCOVERY_STARTEDBluetoothDevice.ACTION_DISCOVERY_FINISHED 并进行相应处理。

注意:不要忘记在 list 中注册广播接收器并包含必要的权限。

关于java - 是否可以仅显示已配对、开启且在范围内的蓝牙设备的 Activity 列表,而不是显示所有先前配对的设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38794057/

相关文章:

java - Hibernate 无法在具有多个数据源的 Spring 项目中实例化 id 生成器

java - 具有曼哈顿启发式的 A* 算法

java - 在 JTextFields 中从法语切换为阿拉伯语

java - 字符串只接受某些字符

java - Android:显示带有时间延迟的数组元素?

android - android 5.0中的布局对齐问题

Android:什么是 ProGuard,我什么时候需要使用它?

ios - Apple 的外部配件(蓝牙)仅适用于 MFI 设备?

java - Android编程将连续数据从类发送到 fragment

安卓蓝牙打印机