gpt4 book ai didi

android - 如何在android中保存可发现的蓝牙设备列表?

转载 作者:行者123 更新时间:2023-11-29 01:55:57 24 4
gpt4 key购买 nike

我正在尝试获取 android 中可发现的蓝牙设备的列表。我可以获得设备并使用 ArrayAdapter 填充设备的 ListView。我的问题是,如何将它们保存到列表中以便我可以将此信息用于其他功能?我试过查看 android 开发者网站,它只有 ListView 的教程。我还寻找了其他教程或解释,但似乎得到了错误的信息。

我的代码是:

protected List<String> doInBackground(Void... arg0) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();

// Create a BroadcastReceiver for ACTION_FOUND
final List<String> discoverableDevicesList = new ArrayList<String>();

final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
// Add the name and address to an array adapter to show in a ListView
System.out.println(device.getName());
discoverableDevicesList.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

return discoverableDevicesList;

这可能与扫描蓝牙设备相关的发现时间有关,但我认为当每个设备被发现时我可以将它添加到列表中吗?有没有人遇到类似的事情或有可能的解决方案?非常感谢!

最佳答案

看起来它可能与 UI 线程有关。您是否尝试关闭 AsyncTask 以在发现蓝牙设备时填充 ListView?我看到你这样做了:

           // Add the name and address to an array adapter to show in a ListView
System.out.println(device.getName());
discoverableDevicesList.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);

在接收器内部,但无法保证 UI 线程甚至已准备好处理响应。

我从 http://android-developers.blogspot.com/2009/05/painless-threading.html 得到这个

关于android - 如何在android中保存可发现的蓝牙设备列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15120502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com