我正在使用Android开发者网站上的代码来检测范围内的蓝牙设备,并将它们添加到ArrayAdapter。问题是,每个设备都被添加到ArrayAdapter 5-6次。现在,我只是使用此处的代码:http://developer.android.com/guide/topics/connectivity/bluetooth.html#DiscoveringDevices
这就是我所拥有的:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
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);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
知道是什么导致了这个吗?我怎样才能将设备只添加一次到ArrayAdapter而不是5次?
答案 0 :(得分:4)
我不确定它是一个错误还是什么,但我在我的某些设备上也遇到了这个问题。要解决此问题,请通过一些检查在List
中添加找到的设备一次。见下文:
private List<BluetoothDevice> tmpBtChecker = new ArrayList<BluetoothDevice>();
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery starts
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
//clearing any existing list data
tmpBtChecker.clear();
}
// 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);
// Add the name and address to an array adapter
if(!tmpBtChecker.contains(device)){
tmpBtChecker.add(device);
mArrayAdapter.add(device.getName()+"\n"+device.getAddress());
}
}
}
};