我怎样才能获得的全部Android连接的蓝牙设备的列表,无论轮廓的?
另外,我看到,你可以得到所有连接的设备用于通过BluetoothManager.getConnectedDevices特定的配置文件。
我想我可以看到哪些设备通过ACTION_ACL_CONNECTED / ACTION_ACL_DISCONNECTED ...用于连接/断开连接听了似乎很容易出错。
但我不知道是否有更简单的方法来获得所有连接的蓝牙设备的列表。
要查看完整列表,这是一个2步操作:
要获得一个列表,迭代,当前配对的设备:
Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice d: pairedDevices) {
String deviceName = d.getName();
String macAddress = d.getAddress();
Log.i(LOGTAG, "paired device: " + deviceName + " at " + macAddress);
// do what you need/want this these list items
}
}
发现是多一点点复杂的操作。要做到这一点,你需要告诉BluetoothAdapter开始扫描/发现。当它发现的东西,它发出的是你需要接收与广播接收器意图。
首先,我们将设置接收器:
private void setupBluetoothReceiver()
{
BroadcastRecevier btReceiver = new BroadcastReciver() {
@Override
public void onReceive(Context context, Intent intent) {
handleBtEvent(context, intent);
}
};
IntentFilter eventFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
// this is not strictly necessary, but you may wish
// to know when the discovery cycle is done as well
eventFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
myContext.registerReceiver(btReceiver, eventFilter);
}
private void handleBtEvent(Context context, Intent intent)
{
String action = intent.getAction();
Log.d(LOGTAG, "action received: " + action);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i(LOGTAG, "found device: " + device.getName());
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.d(LOGTAG, "discovery complete");
}
}
现在,所有剩下的就是告诉BluetoothAdapter开始扫描:
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
// if already scanning ... cancel
if (btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery();
}
btAdapter.startDiscovery();