插件介绍

本项目是一个专为鸿蒙系统适配的Flutter Channel通信示例包,演示了Flutter与鸿蒙原生平台之间的三种核心通信方式。该框架作为Flutter与鸿蒙原生平台的桥梁,实现了双向通信机制,为开发者提供了灵活的跨平台交互解决方案。

主要功能包括:

  • MethodChannel:实现Flutter调用鸿蒙原生方法(同步/异步)
  • EventChannel:实现鸿蒙原生平台向Flutter发送事件流
  • BasicMessageChannel:实现Flutter与鸿蒙原生平台之间的基础消息通信

该示例包通过电池电量获取功能,全面展示了三种Channel通信方式的使用场景和实现方法,适用于需要在Flutter与鸿蒙原生平台之间进行数据交互的各种应用场景。

使用步骤

1. 项目结构与配置

该示例包是一个完整的Flutter-HarmonyOS跨平台项目,包含以下核心文件:

  • lib/main.dart:Flutter侧Channel通信实现
  • ohos/entry/src/main/ets/entryability/BatteryPlugin.ets:鸿蒙侧Channel通信实现

2. Flutter侧实现

在Flutter项目中,需要导入flutter/services.dart包,并创建相应的Channel实例:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class _PluginPageState extends State<PluginPage> {
  String message = "";
  // 创建三种不同类型的Channel
  final _platform = const MethodChannel('samples.flutter.dev/battery');
  final _eventChannel = const EventChannel('samples.flutter.dev/event_channel');
  final _basicChannel = const BasicMessageChannel(
      "samples.flutter.dev/basic_channel", StandardMessageCodec());
  int count = 0;

  
  void initState() {
    super.initState();
    _initListener();
  }

  // 初始化EventChannel监听
  _initListener() {
    _eventChannel.receiveBroadcastStream().listen((event) {
      setState(() {
        message = "EventChannel event=$event";
      });
    });
  }

  // 其他方法实现...
}

3. 鸿蒙侧实现

在鸿蒙项目中,需要创建实现FlutterPlugin接口的插件类,并注册相应的Channel:

import {
  Any,
  BasicMessageChannel,
  EventChannel,
  FlutterManager,
  FlutterPlugin,
  Log,
  MethodCall,
  MethodChannel,
  StandardMessageCodec
} from '@ohos/flutter_ohos';
import { batteryInfo } from '@kit.BasicServicesKit';

const TAG = "BatteryPluginTag";

export default class BatteryPlugin implements FlutterPlugin {
  private channel?: MethodChannel;
  private basicChannel?: BasicMessageChannel<Any>;
  private eventChannel?: EventChannel;
  private eventSink?: EventSink;
  private api = new BatteryApi();

  onAttachedToEngine(binding: FlutterPluginBinding): void {
    // 初始化并注册各种Channel
    this.channel = new MethodChannel(binding.getBinaryMessenger(), "samples.flutter.dev/battery");
    this.basicChannel = new BasicMessageChannel(binding.getBinaryMessenger(), "samples.flutter.dev/basic_channel", new StandardMessageCodec());
    this.eventChannel = new EventChannel(binding.getBinaryMessenger(), "samples.flutter.dev/event_channel");

    // 设置各自的处理逻辑...
  }

  // 其他方法实现...
}

4. API调用示例

4.1 MethodChannel使用(获取电池电量)

Flutter侧调用代码

Future<void> _getBatteryLevel() async {
  String batteryLevel;
  try {
    // 调用需要在平台中实现的方法
    final result = await _platform.invokeMethod<int>('getBatteryLevel');
    batteryLevel = 'Battery level at $result % .';
  } on PlatformException catch (e) {
    batteryLevel = "Failed to get battery level: '${e.message}'";
  }

  setState(() {
    message = batteryLevel;
  });
}

鸿蒙侧实现代码

// 在BatteryApi类中实现getBatteryLevel方法
getBatteryLevel(result: MethodResult) {
  let level: number = batteryInfo.batterySOC;
  Log.i(TAG, "level=" + level);
  if (level >= 0) {
    result.success(level);
  } else {
    result.error("UNAVAILABLE", "Battery level not available.", null);
  }
}
4.2 EventChannel使用(接收平台事件)

Flutter侧监听代码

_initListener() {
  _eventChannel.receiveBroadcastStream().listen((event) {
    setState(() {
      message = "EventChannel event=$event";
    });
  });
}

// 触发平台发送事件
_testStreamCall() async {
  try {
    await _platform.invokeMethod('callEvent');
  } on PlatformException catch (e) {
    print(e);
  }
}

鸿蒙侧实现代码

// 在MethodChannel的处理逻辑中
case "callEvent":
  that.eventSink?.success("Success at " + new Date());
  break;

// 注册EventChannel事件流处理器
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);
  }
});
4.3 BasicMessageChannel使用(双向消息通信)

Flutter侧发送消息代码

_testBasicChannel() async {
  String result;
  try {
    result = await _basicChannel.send(++count) as String;
  } on PlatformException catch (e) {
    result = "Error: $e";
  }
  setState(() {
    message = result;
  });
}

鸿蒙侧接收消息代码

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");
    }
  }
});

5. 完整UI实现

将所有Channel功能整合到Flutter界面中:


Widget build(BuildContext context) {
  return Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(message),
        ElevatedButton(
          onPressed: () => _getBatteryLevel(),
          child: const Text("getBatteryLevel"),
        ),
        ElevatedButton(
          onPressed: () => _testStreamCall(),
          child: const Text("_testStreamCall"),
        ),
        ElevatedButton(
          onPressed: () => _testBasicChannel(),
          child: const Text("_testBasicChannel"),
        ),
      ],
    ),
  );
}

总结

Flutter Channel通信框架在鸿蒙跨平台开发中的应用,为开发者提供了强大的跨平台交互能力。其核心优势包括:

  • 灵活的通信方式:提供三种不同类型的Channel,满足各种通信需求
  • 高效的性能:底层基于二进制通信,保证数据传输效率
  • 易用的API:简洁的接口设计,降低跨平台通信开发难度
  • 良好的扩展性:支持自定义数据类型和通信协议

该示例通过电池电量获取功能,全面展示了Flutter与鸿蒙原生平台之间的通信实现,为开发者提供了清晰的参考模板。在实际应用中,开发者可以根据具体需求,选择合适的Channel类型,实现Flutter与鸿蒙原生平台之间的高效数据交互。

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐