2012-06-21 47 views
0

我正在创建一个简单的应用程序,它将通过蓝牙进行通信。我已经创建了一个简单的活动,列出附近的设备与蓝牙打开,但不幸的是,我不知道如何检测当某些设备从蓝牙网络中消失(bt被关闭),以便我可以从中删除该项目列表。当Android上的蓝牙设备消失时检测到

这是我的代码,我写信给附近的BT设备添加到ListView:

mNewDevicesArrayAdapter = new BluetoothDeviceArrayAdapter(this, 0, new ArrayList<BluetoothDevice>()); 

lvDiscovered = (ListView)findViewById(R.id.bt_dev_discovered_list); 
lvDiscovered.setAdapter(mNewDevicesArrayAdapter); 

... 

// The BroadcastReceiver that listens for discovered devices and 
// changes the title when discovery is finished 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      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); 
       } 
      // When discovery is finished, change the Activity title 
      } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
       // TODO show no devices found! 
      }    
     } 
    }; 

我发现的情况下不适用的行动意图,当设备被消失。也许可以使用ACTION_DISCOVERY_FINISHED,但是如何?

在此先感谢!

回答

0

我发现了一个简单的方法,从先前发现的列表中删除这些设备。

扩展我的代码上面我介绍了一个update list我在哪里存储新发现的设备。当出现ACTION_DISCOVERY_FINISHED时,我将使用此更新列表更新ListView

... 
private ArrayList<BluetoothDevice> btDevicesUpdateList; 
... 

// The BroadcastReceiver that listens for discovered devices and 
// changes the title when discovery is finished 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     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 
      // in the paired devices list 
      if (device.getBondState() != BluetoothDevice.BOND_BONDED) { 
       if(mNewDevicesArrayAdapter.getCount() == 0){ 
        // if the list is empty we add the device immediately to it 
        mNewDevicesArrayAdapter.add(device); 
       } 
       btDevicesUpdateList.add(device);      
      } 
     } 
     else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
      mNewDevicesArrayAdapter.setItems(btDevicesUpdateList); 
      btDevicesUpdateList.clear(); 
      mBtAdapter.startDiscovery(); 
     } 
    } 
} 

// BluetoothDeviceArrayAdapter.java 
public void setItems(ArrayList<BluetoothDevice> items){ 
    this.items.clear(); 
    this.items.addAll(items); 
} 

不可用的设备不在列表中。