鸿蒙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);
        })
      }
    })
  }
}
相关推荐
恋猫de小郭1 小时前
Flutter 发布官方 Skills ,Flutter 在 AI 领域再添一助力
android·前端·flutter
恋猫de小郭16 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
明君8799721 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter
四眼肥鱼1 天前
flutter 利用flutter_libserialport 实现SQ800 串口通信
前端·flutter
火柴就是我2 天前
让我们实现一个更好看的内部阴影按钮
android·flutter
王晓枫2 天前
flutter接入三方库运行报错:Error running pod install
前端·flutter
shankss2 天前
Flutter 下拉刷新库 pull_to_refresh_plus 设计与实现分析
flutter
忆江南3 天前
iOS 深度解析
flutter·ios
明君879973 天前
Flutter 实现 AI 聊天页面 —— 记一次 Markdown 数学公式显示的踩坑之旅
前端·flutter
恋猫de小郭3 天前
移动端开发稳了?AI 目前还无法取代客户端开发,小红书的论文告诉你数据
前端·flutter·ai编程