鸿蒙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通信

相关推荐
Random_index5 小时前
#Uniapp篇:支持纯血鸿蒙&发布&适配&UIUI
uni-app·harmonyos
比格丽巴格丽抱8 小时前
flutter项目苹果编译运行打包上线
flutter·ios
SoaringHeart8 小时前
Flutter进阶:基于 MLKit 的 OCR 文字识别
前端·flutter
鸿蒙自习室9 小时前
鸿蒙多线程开发——线程间数据通信对象02
ui·harmonyos·鸿蒙
SuperHeroWu711 小时前
【HarmonyOS】鸿蒙应用接入微博分享
华为·harmonyos·鸿蒙·微博·微博分享·微博sdk集成·sdk集成
期待未来的男孩11 小时前
华为FusionCube 500-8.2.0SPC100 实施部署文档
华为
AiFlutter12 小时前
Flutter通过 Coap发送组播
flutter
岳不谢13 小时前
VPN技术-VPN简介学习笔记
网络·笔记·学习·华为
zhangjr057513 小时前
【HarmonyOS Next】鸿蒙实用装饰器一览(一)
前端·harmonyos·arkts
诗歌难吟46420 小时前
初识ArkUI
harmonyos