我正在为 android 编写 Eddystone-url BLE 广告商。但是,我在正确编码 url 时遇到问题。根据规范(https://github.com/google/eddystone/tree/master/eddystone-url),方案前缀(例如http://www .)可以设置为单个字节(例如 0x00)。扩展时也应该发生同样的情况(例如 .com/ = 0x00)。有不同前缀和扩展的完整列表。
当前缀起作用时,扩展的行为很奇怪。
如果我输入:
url = "http://www.orf.at/"
BLE 扫描仪准确检索此 url。
如果我输入:
url = "http://www.orf.at"
最后没有“/”,BLE扫描仪告诉我添加了一个“.com”,如下所示:
"http://www.orf.at.com"
如果我输入:
url = "http://www.orf.at/test"
检索到的 url 看起来又像原来的了。
如何使用扩展编码?或者我该如何禁用它?这似乎非常不可靠。
我的相应代码:
private AdvertiseData buildEddystoneURLData(String url) throws UnsupportedEncodingException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
//frame type
os.write((byte) 0x10);
//TX Power
os.write((byte) 0xB5);
//URL scheme code
/*
0 0x00 http://www.
1 0x01 https://www.
2 0x02 http://
3 0x03 https://
*/
if(url.startsWith("http://www.")){
os.write((byte) 0x00);
url = url.substring(11,url.length());
log("starts with http://www.");
log("cutting to: "+url);
}else if(url.startsWith("https://www.")){
os.write((byte) 0x01);
url = url.substring(12,url.length());
log("starts with https://www.");
log("cutting to: "+url);
}
else if(url.startsWith("http://")){
os.write((byte) 0x02);
url = url.substring(7,url.length());
log("starts with http://");
log("cutting to: "+url);
}
else if(url.startsWith("https://")){
os.write((byte) 0x03);
url = url.substring(8,url.length());
log("starts with https://");
log("cutting to: "+url);
}
byte [] advertiseBytes = string2byte(url);
//0-17: url
for (Byte bt: advertiseBytes) {
os.write(bt);
}
byte[] serviceData = os.toByteArray();
ParcelUuid SERVICE_UUID = ParcelUuid.fromString("0000FEAA-0000-1000-8000-00805F9B34FB");
AdvertiseData.Builder builder = new AdvertiseData.Builder();
if(serviceData!=null) {
builder.addServiceData(SERVICE_UUID, serviceData)
.addServiceUuid(SERVICE_UUID)
.setIncludeTxPowerLevel(false)
.setIncludeDeviceName(false); //don't include device name - it does not work
return builder.build();
}
else
return null;
}
更新 字符串 2 字节:
private byte[] string2byte(String st) throws UnsupportedEncodingException {
return st.getBytes("UTF-8");
}
并在 logcat 中打印字节显示:对于“ http://www.orf.at/ ”:
starts with http://www.
cutting to: orf.at/
getServiceData at: 0000feaa-0000-1000-8000-00805f9b34fb
byte: 16
byte: -75
byte: 0
byte: 111
byte: 114
byte: 102
byte: 46
byte: 97
byte: 116
byte: 47
getServiceData as String: ���orf.at/
这适用于:“ http://www.orf.at ”:
starts with http://www.
cutting to: orf.at
getServiceData at: 0000feaa-0000-1000-8000-00805f9b34fb
byte: 16
byte: -75
byte: 0
byte: 111
byte: 114
byte: 102
byte: 46
byte: 97
byte: 116
getServiceData as String: ���orf.at