HarmonyOS鸿蒙Next中传统蓝牙怎么通信呀,DataListenSocket如何使用,有没有大佬遇到

HarmonyOS鸿蒙Next中传统蓝牙怎么通信呀,DataListenSocket如何使用,有没有大佬遇到 执行到这里就跑不下去了

cke_456.png


更多关于HarmonyOS鸿蒙Next中传统蓝牙怎么通信呀,DataListenSocket如何使用,有没有大佬遇到的实战教程也可以访问 https://www.itying.com/category-93-b0.html

6 回复

楼主你好,如果代码执行报错,请上传完整log,提供api版本,OS版本和机型帮你进一步分析。

同时你也可以参考这个帖子2楼的回复进行尝试:https://developer.huawei.com/consumer/cn/forum/topic/0203860175904070215?fid=0101587865002800104

更多关于HarmonyOS鸿蒙Next中传统蓝牙怎么通信呀,DataListenSocket如何使用,有没有大佬遇到的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


首先很感谢。DataListenSocket反射获取不到dataListenInsecureRfcomm方法,其他几个也获取不到。都会报java.lang.NoSuchMethodException: ohos.bluetooth.DataListenSocket.dataListenInsecureRfcomm [class java.lang.String, class java.util.UUID]错误。通过获取getDeclaredMethods来看。有以下6个方法:

  • buildInsecureRfcommDataSocketByServiceRecord
  • buildRfcommDataSocketByServiceRecord
  • dataListenInsecureRfcommByServiceRecord
  • dataListenRfcommByServiceRecord
  • dataListenWithInsecureL2capChannel
  • dataListenWithL2capChannel

我的Api版本是6,真机机型是DBY-W09,Pad。

楼主你好,目前查阅资料DataListenSocket从API7开始开放使用,参考链接:https://developer.harmonyos.com/cn/docs/documentation/doc-references/datalistensocket-0000001172398174

在HarmonyOS鸿蒙Next中,传统蓝牙通信主要通过BluetoothHostBluetoothSocket实现。BluetoothHost用于管理蓝牙设备,BluetoothSocket用于建立连接并进行数据传输。

DataListenSocket是用于监听蓝牙连接的类。首先,通过BluetoothHost获取本地蓝牙适配器,然后使用listenUsingRfcommWithServiceRecord方法创建一个BluetoothServerSocket实例。接着,调用accept方法等待客户端连接,连接成功后返回一个BluetoothSocket实例。

BluetoothSocket实例中,可以通过getInputStreamgetOutputStream获取输入输出流,进行数据传输。数据传输完成后,调用close方法关闭连接。

以下是一个简单的代码示例:

import bluetooth from '@ohos.bluetooth';

let serverSocket: bluetooth.BluetoothServerSocket = bluetooth.BluetoothHost.listenUsingRfcommWithServiceRecord("MyService", "00001101-0000-1000-8000-00805F9B34FB");

serverSocket.accept().then((socket: bluetooth.BluetoothSocket) => {
    let inputStream = socket.getInputStream();
    let outputStream = socket.getOutputStream();

    // 读取数据
    let buffer = new ArrayBuffer(1024);
    inputStream.read(buffer).then((bytesRead: number) => {
        // 处理接收到的数据
    });

    // 发送数据
    let data = new Uint8Array([0x01, 0x02, 0x03]);
    outputStream.write(data).then(() => {
        // 数据发送成功
    });

    // 关闭连接
    socket.close();
}).catch((err: Error) => {
    // 处理错误
});

DataListenSocket的使用主要集中在监听连接和处理数据传输上。

在HarmonyOS鸿蒙Next中,传统蓝牙通信主要通过BluetoothHostDataListenSocket实现。首先使用BluetoothHost进行设备发现和配对,然后通过DataListenSocket监听传入的连接。使用时需确保权限配置正确,并处理连接状态和数据传输。具体代码示例可参考官方文档或社区分享的案例。

回到顶部