鸿蒙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);
        })
      }
    })
  }
}
相关推荐
旭日猎鹰2 小时前
Flutter踩坑记录(三)-- 更改入口执行文件
flutter
旭日猎鹰2 小时前
Flutter踩坑记录(一)debug运行生成的项目,不能手动点击运行
flutter
️ 邪神2 小时前
【Android、IOS、Flutter、鸿蒙、ReactNative 】自定义View
flutter·ios·鸿蒙·reactnative·anroid
比格丽巴格丽抱14 小时前
flutter项目苹果编译运行打包上线
flutter·ios
SoaringHeart14 小时前
Flutter进阶:基于 MLKit 的 OCR 文字识别
前端·flutter
AiFlutter19 小时前
Flutter通过 Coap发送组播
flutter
嘟嘟叽2 天前
初学 flutter 环境变量配置
flutter
iFlyCai2 天前
深入理解Flutter生命周期函数之StatefulWidget(一)
flutter·生命周期·dart·statefulwidget
sunly_2 天前
Flutter:photo_view图片预览功能
android·javascript·flutter
Summer不秃2 天前
Flutter中sqflite的使用案例
flutter