我的安卓应用程序检测到同一蓝牙设备多次

6
我正在使用来自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中,而不是五次?
1个回答

6

我不确定这是否是一个错误,但我在我的一些设备上也遇到了这个问题。为了解决这个问题,只需将找到的设备添加到 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());
                }
            }
        }
    };

1
我之前确实遇到过这个问题。但是有人告诉我这不是一个“优雅”的解决方案。你认为这可能只是一个特定设备的错误吗?我希望我有另一个设备来测试一下... - aakbari1024
1
我通常在三星设备上遇到这个问题。我认为这是一个优雅的解决方案,否则你打算如何解决呢? - waqaslam
我本来想建议检查它是否已经在列表中,但这个方法似乎更好。 - Shark
你可以使用 HashSet 来使这个过程更加高效。List.Contains 的时间复杂度是 (O)n,而 HashSet 的时间复杂度是 (O)1。也就是说,HashSet 更加高效,因为它不需要遍历整个列表。private Set<BluetoothDevice> foundDevices = new HashSet<>(); .... if(foundDevices.contains(device)){ return; } foundDevices.add(device); - serenskye
这并没有解决这个 bug,只是一个权宜之计。这个答案并没有帮助。 - Reaz Murshed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接