开发者

Bluetooth added to the ListView twice instead once

开发者 https://www.devze.com 2023-03-09 08:54 出处:网络
I\'m searching through available Bluetooth devices in range. For some reason, each found device is added to the ListView twice, when it should only be shown once.

I'm searching through available Bluetooth devices in range. For some reason, each found device is added to the ListView twice, when it should only be shown once.

Does anyone have any idea what I am doing wrong here? Code included below.

When discovery finds a device

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();
  开发者_JAVA技巧    mNewDevicesArrayAdapter.add(noDevices);
   }
}


In your code you use the equals operation. that's why it adds the two times. one in already paired device list. And the same items are added again int the newly invented list. Try this code.

// 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);
            }
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消