[英]My android app is detecting the same bluetooth device multiple times
我正在使用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次?
我不確定這是錯誤還是什么,但是我在某些設備上也經歷過。 要解決此問題,請在一次檢查中將找到的設備僅添加到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());
}
}
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.