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

news/2024/12/22 18:12:11/
  • 建立通道

flutter代码:

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

ohos代码:

  //定义eventChannelprivate eventChannel: EventChannel | null = null//定义eventSinkprivate 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接收消息并展示当前时间
@overridevoid 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});@overrideWidget 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;@overrideState<MyHomePage> createState() => _MyHomePageState();
}class _MyHomePageState extends State<MyHomePage> {EventChannel eventChannel = EventChannel("com.xmg.eventChannel");String returnMessageFromOhos = "";@overridevoid initState() {eventChannel.receiveBroadcastStream().listen((event){print("eventChannel.receiveBroadcastStream().listen");print(event);returnMessageFromOhos = event;setState(() {});});super.initState();}@overrideWidget 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//定义BasicMessageChannelprivate basicMessageChannel: BasicMessageChannel<String> | null = null//eventChannelprivate eventChannel: EventChannel | null = nullprivate eventSink: EventSink | null = nullconfigureFlutterEngine(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.notImplementedbreak;}}});//建立通道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通信


http://www.ppmy.cn/news/1533534.html

相关文章

刷题学习日记 (1) - SWPUCTF

写这篇文章主要是想看看自己一个下午能干啥&#xff0c;不想老是浪费时间了&#xff0c;所以刷多少题我就会写多少题解&#xff0c;使用nss随机刷题&#xff0c;但是今天下午不知道为啥一刷都是SWPUCTF的。 [SWPUCTF 2021 新生赛]gift_F12 控制台ctrlf搜索flag即可&#xff0…

记Flink SQL 将数据写入 MySQL时的一个优化策略

Flink SQL 将数据写入 MySQL 时&#xff0c;如果主分片数较少&#xff0c;可以通过调整 MySQL 的主分片数来提高读写性能 1. 检查当前的分片设置 在 MySQL 中&#xff0c;使用以下 SQL 查询来查看当前的分片情况&#xff1a; SHOW VARIABLES LIKE innodb_buffer_pool_size; …

Master PDF Editor 下载及详细安装教程

具体安装方式如下&#xff1a; 下载&#xff1a; MasterPDFEditor 先解压&#xff0c;将解压后的如下文件发送到桌面快捷方式 启动发送后桌面图标 选择要打开的pdf文档&#xff0c;可以看到打开速度是超级快&#xff0c;正常使用&#xff0c;操作简单方便

Spring MVC__入门

目录 一、SpringMVC简介1、什么是MVC2、什么是SpringMVC 二、Spring MVC实现原理2.1核心组件2.2工作流程 三、helloworld1、开发环境2、创建maven工程3、配置web.xml4、创建请求控制器5、创建springMVC的配置文件6、测试HelloWorld7、总结 一、SpringMVC简介 1、什么是MVC MV…

网络安全中的 EDR 是什么:概述和功能

专业知识&#xff1a;EDR、XDR、NDR 和 MDR_xdr edr ndr-CSDN博客 端点检测和响应 (EDR) 是一种先进的安全系统&#xff0c;用于检测、调查和解决端点上的网络攻击。它可以检查事件、检查行为并将系统恢复到攻击前的状态。EDR 使用人工智能、机器学习和威胁情报来避免再次发生攻…

<<迷雾>> 第5章 从逻辑学到逻辑电路(5)--异或门 示例电路

!ABA!B 的逻辑电路组成 info::操作说明 鼠标单击开关切换开合状态 注: 这个实际就是 异或门, 当两个输入相异时输出高电平, 否则输出低电平 primary::在线交互操作链接 https://cc.xiaogd.net/?startCircuitLinkhttps://book.xiaogd.net/cyjsjdmw-examples/assets/circuit/cyj…

Python的异步编程

什么是协程&#xff1f; 协程不是计算机系统提供&#xff0c;程序员人为创造。 协程也可以被称为微线程&#xff0c;是一种用户态内的上下文切换技术。简而言之&#xff0c;其实就是通过一个线程实现代码块相互切换执行。 实现协程有那么几种方法&#xff1a; greenlet&…

云RDS MySQL迁移至本地MySQL

本地准备工作 1.安装:percona-xtrabackup 上传percona-xtrabackup-2.3.9-Linux-x86_64.tar.gz包到/usr/local tar -zxvf percona-xtrabackup-2.3.9-Linux-x86_64.tar.gz mv percona-xtrabackup-2.3.9-Linux-x86_64 percona-xtrabackup 2.创建数据目录 cd /data/ mkdir rds-mys…