aak*_*024 2 java android bluetooth broadcastreceiver
我正在使用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());
}
}
};
Run Code Online (Sandbox Code Playgroud)
知道是什么原因造成的吗?我该怎么做才能将设备仅添加到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());
}
}
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2235 次 |
| 最近记录: |