建网站非要做外链吗,wordpress 搬瓦工,温州,企业网页模板图片前言
在上一篇文章《OpenHarmony 特有挑战#xff1a;如何让 Flutter 应用支持分布式软总线》中#xff0c;我们从架构层面探讨了集成思路。本文将更进一步——手把手带你完成一个完整的 Flutter 应用#xff0c;实现在 OpenHarmony 设备间通过分布式软总线发送和接收消息。…前言在上一篇文章《OpenHarmony 特有挑战如何让 Flutter 应用支持分布式软总线》中我们从架构层面探讨了集成思路。本文将更进一步——手把手带你完成一个完整的 Flutter 应用实现在 OpenHarmony 设备间通过分布式软总线发送和接收消息。我们将构建一个“跨设备聊天小助手”支持两台 OpenHarmony 设备如手机与平板自动发现彼此并实时互发文本消息。所有代码均可运行于 OpenHarmony 4.0 环境并基于社区维护的 OpenHarmony Flutter Engine。一、环境准备1. 开发工具DevEco Studio 4.1OpenHarmony SDK API Version 10对应 OHOS 4.0Flutter SDK需使用 OpenHarmony 定制版2. 项目依赖确保oh-package.json5中包含{devDependencies:{ohos/flutter_embedding:1.0.0}}3. 权限配置module.json5{module:{requestPermissions:[{name:ohos.permission.DISTRIBUTED_DATASYNC},{name:ohos.permission.GET_DISTRIBUTED_DEVICE_INFO},{name:ohos.permission.ACCESS_BLUETOOTH},{name:ohos.permission.DISCOVER_BLUETOOTH}]}}二、原生侧封装分布式软总线服务ArkTS我们将创建一个完整的DSoftBusService.ets支持设备发现、会话建立与消息收发。文件路径entry/src/main/ets/services/DSoftBusService.ets// DSoftBusService.etsimportdeviceManagerfromohos.distributedHardware.deviceManager;import{BusinessType,DeviceInfo,DeviceStateChangeType}fromohos.distributedHardware.deviceManager;importsessionfromohos.net.session;classDSoftBusService{privatedm:deviceManager.DeviceManager|nullnull;privatesessionId:number-1;privatepeerDeviceId:string;privateeventCallback:((msg:string)void)|nullnull;// 初始化设备管理器asyncinit():Promiseboolean{try{this.dmdeviceManager.createDeviceManager(com.example.flutterdsoftbus);this.registerDeviceStateListener();returntrue;}catch(err){console.error([DSoftBus] init failed:,err);returnfalse;}}// 注册设备状态监听privateregisterDeviceStateListener():void{if(!this.dm)return;this.dm.on(deviceStateChange,(data){if(data.typeDeviceStateChangeType.ONLINE){console.info([DSoftBus] Device online:${data.deviceId});this.peerDeviceIddata.deviceId;this.createSession();}elseif(data.typeDeviceStateChangeType.OFFLINE){console.info([DSoftBus] Device offline:${data.deviceId});this.sessionId-1;}});}// 创建会话用于点对点通信privatecreateSession():void{constconfig:session.SessionConfig{peerDevId:this.peerDeviceId,groupId:,// 可选组IDsessionMode:session.SessionMode.SESSION_MODE_P2P,protocol:chat};session.createSession(config).then((id:number){this.sessionIdid;console.info([DSoftBus] Session created:${id});this.registerSessionListener(id);}).catch((err){console.error([DSoftBus] createSession failed:,err);});}// 注册会话消息监听privateregisterSessionListener(sessionId:number):void{session.on(sessionDataReceived,(data){if(data.sessionIdsessionId){constmsgString.fromCharCode.apply(null,newUint8Array(data.data));console.info([DSoftBus] Received:${msg});if(this.eventCallback){this.eventCallback(msg);}}});session.on(sessionClosed,(data){if(data.sessionIdsessionId){console.info([DSoftBus] Session closed);this.sessionId-1;}});}// 获取已发现的可信设备列表getTrustedDevices():string[]{if(!this.dm)return[];try{constdevices:ArrayDeviceInfothis.dm.getTrustedDeviceListSync();returndevices.map(dd.deviceId);}catch(err){console.error([DSoftBus] getTrustedDevices error:,err);return[];}}// 发送消息sendMessage(message:string):boolean{if(this.sessionId-1){console.warn([DSoftBus] No active session);returnfalse;}constencodernewTextEncoder();constdataencoder.encode(message);session.sendData(this.sessionId,data.buffer).then((){console.info([DSoftBus] Message sent);}).catch((err){console.error([DSoftBus] send failed:,err);});returntrue;}// 设置 Dart 层回调用于 EventChannelsetOnMessageReceived(callback:(msg:string)void):void{this.eventCallbackcallback;}}constdSoftBusServicenewDSoftBusService();exportdefaultdSoftBusService;三、桥接层MethodChannel EventChannel创建SoftBusPlugin.ets// SoftBusPlugin.etsimportdSoftBusServicefrom./services/DSoftBusService;import{MethodChannel,EventChannel}fromflutter/engine;constMETHOD_CHANNELcom.example.flutter/dsoftbus/method;constEVENT_CHANNELcom.example.flutter/dsoftbus/event;exportclassSoftBusPlugin{privateeventSink:anynull;init(){// MethodChannel用于主动调用constmethodChannelnewMethodChannel(METHOD_CHANNEL);methodChannel.setMethodCallHandler(this.handleMethodCall.bind(this));// EventChannel用于被动接收消息consteventChannelnewEventChannel(EVENT_CHANNEL);eventChannel.setStreamHandler({onListen:(arguments,sink){this.eventSinksink;dSoftBusService.setOnMessageReceived((msg){if(this.eventSink){this.eventSink.success(msg);}});},onCancel:(){this.eventSinknull;}});}privateasynchandleMethodCall(call:any):Promiseany{switch(call.method){caseinitSoftBus:constsuccessawaitdSoftBusService.init();return{success};casegetDeviceList:constdevicesdSoftBusService.getTrustedDevices();return{devices};casesendMessage:const{message}call.arguments;constsentdSoftBusService.sendMessage(message);return{success:sent};default:thrownewError(Unknown method: call.method);}}}在MainPage.ets中初始化插件// MainPage.etsimport{SoftBusPlugin}from./SoftBusPlugin;Entry Component struct MainPage{aboutToAppear(){newSoftBusPlugin().init();}build(){// FlutterView 占位Column(){Text(Flutter DSoftBus Demo)}}}四、Dart 侧Flutter 应用逻辑1. 定义通道// lib/softbus/softbus_channel.dartimportpackage:flutter/services.dart;classSoftBusChannel{staticconstMethodChannel _methodChannelMethodChannel(com.example.flutter/dsoftbus/method);staticconstEventChannel _eventChannelEventChannel(com.example.flutter/dsoftbus/event);// 初始化软总线staticFutureboolinit()async{finalresultawait_methodChannel.invokeMethod(initSoftBus);returnresult[success]true;}// 获取设备列表staticFutureListStringgetDeviceList()async{finalresultawait_methodChannel.invokeMethod(getDeviceList);returnListString.from(result[devices]??[]);}// 发送消息staticFutureboolsendMessage(String msg)async{finalresultawait_methodChannel.invokeMethod(sendMessage,{message:msg});returnresult[success]true;}// 监听接收消息staticStreamStringgetonMessageReceived_eventChannel.receiveBroadcastStream().map((event)eventasString);}2. 聊天界面简化版// lib/main.dartimportpackage:flutter/material.dart;importsoftbus/softbus_channel.dart;voidmain()async{WidgetsFlutterBinding.ensureInitialized();awaitSoftBusChannel.init();runApp(constMyApp());}classMyAppextendsStatelessWidget{constMyApp({super.key});overrideWidgetbuild(BuildContext context){returnMaterialApp(home:ChatPage(),);}}classChatPageextendsStatefulWidget{override_ChatPageStatecreateState()_ChatPageState();}class_ChatPageStateextendsStateChatPage{finalListString_messages[];finalTextEditingController _controllerTextEditingController();overridevoidinitState(){super.initState();// 监听来自其他设备的消息SoftBusChannel.onMessageReceived.listen((msg){setState((){_messages.add(Peer: $msg);});});}void_sendMessage(){finaltext_controller.text.trim();if(text.isEmpty)return;SoftBusChannel.sendMessage(text);setState((){_messages.add(Me: $text);_controller.clear();});}overrideWidgetbuild(BuildContext context){returnScaffold(appBar:AppBar(title:Text(DSoftBus Chat)),body:Column(children:[Expanded(child:ListView.builder(itemCount:_messages.length,itemBuilder:(ctx,i)ListTile(title:Text(_messages[i])),),),Padding(padding:EdgeInsets.all(8),child:Row(children:[Expanded(child:TextField(controller:_controller,decoration:InputDecoration(hintText:Type a message...),),),IconButton(onPressed:_sendMessage,icon:Icon(Icons.send))],),)],),);}}五、部署与测试在两台 OpenHarmony 设备上安装同一应用确保设备处于同一局域网且已登录同一华为账号或完成设备信任配对打开应用稍等几秒设备应自动发现彼此在任一设备输入消息并发送另一设备将实时收到。 提示若未发现设备请检查“设置 安全与隐私 更多安全设置 设备互联”是否开启。六、总结本文通过一个完整的跨设备聊天案例系统地展示了如何在 Flutter 应用中深度集成 OpenHarmony 分布式软总线。这个案例不仅验证了技术可行性也为开发者提供了一个可复用的参考实现。关键点包括分布式会话管理详细演示了如何使用session模块建立 P2P 会话包含会话发现、连接建立和会话管理的完整流程示例中实现了设备自动发现和手动选择两种连接方式跨平台通信机制通过MethodChannel实现 Flutter 到原生平台的单向调用利用EventChannel建立原生到 Flutter 的事件推送通道设计了一套完整的消息编码/解码方案处理跨平台数据交换架构分层设计原生侧(Java/Kotlin)封装核心业务逻辑和分布式能力Dart 侧专注于 UI 渲染和用户交互逻辑通过清晰的接口定义实现关注点分离虽然目前的技术方案仍存在一些局限性需要手动编写大量桥接代码性能优化空间较大错误处理机制有待完善但随着 OpenHarmony 生态的持续发展我们预期未来可能出现标准化的 Flutter 插件提供开箱即用的分布式能力官方可能会推出更高效的跨平台通信方案开发工具链将逐步完善显著降低集成难度这个案例不仅适用于即时通讯场景其技术方案也可扩展到跨设备文件共享多屏协同应用分布式计算任务分发IoT 设备联动控制开发者可根据实际需求在此基础架构上进行扩展和优化。欢迎大家加入开源鸿蒙跨平台开发者社区一起共建开源鸿蒙跨平台生态。