鸿蒙harmonyos next flutter通信之BasicMessageChannel获取app版本号

本文将通过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

Dart 复制代码
//消息处理,接收来自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代码:

Dart 复制代码
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: 'BasicMessageChannel获取app版本号'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<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(() {
    });
  }

  @override
  Widget 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代码:

Dart 复制代码
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

  //定义BasicMessageChannel
  private basicMessageChannel: BasicMessageChannel<String> | null = null

  configureFlutterEngine(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.notImplemented
            break;
        }
      }
    });

    //建立通道
    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);
        })
      }
    })
  }
}
相关推荐
️ 邪神12 小时前
【Android、IOS、Flutter、鸿蒙、ReactNative 】文本点击事件
flutter·ios·鸿蒙·reactnative·anroid
️ 邪神13 小时前
【Android、IOS、Flutter、鸿蒙、ReactNative 】文本Text显示
flutter·ios·鸿蒙·reactnative·anroid
iFlyCai15 小时前
Flutter中有趣的级联语法
flutter
恋猫de小郭15 小时前
Flutter 小技巧之 Shader 实现酷炫的粒子动画
flutter
hello world smile18 小时前
Dart中List API用法大全
flutter·list·dart
lqj_本人1 天前
Flutter&鸿蒙next 使用 BLoC 模式进行状态管理详解
flutter·华为·harmonyos
Miketutu1 天前
flutter 项目初建碰到的控制台报错无法启动问题
flutter
lqj_本人1 天前
flutter&鸿蒙next 使用 InheritedWidget 实现跨 Widget 传递状态
flutter·华为·harmonyos
氤氲息1 天前
flutter 发版的时候设置版本号
flutter
潘敬1 天前
flutter 语法糖库 flutter_magic 发布 1.0.1
开发语言·前端·javascript·flutter·typescript