- 建立通道
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}})}
}
- 效果展示