写点什么

【HarmonyOS 5】鸿蒙星闪 NearLink 详解

作者:GeorgeGcs
  • 2025-05-20
    上海
  • 本文字数:2952 字

    阅读完需:约 10 分钟

【HarmonyOS 5】鸿蒙星闪NearLink详解

【HarmonyOS 5】鸿蒙星闪 NearLink 详解

一、前言

鸿蒙星闪 NearLink Kit 是 HarmonyOS 提供的短距离通信服务,支持星闪设备间的连接、数据交互。例如,手机可作为中心设备与外围设备(如鼠标、手写笔、智能家电、车钥匙等)通过星闪进行连接。

二、NearLink Kit 的接入与使用:

点击跳转官方文档地址



鸿蒙星闪(NearLink)的基本接入代码示例,包含设备发现、连接和数据传输的核心流程:


// NearLink设备管理服务示例
import nearlink from '@ohos.nearlink';import nearlinkSle from '@ohos.nearlink.sle';import common from '@ohos.app.ability.common';
// 星闪服务管理类export class NearLinkManager { private context: common.UIAbilityContext | undefined; private deviceManager: nearlinkSle.SleDeviceManager | undefined; private connectedDeviceId: string | null = null; private dataChannel: nearlinkSle.SleDataChannel | undefined; constructor(context: common.UIAbilityContext) { this.context = context; } // 初始化星闪服务 async initNearLinkService() { try { // 检查并请求星闪权限 await this.checkAndRequestNearLinkPermission(); // 创建设备管理器实例 this.deviceManager = await nearlinkSle.getSleDeviceManager(this.context!); // 注册设备状态变化监听 this.registerDeviceStateListener(); console.info('NearLink service initialized successfully'); } catch (error) { console.error(`Failed to initialize NearLink service: ${error}`); throw error; } } // 检查并请求星闪权限 private async checkAndRequestNearLinkPermission() { // 权限检查逻辑 // ... } // 开始扫描附近的星闪设备 async startDiscovery() { if (!this.deviceManager) { throw new Error('Device manager not initialized'); } try { // 配置扫描参数 const discoveryConfig = { mode: nearlinkSle.SleDiscoveryMode.ACTIVE, duration: 30, // 扫描持续时间(秒) filter: { deviceTypes: [nearlinkSle.SleDeviceType.ALL] } }; // 注册设备发现回调 const callback = { onDeviceFound: (device: nearlinkSle.SleDevice) => { console.info(`Found device: ${device.deviceName}, type: ${device.deviceType}`); // 处理发现的设备,例如更新UI this.onDeviceDiscovered(device); }, onDiscoveryStateChanged: (state: number) => { console.info(`Discovery state changed: ${state}`); } }; // 开始扫描 await this.deviceManager.startDiscovery(discoveryConfig, callback); console.info('NearLink device discovery started'); } catch (error) { console.error(`Failed to start discovery: ${error}`); throw error; } } // 处理发现的设备 private onDeviceDiscovered(device: nearlinkSle.SleDevice) { // 这里可以添加设备过滤逻辑 // ... // 通知UI更新设备列表 // ... } // 连接到指定星闪设备 async connectToDevice(deviceId: string) { if (!this.deviceManager) { throw new Error('Device manager not initialized'); } try { // 创建连接参数 const connectParams = { timeout: 10000, // 连接超时时间(毫秒) connectionType: nearlinkSle.SleConnectionType.DATA_CHANNEL }; // 连接设备 const connectionResult = await this.deviceManager.connect(deviceId, connectParams); if (connectionResult.resultCode === 0) { this.connectedDeviceId = deviceId; this.dataChannel = connectionResult.dataChannel; console.info(`Connected to device: ${deviceId}`); // 注册数据接收回调 this.registerDataReceiveListener(); } else { console.error(`Failed to connect device, error code: ${connectionResult.resultCode}`); throw new Error(`Connection failed: ${connectionResult.resultCode}`); } } catch (error) { console.error(`Failed to connect device: ${error}`); throw error; } } // 注册数据接收监听器 private registerDataReceiveListener() { if (!this.dataChannel) return; this.dataChannel.on('dataReceived', (data: ArrayBuffer) => { // 处理接收到的数据 const decoder = new TextDecoder(); const message = decoder.decode(data); console.info(`Received data: ${message}`); // 通知UI有新数据到达 // ... }); } // 发送数据到已连接设备 async sendData(message: string) { if (!this.dataChannel) { throw new Error('Data channel not initialized'); } try { const encoder = new TextEncoder(); const data = encoder.encode(message).buffer; // 发送数据 await this.dataChannel.send(data); console.info(`Data sent successfully: ${message}`); } catch (error) { console.error(`Failed to send data: ${error}`); throw error; } } // 断开与设备的连接 async disconnect() { if (!this.deviceManager || !this.connectedDeviceId) return; try { await this.deviceManager.disconnect(this.connectedDeviceId); this.connectedDeviceId = null; this.dataChannel = undefined; console.info('Device disconnected'); } catch (error) { console.error(`Failed to disconnect device: ${error}`); throw error; } } // 注册设备状态变化监听 private registerDeviceStateListener() { if (!this.deviceManager) return; this.deviceManager.on('deviceStateChanged', (params) => { console.info(`Device state changed: ${JSON.stringify(params)}`); // 处理设备状态变化 // ... }); } // 释放资源 async release() { await this.disconnect(); if (this.deviceManager) { try { await this.deviceManager.release(); console.info('NearLink resources released'); } catch (error) { console.error(`Failed to release resources: ${error}`); } } }}
复制代码

三、鸿蒙星闪指标对比

以下是鸿蒙星闪、蓝牙和 NFC 在技术性能、应用场景、成本与生态系统等方面的区别表格:



发布于: 刚刚阅读数: 4
用户头像

GeorgeGcs

关注

路漫漫其修远兮,吾将上下而求索。 2024-12-24 加入

历经腾讯,宝马,研究所,金融。 待过私企,外企,央企。 深耕大应用开发领域十年。 OpenHarmony,HarmonyOS,Flutter,H5,Android,IOS。 目前任职鸿蒙应用架构师。 HarmonyOS官方认证创作先锋,华为开发专家HDE。

评论

发布
暂无评论
【HarmonyOS 5】鸿蒙星闪NearLink详解_GeorgeGcs_InfoQ写作社区