我复制并编辑了这段代码,以便通过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();
}
}
答案 0 :(得分:0)
代码尝试存储字符串" Paulo"进入AltBeacon Id2字段。问题是ASCII编码对每个字符使用一个字节,而Id2字段只有两个字节长。因此,该字段只有两个字符的空间。这就是为什么你只看到" Pa"。