android byte[] to String

做一个蓝牙的项目,现实的数据总是乱码,以下亲测有用:

//蓝牙部分
public void broadcastUpdate(final String action,
			final BluetoothGattCharacteristic characteristic)
	{
		final Intent intent = new Intent(action);
		final byte[] data = 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 for  read 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 byte[] to String)