鸿蒙harmonyos next flutter通信之EventChannel获取ohos系统时间

  • 建立通道

flutter代码:

EventChannel eventChannel = EventChannel("com.xmg.eventChannel");

ohos代码:

  //定义eventChannel
  private eventChannel: EventChannel | null = null
  //定义eventSink
  private eventSink: EventSink | null = null

//建立通道
    this.eventChannel = new EventChannel(flutterEngine.dartExecutor.getBinaryMessenger(),"com.xmg.eventChannel");
    this.eventChannel.setStreamHandler({
      onListen(args: Any, events: EventSink) {
        that.eventSink = events;
        //设置定时器
        setInterval(()=>{
          console.log("that.eventSink is "+that.eventSink)
          console.log("that.eventSink is "+new Date())
          let dateTime = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss')
          that.eventSink?.success(dateTime)
        },1000)
      },
      onCancel(args: Any) {
        that.eventSink = null
      }
    })
  • ohos消息发送,这里使用定时器通过eventSink每隔一秒传送当前时间给flutter,代码如下:

          //设置定时器
          setInterval(()=>{
            console.log("that.eventSink is "+that.eventSink)
            console.log("that.eventSink is "+new Date())
            let dateTime = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss')
            that.eventSink?.success(dateTime)
          },1000)
    
  • flutter接收消息并展示当前时间

    @override
    void initState() {
    eventChannel.receiveBroadcastStream().listen((event){
    print("eventChannel.receiveBroadcastStream().listen");
    print(event);
    returnMessageFromOhos = event;
    setState(() {

        });
      });
      super.initState();
    }
    
  • 完整代码

flutter代码:

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'EventChannel获取ohos系统时间'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  EventChannel eventChannel = EventChannel("com.xmg.eventChannel");
  String returnMessageFromOhos = "";

  @override
  void initState() {
    eventChannel.receiveBroadcastStream().listen((event){
      print("eventChannel.receiveBroadcastStream().listen");
      print(event);
      returnMessageFromOhos = event;
      setState(() {

      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              returnMessageFromOhos,
            ),
          ],
        ),
      ),
    );
  }
}

ohos代码:

import {
  Any,
  BasicMessageChannel,
  EventChannel,
  FlutterAbility, FlutterEngine, MethodCall, MethodChannel, MethodResult,
  StringCodec} from '@ohos/flutter_ohos';
import { GeneratedPluginRegistrant } from '../plugins/GeneratedPluginRegistrant';
import deviceInfo from '@ohos.deviceInfo'
import { bundleManager } from '@kit.AbilityKit'
import { EventSink } from '@ohos/flutter_ohos/src/main/ets/plugin/common/EventChannel'
import dayjs from 'dayjs'

export default class EntryAbility extends FlutterAbility {
  private channel: MethodChannel | null = null

  //定义BasicMessageChannel
  private basicMessageChannel: BasicMessageChannel<String> | null = null

  //eventChannel
  private eventChannel: EventChannel | null = null
  private eventSink: EventSink | null = null

  configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    GeneratedPluginRegistrant.registerWith(flutterEngine)
    let that = this;
    this.channel = new MethodChannel(flutterEngine.dartExecutor.getBinaryMessenger(), 'com.xmg.test')
    this.channel.setMethodCallHandler({
      onMethodCall(call: MethodCall, result: MethodResult): void {
        switch (call.method) {
          case 'getDeviceInfo':
            result.success(deviceInfo.displayVersion);
            break;
          default:
            result.notImplemented
            break;
        }
      }
    });

    //建立通道
    this.basicMessageChannel = new BasicMessageChannel(flutterEngine.dartExecutor.getBinaryMessenger(), "com.xmg.basicMessageChannel", StringCodec.INSTANCE)
    //消息处理,接收来自flutter的消息
    this.basicMessageChannel.setMessageHandler({
      onMessage(message,reply) {
        console.log("收到来自Flutter的消息: " + message)
        let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION;
        bundleManager.getBundleInfoForSelf(bundleFlags, (err, data) => {
          // 获取应用的版本名(versionName)
          const versionName = data.versionName;
          reply.reply(versionName);
        })
      }
    })

    //建立通道
    this.eventChannel = new EventChannel(flutterEngine.dartExecutor.getBinaryMessenger(),"com.xmg.eventChannel");
    this.eventChannel.setStreamHandler({
      onListen(args: Any, events: EventSink) {
        that.eventSink = events;
        //设置定时器
        setInterval(()=>{
          console.log("that.eventSink is "+that.eventSink)
          console.log("that.eventSink is "+new Date())
          let dateTime = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss')
          that.eventSink?.success(dateTime)
        },1000)
      },
      onCancel(args: Any) {
        that.eventSink = null
      }
    })

  }
}
  • 效果展示

鸿蒙harmonyos next flutter通信

相关推荐
SoraLuna2 小时前
「Mac畅玩鸿蒙与硬件28」UI互动应用篇5 - 滑动选择器实现
macos·ui·harmonyos
ClkLog-开源埋点用户分析3 小时前
ClkLog企业版(CDP)预售开启,更有鸿蒙SDK前来助力
华为·开源·开源软件·harmonyos
mg6683 小时前
鸿蒙系统的优势 开发 环境搭建 开发小示例
华为·harmonyos
模拟IC攻城狮3 小时前
华为海思招聘-芯片与器件设计工程师-模拟芯片方向- 机试题-真题套题题目——共8套(每套四十题)
嵌入式硬件·华为·硬件架构·芯片
lqj_本人3 小时前
鸿蒙next选择 Flutter 开发跨平台应用的原因
flutter·华为·harmonyos
lqj_本人3 小时前
使用 Flutter 绘制一个棋盘
harmonyos
TangKenny3 小时前
计算网络信号
java·算法·华为
23zhgjx-NanKon4 小时前
华为eNSP:QinQ
网络·安全·华为
23zhgjx-NanKon4 小时前
华为eNSP:mux-vlan
网络·安全·华为
Leo.yuan6 小时前
39页PDF | 华为数据架构建设交流材料(限免下载)
数据结构·华为