由以上分析结论可知,要打印ArrayBuffer需要解码成对应格式才能打印:
可以使用TextDecoder工具类将ArrayBuffer解码成字符串之后打印。
示例代码如下:
import { emitter } from '@kit.BasicServicesKit'; import { util } from '@kit.ArkTS'; @Entry @Component struct EmitterParam { private arrayBuffer = new ArrayBuffer(20); private str: string = 'Hello ArrayBuffer!'; event: emitter.InnerEvent = { eventId: 1 }; // 自定义回调方法 private callback = (eventData: emitter.EventData): void => { let arrayBuffer: ArrayBuffer = eventData.data!['buffer']; let textDecoder = new util.TextDecoder(); let text = textDecoder.decodeToString(new Uint8Array(arrayBuffer)); this.getUIContext().getPromptAction().showToast({ message: `收到数据:${text}` }); // 使用分段打印到控制台 printInChunks(text); }; aboutToAppear(): void { let bufView = new Uint8Array(this.arrayBuffer); for (let i = 0, strLen = this.str.length; i < strLen; i++) { bufView[i] = this.str.charCodeAt(i); } this.arrayBuffer = bufView.buffer as ArrayBuffer; emitter.on(this.event, this.callback); // 开启监听 } build() { RelativeContainer() { Button(`发送数据: ${this.str}`).width('100%').height(100) .onClick(() => { let eventData: emitter.EventData = { data: { buffer: this.arrayBuffer } }; emitter.emit(this.event, eventData); }) } .height('100%') .width('100%') } } /* * 分段打印日志 * */ function printInChunks(str: string, chunkSize = 1000) { for (let i = 0; i < str.length; i += chunkSize) { console.log(str.substring(i, i + chunkSize)); } }