android|android byte[] to String
【android|android byte[] to String】做一个蓝牙的项目,现实的数据总是乱码,以下亲测有用:
//蓝牙部分
public void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic)
{
final Intent intent = new Intent(action);
final byte[] data = https://www.it610.com/article/characteristic.getValue();
if (data != null && data.length> 0)
{
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
{
stringBuilder.append(String.format("%02X ", byteChar));
Log.i(TAG, "***broadcastUpdate: byteChar = " + byteChar);
}
}
String mString = byteArrayToStr(data);
intent.putExtra(EXTRA_DATA, mString);
System.out.println("broadcastUpdate forread data:"
+ new String(data));
sendBroadcast(intent);
}
//数据转换
public static String byteArrayToStr(byte[] byteArray) {
if (byteArray == null){
return null;
}
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[byteArray.length * 2];
for (int j = 0;
j < byteArray.length;
j++) {
int v = byteArray[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
推荐阅读
- android第三方框架(五)ButterKnife
- Android中的AES加密-下
- 带有Hilt的Android上的依赖注入
- android|android studio中ndk的使用
- Android事件传递源码分析
- RxJava|RxJava 在Android项目中的使用(一)
- Android7.0|Android7.0 第三方应用无法访问私有库
- 深入理解|深入理解 Android 9.0 Crash 机制(二)
- android防止连续点击的简单实现(kotlin)
- Android|Android install 多个设备时指定设备