蓝牙添加到ListView两次而不是一次

时间:2011-05-28 05:18:19

标签: android android-listview android-bluetooth

我正在搜索范围内的可用Bluetooth devices。出于某种原因,每个找到的设备都会添加到ListView 两次,而只能显示一次

有谁知道我在这里做错了什么?代码包括在下面。

  

当发现找到设备时

if (BluetoothDevice.ACTION_FOUND.equals(action)) {
   // Get the BluetoothDevice object from the Intent
   BluetoothDevice device;
   device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

   // If it's already paired, skip it, because it's been listed already
   if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
      Log.v("test", "test");

      mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
   }

} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
   // When discovery is finished, change the Activity title

   setProgressBarIndeterminateVisibility(false);
   setTitle(R.string.select_device);

   if (mNewDevicesArrayAdapter.getCount() == 0) {
      String noDevices = getResources().getText(R.string.none_found).toString();
      mNewDevicesArrayAdapter.add(noDevices);
   }
}

1 个答案:

答案 0 :(得分:4)

在您的代码中使用equals操作。这就是为什么它会增加两次。一个已经配对的设备列表。并且在新发明的列表中再次添加相同的项目。试试这段代码。

// 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);
            // If it's already paired, skip it, because it's been listed already
            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        // When discovery is finished, change the Activity title
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            setProgressBarIndeterminateVisibility(false);
            setTitle(R.string.select_device);
            if (mNewDevicesArrayAdapter.getCount() == 0) {
                String noDevices = getResources().getText(R.string.none_found).toString();
                mNewDevicesArrayAdapter.add(noDevices);
            }
        }