本文将通过BasicMessageChannel获取app版本号,以此来演练BasicMessageChannel用法。
- 建立channel
flutter代码:
//建立通道
BasicMessageChannel basicMessageChannel = BasicMessageChannel("com.xmg.basicMessageChannel",StringCodec());
ohos代码:
//定义BasicMessageChannel
private basicMessageChannel: BasicMessageChannel<String> | null = null
//建立通道
this.basicMessageChannel = new BasicMessageChannel(flutterEngine.getDartExecutor(), "com.xmg.basicMessageChannel", StringCodec.INSTANCE)
- 消息发送
消息发送由flutter发送,flutter代码如下:
//发送消息给ohos,并接收ohos返回的消息
void _sendMessage(String sendMessage) async{ohosResultToFlutter = await basicMessageChannel.send(sendMessage);setState(() {});}
- 消息处理
ohos接收消息,打印log,并且返回应用版本号给flutter
//消息处理,接收来自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);})}})
log输出打印收到来自Flutter的消息: flutter发送消息到ohos
- flutter展示版本号
- 完整代码
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: 'BasicMessageChannel获取app版本号'),);}
}class MyHomePage extends StatefulWidget {const MyHomePage({super.key, required this.title});final String title;@overrideState<MyHomePage> createState() => _MyHomePageState();
}class _MyHomePageState extends State<MyHomePage> {//建立通道BasicMessageChannel basicMessageChannel = BasicMessageChannel("com.xmg.basicMessageChannel",StringCodec());//展示ohos返回结果String ohosResultToFlutter = "";//发送消息给ohos,并接收ohos返回的消息void _sendMessage(String sendMessage) async{ohosResultToFlutter = await basicMessageChannel.send(sendMessage);setState(() {});}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text(widget.title),),body: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[if (ohosResultToFlutter.isNotEmpty)Text("收到来自ohos的消息为:"+ohosResultToFlutter,),ElevatedButton(onPressed: () {_sendMessage("flutter发送消息到ohos");}, child: Text("发送消息"))],),),);}
}
ohos代码:
import {BasicMessageChannel,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'export default class EntryAbility extends FlutterAbility {private channel: MethodChannel | null = null//定义BasicMessageChannelprivate basicMessageChannel: BasicMessageChannel<String> | null = nullconfigureFlutterEngine(flutterEngine: FlutterEngine) {super.configureFlutterEngine(flutterEngine)GeneratedPluginRegistrant.registerWith(flutterEngine)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.getDartExecutor(), "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);})}})}
}