首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的android应用程序多次检测到相同的蓝牙设备

我的android应用程序多次检测到相同的蓝牙设备
EN

Stack Overflow用户
提问于 2012-07-31 23:00:41
回答 1查看 2.7K关注 0票数 5

我正在使用安卓开发者网站上的代码来检测范围内的蓝牙设备,并将它们添加到ArrayAdapter中。问题是,每个设备都会被添加到ArrayAdapter中5-6次。现在,我只使用这里的代码:http://developer.android.com/guide/topics/connectivity/bluetooth.html#DiscoveringDevices

这就是我所拥有的:

代码语言:javascript
复制
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次?

EN

回答 1

Stack Overflow用户

发布于 2012-07-31 23:08:31

我不确定这是一个bug还是什么,但我在我的一些设备上也经历过这种情况。要解决此问题,只需在List中添加一次找到的设备,并进行一些检查。如下所示:

代码语言:javascript
复制
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());
                }
            }
        }
    };
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11743036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档