openharmony Flutter-OH 通道测试Demo

📅 发布时间:2026/7/8 3:39:41 👁️ 浏览次数:
openharmony Flutter-OH 通道测试Demo
欢迎大家加入开源鸿蒙跨平台社区openharmonyFlutter 通道测试 Demo一、三种通道对比通道类型通信模式适用场景MethodChannel方法调用异步一次性请求响应EventChannel事件流Stream持续数据推送BasicMessageChannel基本消息双向简单消息传递二、Flutter 端实现1. 通道定义// MethodChannel - 方法调用staticconstMethodChannel_methodChannelMethodChannel(com.example.test1/method);// EventChannel - 事件流staticconstEventChannel_eventChannelEventChannel(com.example.test1/event);// BasicMessageChannel - 基本消息staticconstBasicMessageChannelString_messageChannelBasicMessageChannel(com.example.test1/message,StringCodec());命名规范:包名/通道名2. MethodChannel 使用// 调用原生方法finalresultawait_methodChannel.invokeMethod(方法名,参数);// 示例获取平台版本finalversionawait_methodChannel.invokeMethod(getPlatformVersion);// 示例带参数调用finalresultawait_methodChannel.invokeMethod(sendData,{name:Flutter,value:123,});错误处理:try{finalresultawait_methodChannel.invokeMethod(方法名);}onPlatformExceptioncatch(e){// 处理平台错误print(错误码:${e.code});print(错误信息:${e.message});}3. EventChannel 使用// 监听事件流StreamSubscription?_subscription;voidstartListening(){_subscription_eventChannel.receiveBroadcastStream({param:初始参数,}).listen((event)print(收到事件:$event),onError:(error)print(错误:$error),onDone:()print(流结束),);}// 取消监听voidstopListening(){_subscription?.cancel();}4. BasicMessageChannel 使用// 设置消息处理器接收原生消息_messageChannel.setMessageHandler((String?message)async{print(收到:$message);returnFlutter 回复;});// 发送消息到原生finalreplyawait_messageChannel.send(Hello);print(原生回复:$reply);三、鸿蒙端实现1. MethodChannel 处理constmethodChannelnewMethodChannel(messenger.binaryMessenger,com.example.test1/method);methodChannel.setMethodCallHandler((call:MethodCall,result:MethodResult){switch(call.method){casegetPlatformVersion:result.success({platform:HarmonyOS,version:5.0});break;casesendData:constnamecall.argument(name)asstring;result.success({received:true,message:收到:${name}});break;casethrowError:result.error(ERROR_CODE,错误信息,{detail:详情});break;default:result.notImplemented();}});关键类型:类型说明MethodCall方法调用对象含method和参数MethodResult结果回调success()/error()/notImplemented()call.argument(key)获取参数值2. EventChannel 处理consteventChannelnewEventChannel(messenger.binaryMessenger,com.example.test1/event);eventChannel.setStreamHandler({onListen:(args:object,events:EventSink){// 开始发送事件events.success({type:connected});// 定时发送this.timersetInterval((){events.success({type:data,timestamp:newDate().toISOString()});},2000);},onCancel:(args:object){// 停止发送clearInterval(this.timer);}});3. BasicMessageChannel 处理constmessageChannelnewBasicMessageChannel(messenger.binaryMessenger,com.example.test1/message,newStringCodec());messageChannel.setMessageHandler((message:string,reply:Replystring){console.info(收到:${message});reply.reply(鸿蒙回复:${message});});四、完整通信流程MethodChannel 时序Flutter 鸿蒙 │ │ │── invokeMethod() ────────│ │ │── handleMethodCall() │ │ │──────── result.success()─│ │ │EventChannel 时序Flutter 鸿蒙 │ │ │── receiveBroadcastStream()│ │ │ │ │───────────┼── events.success() [多次] │ │ │ │── cancel()───────────────│── onCancel()五、关键要点注意点说明通道名必须一致Flutter 和鸿蒙端名称要完全相同类型安全ArkTS 需要显式类型转换as string内存管理EventChannel 记得取消订阅错误处理使用PlatformException捕获错误主线程通道通信在主线程耗时操作需异步六、测试 Demo 功能测试项操作预期结果获取版本点击按钮返回{platform: HarmonyOS, version: 5.0}发送数据点击按钮返回处理后的数据对象设备信息点击按钮返回复杂对象含多个字段测试错误点击按钮捕获PlatformException事件流开始监听每2秒收到一个事件消息通道发送消息收到鸿蒙回复七、快速开始// 1. 定义通道constplatformMethodChannel(com.example/channel);// 2. 调用原生finalresultawaitplatform.invokeMethod(方法名);// 3. 鸿蒙端处理methodChannel.setMethodCallHandler((call,result){result.success(返回数据);});