2012-07-31 2 views
2

Android 개발자 웹 사이트의 코드를 사용하여 범위 내의 Bluetooth 장치를 감지하고이를 ArrayAdapter에 추가하고 있습니다. 문제는 각 장치가 ArrayAdapter에 5-6 번 추가된다는 것입니다. 지금, 나는 여기에서 코드를 사용하고이 원인을 무엇내 안드로이드 앱이 동일한 블루투스 장치를 여러 번 감지했습니다.

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()); 
     } 
    } 
}; 

어떤 생각을 : http://developer.android.com/guide/topics/connectivity/bluetooth.html#DiscoveringDevices 여기

내가 가진 무엇인가? 그리고 장치를 ArrayAdapter에 5 회가 아닌 한 번만 추가하도록하려면 어떻게해야합니까?

답변

4

버그인지 또는 일부 기기에서이 점을 경험했는지 확실하지 않습니다. 이 문제를 해결하려면 확인 된 기기를 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

+0

나는 이미 목록에 있는지 확인해 보려고했으나 이것이 더 좋아 보인다. – Shark

관련 문제