我目前正在开发一个 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_STARTED
和 BluetoothDevice.ACTION_DISCOVERY_FINISHED
并进行相应处理。
注意:不要忘记在 list 中注册广播接收器并包含必要的权限。
关于java - 是否可以仅显示已配对、开启且在范围内的蓝牙设备的 Activity 列表,而不是显示所有先前配对的设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38794057/