如何将字符串传递给 Beacon alte
How to pass string to Beacon alte
我复制并编辑了这段代码,以便通过 ALTEBeacon 传递字符串,但我只能看到两个字符,例如 String name = "Paulo" 而我只能看到 "Pa"。我不懂为什么。我用了这个方法代码。
if (Build.VERSION.SDK_INT >= 21) {
// Call some material design APIs here
device.setText("supported");
// new code
String stringToTransmit = "Paulo";
byte[] stringToTransmitAsAsciiBytes = stringToTransmit.getBytes(StandardCharsets.US_ASCII);
Beacon beacon = new Beacon.Builder()
.setId1(MY_MATCHING_IDENTIFIER.toString())
.setId2(Identifier.fromBytes(stringToTransmitAsAsciiBytes, 0, 5, false).toString())
.setId3("2")
.setManufacturer(0x0118)
.setTxPower(-59)
.setDataFields(Arrays.asList(new Long[] {255l}))
.setBluetoothName(Identifier.fromBytes(stringToTransmitAsAsciiBytes, 0, 5, false).toString())
.build();
BeaconParser beaconParser = new BeaconParser()
.setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
BeaconTransmitter beaconTransmitter = new BeaconTransmitter(getActivity(), beaconParser);
beaconTransmitter.startAdvertising(beacon);
}
我用这段代码恢复了
for (Beacon b:beacons) {
//new
String receivedString = null;
// byte[] bytes = b.getId2().toByteArray();
byte[] bytes = b.getId2().toByteArray();
receivedString = null;
try {
receivedString = new String(bytes, 0, bytes.length, "ASCII");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
代码尝试将字符串 "Paulo" 存储到 AltBeacon Id2 字段中。问题在于 ASCII 编码对每个字符使用一个字节,而 Id2 字段只有两个字节长。因此,该字段只能容纳两个字符。这就是您只看到 "Pa" 的原因。
我复制并编辑了这段代码,以便通过 ALTEBeacon 传递字符串,但我只能看到两个字符,例如 String name = "Paulo" 而我只能看到 "Pa"。我不懂为什么。我用了这个方法代码。
if (Build.VERSION.SDK_INT >= 21) {
// Call some material design APIs here
device.setText("supported");
// new code
String stringToTransmit = "Paulo";
byte[] stringToTransmitAsAsciiBytes = stringToTransmit.getBytes(StandardCharsets.US_ASCII);
Beacon beacon = new Beacon.Builder()
.setId1(MY_MATCHING_IDENTIFIER.toString())
.setId2(Identifier.fromBytes(stringToTransmitAsAsciiBytes, 0, 5, false).toString())
.setId3("2")
.setManufacturer(0x0118)
.setTxPower(-59)
.setDataFields(Arrays.asList(new Long[] {255l}))
.setBluetoothName(Identifier.fromBytes(stringToTransmitAsAsciiBytes, 0, 5, false).toString())
.build();
BeaconParser beaconParser = new BeaconParser()
.setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
BeaconTransmitter beaconTransmitter = new BeaconTransmitter(getActivity(), beaconParser);
beaconTransmitter.startAdvertising(beacon);
}
我用这段代码恢复了
for (Beacon b:beacons) {
//new
String receivedString = null;
// byte[] bytes = b.getId2().toByteArray();
byte[] bytes = b.getId2().toByteArray();
receivedString = null;
try {
receivedString = new String(bytes, 0, bytes.length, "ASCII");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
代码尝试将字符串 "Paulo" 存储到 AltBeacon Id2 字段中。问题在于 ASCII 编码对每个字符使用一个字节,而 Id2 字段只有两个字节长。因此,该字段只能容纳两个字符。这就是您只看到 "Pa" 的原因。