我想在我的
Android代码中只扫描具有特定UUID的BLE信标.即使我可以为特定的MAC地址添加过滤器,我也无法使用UUID.永远不会调用onScanResult函数.为什么会这样?我正在使用API 21,我没有收到任何项目错误.
final String tagUUID = "01122334-4556-6778-899a-abbccddeeff0"; //does not work ScanFilter filter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(UUID.fromString(tagUUID))).build(); //works ScanFilter filter = new ScanFilter.Builder().setDeviceAddress(tagMAC).build();
解决方法
我是上面提到的博客文章的作者.以下是解决Android 21问题的方法.
// Empty data byte[] manData = new byte[]{0,0}; // Data Mask byte[] mask = new byte[]{0,1,0}; // Copy UUID into data array and remove all "-" System.arraycopy(hexStringToByteArray("YOUR_UUID_TO_FILTER".replace("-","")),manData,2,16); // Add data array to filters ScanFilter filter = new ScanFilter.Builder().setManufacturerData(76,mask).build()); public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i),16) << 4) + Character.digit(s.charAt(i+1),16)); } return data; }
这里的问题是你可以添加UUID过滤但不完全直截了当