鸿蒙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;
        }
      }
    });
  }
}
  • 效果展示
相关推荐
blanks20209 小时前
如何查看 drift 在 本机的 sqlite 文件路径
flutter
m0_7381858216 小时前
Flutter 鸿蒙化实战:flutter_iot_wifi 适配 OpenHarmony,IoT 设备 WiFi 配网
物联网·flutter·华为·harmonyos·鸿蒙
律宏阔1 天前
Flutter Riverpod 3:统一打印 Provider 错误与自动重试日志
前端·flutter
m0_738185821 天前
Flutter 鸿蒙化实战:flutter_exif_plugin 适配 OpenHarmony,图片 EXIF 读写
flutter·华为·harmonyos·鸿蒙
恋猫de小郭1 天前
Shopify 回应为什么从 RN 回到原生,为什么不用 KMP ?
android·前端·flutter
事圆则缓2 天前
Flutter 状态管理框架对比(五):GetX 的响应式、依赖注册与生命周期
前端·javascript·flutter
事圆则缓2 天前
Flutter 状态管理框架对比(六):同一个购物车,四种方案怎么落地?
前端·javascript·flutter
恋猫de小郭2 天前
Android 原生的 Compose A2UI 也来了,你还抱着 XML 养老吗?
android·前端·flutter
事圆则缓3 天前
Flutter 状态管理框架对比(三):Riverpod 如何连起购物车与异步价格
开发语言·javascript·flutter