tel*_*lob 22 android bluetooth
由于我目前正在为Android安装一个小蓝牙库,我正试图获得我在周围发现的设备的所有服务uuids.
当我的广播接收器获得BluetoothDevice.ACTION_FOUND
意图时,我正在提取设备并致电:
device.fetchUuidsWithSdp();
Run Code Online (Sandbox Code Playgroud)
这将导致BluetoothDevice.ACTION_UUID
找到的每个设备的意图,并且我使用相同的接收器处理它们:
BluetoothDevice d = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
if(uuidExtra == null) {
Log.e(TAG, "UUID = null");
}
if(d != null && uuidExtra != null)
Log.d(TAG, d.getName() + ": " + uuidExtra.toString());
Run Code Online (Sandbox Code Playgroud)
问题是,这uuidExtra
总是如此null
.
我怎样才能获得周围设备的所有UUID?
编辑:
我正在使用Nexus 7.我尝试了在互联网上找到的代码,这也给了我一个NullPointerException:http://digitalhacksblog.blogspot.de/2012/05/android-example-bluetooth-discover-and.html
谢谢.
注意:此解决方案适用于
CLASSIC
蓝牙而不适用BLE
.对于BLE
检查如何发送特定制造商的数据在广告上的周侧
获取Uuids的问题在于您只有一个蓝牙适配器,我们不能使用适配器进行并行api调用.
正如埃迪指出的那样,等待BluetoothAdapter.ACTION_DISCOVERY_FINISHED
然后再打电话fetchUuidsWithSdp()
.
仍然无法保证所有设备都能获取uuids.除此之外,必须等待每个后续调用fetchuuidsWithSdp()
完成,然后为另一个设备调用此方法.
请参阅下面的代码 -
ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// discovery has finished, give a call to fetchUuidsWithSdp on first device in list.
if (!mDeviceList.isEmpty()) {
BluetoothDevice device = mDeviceList.remove(0);
boolean result = device.fetchUuidsWithSdp();
}
} else if (BluetoothDevice.ACTION_UUID.equals(action)) {
// This is when we can be assured that fetchUuidsWithSdp has completed.
// So get the uuids and call fetchUuidsWithSdp on another device in list
BluetoothDevice deviceExtra = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
System.out.println("DeviceExtra address - " + deviceExtra.getAddress());
if (uuidExtra != null) {
for (Parcelable p : uuidExtra) {
System.out.println("uuidExtra - " + p);
}
} else {
System.out.println("uuidExtra is still null");
}
if (!mDeviceList.isEmpty()) {
BluetoothDevice device = mDeviceList.remove(0);
boolean result = device.fetchUuidsWithSdp();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
更新:最新的Android版本(毫米及以上)将导致触发与每个设备的配对过程