如何用HarmonyOS鸿蒙Next的socket.sppWrite向蓝牙模块发送字符串

如何用HarmonyOS鸿蒙Next的socket.sppWrite向蓝牙模块发送字符串

这个函数是只能发送number类型的数据吗,如果想要发送字符串的话该怎么操作,在一篇博客看到转字符也没用

// 字符串转成字节流
function stringToUint8Array(str: string) {
  console.info('字符串转成字节流:' + new Uint8Array(buffer.from(str, 'utf-8').buffer);
  return new Uint8Array(buffer.from(str, 'utf-8').buffer);
}

![cke_832.png](data-originheight=“759” data-originwidth=“1032” src="https://alliance-communityfile-drcn.dbankcdn.com/FileServer/getFile/cmtybbs/857/978/216/0010086000857978216.20250503001302.77782724512845559224605050752737:50001231000000:2800:8531BC2BFD0CD004AFF71420AC42C086C5AABC2739C93DEB1C8EFFD48E63F714.png)

![cke_1550.png](data-originheight=“637” data-originwidth=“1757” src="https://alliance-communityfile-drcn.dbankcdn.com/FileServer/getFile/cmtybbs/857/978/216/0010086000857978216.20250503001325.51211893906213963959303938437885:50001231000000:2800:182A32030824D93B6F6EE56115EDA23608E01033D8092FE620F9B9907A7F6C4C.png)


更多关于如何用HarmonyOS鸿蒙Next的socket.sppWrite向蓝牙模块发送字符串的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

伙伴您好,此方法需要传入ArrayBuffer,您可以参考以下代码将string转为ArrayBuffer:

strToArrayBuffer(str: string) {
  let buf = new ArrayBuffer(str.length * 2);
  let bufView = new Uint8Array(buf);
  for (let i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return bufView.buffer;
}

Uint8Array是8位无符号整型数组,里面的元素只能为无符号整型,不能为string。您可以如上代码所述,通过Uint8Array对象的buffer,获取其所关联的ArrayBuffer。

更多关于如何用HarmonyOS鸿蒙Next的socket.sppWrite向蓝牙模块发送字符串的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,使用socket.sppWrite向蓝牙模块发送字符串的步骤如下:

  1. 建立连接:首先通过BluetoothSocket建立与蓝牙设备的连接。
  2. 获取输出流:使用BluetoothSocketgetOutputStream()方法获取输出流。
  3. 发送数据:调用socket.sppWrite()方法,将字符串转换为字节数组后发送。

示例代码:

BluetoothSocket socket = ...; // 已建立的蓝牙连接
String data = "Hello, Bluetooth!";
byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
socket.sppWrite(bytes, 0, bytes.length);

确保蓝牙模块已配对并连接,且权限已正确配置。

回到顶部