Flutter项目和鸿蒙平台的通信

Flutter项目和鸿蒙平台的通信

前言

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

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

  • BasicMessageChannel:用于传递字符串和半结构化的信息。BasicMessageChannel支持数据双向传递,有返回值。
  • MethodChannel:用于传递方法调用(method invocation)。MethodChannel支持数据双向传递,有返回值。通常用来调用 native 中某个方法
  • EventChannel: 用于数据流(event streams)的通信。 EventChannel仅支持数据单向传递,无返回值。有监听功能,比如电量变化之后直接推送数据给flutter端
    对比表格:

    flutter_flutter 也是通过上述三种方式来和鸿蒙平台进行通信的

Flutter和Harmonyos通信

MethodChannel

  • flutter代码:
dart 复制代码
// 创建一个通道
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}'.";
    }
  }

鸿蒙平台代码:

typescript 复制代码
// 实现这个声明周期方法,在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":
          	// 执行对应的方法, 然后把结果传递给flutter
            that.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代码:

typescript 复制代码
// 创建一个基础通道, 通道名需要和鸿蒙平台约定好
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;
    });
  }

鸿蒙平台代码:

typescript 复制代码
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代码:

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

鸿蒙平台代码:

typescript 复制代码
onAttachedToEngine(binding: FlutterPluginBinding): void {
    let that = this;
    // 创建实例
    this.eventChannel = new EventChannel(binding.getBinaryMessenger(), "samples.flutter.dev/event_channel");
    // 设置回调,获取EventSink
    this.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());
相关推荐
ChinaDragon6 分钟前
HarmonyOS:进度条 (Progress)
harmonyos
半路下车27 分钟前
【Harmony OS 5】DevEco Testing赋能智慧教育
harmonyos·arkts
libo_202536 分钟前
HarmonyOS5 灰度发布:通过AGC控制台分阶段更新Uniapp混合应用
harmonyos
libo_202537 分钟前
自动化测试:将Uniapp页面注入HarmonyOS5 UITest框架
harmonyos
libo_202537 分钟前
HarmonyOS5 Uniapp+OpenHarmony标准设备适配指南
harmonyos
libo_202538 分钟前
HarmonyOS5 内存优化:用DevEco Studio Profiler分析Uniapp混合栈泄漏
harmonyos
libo_202541 分钟前
AI能力整合:在Uniapp中调用HarmonyOS5 HiAI Kit的图像识别
harmonyos
libo_202541 分钟前
HarmonyOS5 Uniapp应用上架AppGallery全流程:从签名到过审避坑指南
harmonyos
恋猫de小郭2 小时前
为什么跨平台框架可以适配鸿蒙,它们的技术原理是什么?
android·前端·flutter