我正在创建一个通过蓝牙进行通信的简单应用程序。我已经创建了一个简单的活动,列出了附近打开蓝牙的设备但不幸的是我无法弄清楚我怎么能检测到某些设备何时从蓝牙网络中消失(bt被关闭)以便我可以从中删除该项目清单。
这是我写的将附近的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意图。也许可以使用ACTION_DISCOVERY_FINISHED,但是如何使用?
提前致谢!
答案 0 :(得分: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);
}
不可用的设备不在列表中。