鸿蒙harmonyos next flutter通信之MethodChannel获取设备信息

本文将通过MethodChannel获取设备信息,以此来演练MethodChannel用法。

  • 建立channel

flutter代码:

复制代码
MethodChannel methodChannel = MethodChannel("com.xmg.test");

ohos代码:

复制代码
private channel: MethodChannel | null = null

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;
        }
      }
    });

注意:channelName必须一致。这里都叫com.xmg.test

  • flutter侧调用

    复制代码
    void _getDeviceInfo() async{
        deviceInfo = await methodChannel.invokeMethod('getDeviceInfo');
        setState(() {
        });
      }
  • 完整代码

flutter完整代码:

复制代码
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: 'MethodChannel获取设备信息'),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  MethodChannel methodChannel = MethodChannel("com.xmg.test");
  String deviceInfo = "";

  void _getDeviceInfo() async{
    deviceInfo = await methodChannel.invokeMethod('getDeviceInfo');
    setState(() {
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              deviceInfo,
            ),
            ElevatedButton(onPressed: () {
              _getDeviceInfo();
            }, child: Text("获取设备版本号"))
          ],
        ),
      ),
    );
  }
}

ohos完整代码:

复制代码
import { FlutterAbility, FlutterEngine, MethodCall, MethodChannel, MethodResult } from '@ohos/flutter_ohos';
import { GeneratedPluginRegistrant } from '../plugins/GeneratedPluginRegistrant';
import deviceInfo from '@ohos.deviceInfo'

export default class EntryAbility extends FlutterAbility {
  private channel: MethodChannel | 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;
        }
      }
    });
  }
}
  • 效果展示
相关推荐
2501_944521595 小时前
Ramda 跨端三方库仓颉适配全流程
开发语言·javascript·flutter·php
大龄秃头程序员12 小时前
Flutter 架构里总被混淆的 IoC、DI、Service Locator,到底是什么关系?
flutter
事圆则缓17 小时前
Flutter 与原生交互的最后一层:RTC 视频帧怎么走
flutter·音视频·实时音视频
2601_9498477517 小时前
jose 跨端三方库仓颉适配全流程
前端·javascript·flutter
2601_9499706920 小时前
msgpackr 跨端三方库仓颉适配全流程
前端·javascript·flutter
2601_949970691 天前
HumanizeDuration 跨端三方库仓颉适配全流程
前端·javascript·flutter
传奇开心果编程1 天前
【Flutter踩坑排雷】第3课:const 误用坑|const 错误使用引发 UI 异常与性能损耗
flutter·移动开发·跨平台·dart·编程语言理论·编程框架·声明式ui
程序员老刘1 天前
你的Flutter项目要不要紧急升级3.47.8?
flutter·客户端
Talyra422 天前
不想开会员,我写了一个记账 App
flutter
2601_949575862 天前
JSON5 跨端三方库仓颉适配全流程
前端·javascript·flutter