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

相关推荐
枫叶丹42 小时前
【HarmonyOS之旅】HarmonyOS开发基础知识(三)
华为od·华为·华为云·harmonyos
迷雾漫步者7 小时前
Flutter组件————FloatingActionButton
前端·flutter·dart
SoraLuna7 小时前
「Mac畅玩鸿蒙与硬件47」UI互动应用篇24 - 虚拟音乐控制台
开发语言·macos·ui·华为·harmonyos
AORO_BEIDOU11 小时前
单北斗+鸿蒙系统+国产芯片,遨游防爆手机自主可控“三保险”
华为·智能手机·harmonyos
coder_pig11 小时前
📝小记:Ubuntu 部署 Jenkins 打包 Flutter APK
flutter·ubuntu·jenkins
博览鸿蒙12 小时前
鸿蒙操作系统(HarmonyOS)的应用开发入门
华为·harmonyos
捡芝麻丢西瓜13 小时前
flutter自学笔记5- dart 编码规范
flutter·dart
恋猫de小郭14 小时前
什么?Flutter 可能会被 SwiftUI/ArkUI 化?全新的 Flutter Roadmap
flutter·ios·swiftui
Damon小智19 小时前
HarmonyOS NEXT 技术实践-基于基础视觉服务的多目标识别
华为·harmonyos
匹马夕阳1 天前
华为笔记本之糟糕的体验
华为·笔记本电脑