欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > Flutter项目和鸿蒙平台的通信

Flutter项目和鸿蒙平台的通信

2025/1/23 15:42:56 来源:https://blog.csdn.net/yong_19930826/article/details/145259046  浏览:    关键词:Flutter项目和鸿蒙平台的通信

Flutter项目和鸿蒙平台的通信

  • 前言
  • Flutter和Harmonyos通信
    • MethodChannel
    • BasicMessageChannel
    • EventChannel

前言

大家在使用Flutter开发项目的时候, Flutter提供了Platfrom Channel API来和个个平台进行交互。

Flutter官方目前提供了一下三种方式来和个个平台交互:

  • BasicMessageChannel:用于传递字符串和半结构化的信息。BasicMessageChannel支持数据双向传递,有返回值。
  • MethodChannel:用于传递方法调用(method invocation)。MethodChannel支持数据双向传递,有返回值。通常用来调用 native 中某个方法
  • EventChannel: 用于数据流(event streams)的通信。 EventChannel仅支持数据单向传递,无返回值。有监听功能,比如电量变化之后直接推送数据给flutter端
    对比表格:
    在这里插入图片描述
    flutter_flutter 也是通过上述三种方式来和鸿蒙平台进行通信的

Flutter和Harmonyos通信

MethodChannel

  • flutter代码:
// 创建一个通道
final _platform = const MethodChannel('samples.flutter.dev/battery');Future<void> _getBatteryLevel() async {String batteryLevel;try {// getBatteryLevel 是flutter传递给鸿蒙平台的参数final result = await _platform.invokeMethod<int>('getBatteryLevel');batteryLevel = 'Battery level at $result % .';} on PlatformException catch (e) {batteryLevel = "Failed to get battery level: '${e.message}'.";}}

鸿蒙平台代码:

// 实现这个声明周期方法,在plugin中
onAttachedToEngine(binding: FlutterPluginBinding): void {
// 创建一个通道, 通道名称需要和flutter创建的通道名称保持一致,才可以通信this.channel = new MethodChannel(binding.getBinaryMessenger(), "samples.flutter.dev/battery");let that = this;// 实现通道的回调方法this.channel.setMethodCallHandler({onMethodCall(call: MethodCall, result: MethodResult) {switch (call.method) {// 接收到flutter传递过来的参数case "getBatteryLevel":// 执行对应的方法, 然后把结果传递给flutterthat.api.getBatteryLevel(result);break;default:result.notImplemented();break;}}})  }// 获取电池电量的类
class BatteryApi {getBatteryLevel(result: MethodResult) {let level: number = batteryInfo.batterySOC;Log.i(TAG, "level=" + level);let wrapped: Map<String, Any> = new Map<String, Any>();if (level >= 0) {result.success(level);} else {Log.i(TAG, "getBatteryLevel else");wrapped.set("UNAVAILABLE", "Battery level not available.");result.error("UNAVAILABLE", "Battery level not available.", null)}Log.i(TAG, "getBatteryLevel finish");}
}

BasicMessageChannel

Flutter代码:

// 创建一个基础通道, 通道名需要和鸿蒙平台约定好
final _basicChannel = const BasicMessageChannel("samples.flutter.dev/basic_channel", StandardMessageCodec());_testBasicChannel() async {String result;try {result = await _basicChannel.send(++count) as String;} on PlatformException catch (e) {result = "Error: $e";}setState(() {message = result;});}

鸿蒙平台代码:

onAttachedToEngine(binding: FlutterPluginBinding): void {// 创建实例this.basicChannel = new BasicMessageChannel(binding.getBinaryMessenger(), "samples.flutter.dev/basic_channel", new StandardMessageCodec());// 设置回调,调用具体的实现this.basicChannel.setMessageHandler({onMessage(message: Any, reply: Reply<Any>) {Log.i(TAG, "message=" + message);if (message % 2 == 0) {reply.reply("run with if case.");} else {reply.reply("run with else case");}}})
}

EventChannel

flutter代码:

// 创建实例
final _eventChannel = const EventChannel('samples.flutter.dev/event_channel');
// 注册事件监听
_eventChannel.receiveBroadcastStream().listen((event) {setState(() {message = "EventChannel event=$event";});
});

鸿蒙平台代码:

onAttachedToEngine(binding: FlutterPluginBinding): void {let that = this;// 创建实例this.eventChannel = new EventChannel(binding.getBinaryMessenger(), "samples.flutter.dev/event_channel");// 设置回调,获取EventSinkthis.eventChannel.setStreamHandler({onListen(args: Any, events: EventSink): void {that.eventSink = events;Log.i(TAG, "onListen: " + args);},onCancel(args: Any): void {that.eventSink = undefined;Log.i(TAG, "onCancel: " + args);}});
}// ...
// 使用 EventSink 发送数据后,dart断的事件监听回调会收到发送的数据。
that.eventSink?.success("Success at " + new Date());

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com