我试图获取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;
}
这可能与扫描蓝牙设备相关的发现时间有关,但我想每发现一次我可以将它添加到列表中吗? 有没有人遇到类似的东西或有可能的解决方案? 非常感谢!
答案 0 :(得分:1)
看起来它可能与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);
在Receiver内部,但无法保证UI线程已准备好处理响应。
我从http://android-developers.blogspot.com/2009/05/painless-threading.html
开始