2012-07-31 87 views
2

我使用Android開發人員網站的代碼來檢測範圍內的藍牙設備,並將它們添加到ArrayAdapter。問題是,每個設備被添加到ArrayAdapter 5-6次。現在,我只是使用的代碼從這裏:http://developer.android.com/guide/topics/connectivity/bluetooth.html#DiscoveringDevices我的Android應用程序多次檢測到相同的藍牙設備

這是我有:

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次?

回答

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 2012-07-31 15:25:22

+1

我通常在三星設備上有這個問題。我認爲這是一個優雅的解決方案,否則你打算如何解決這個問題? – waqaslam 2012-07-31 15:36:03

+0

我打算建議檢查它是否已經在列表中,但這似乎更好。 – Shark 2012-07-31 16:31:11

相關問題