赞
踩
Flutter端:
dart
MethodChannel channel = MethodChannel('samples.flutter.dev/battery');
String batteryLevel = await channel.invokeMethod('getBatteryLevel');
Android原生端:
java
public class BatteryChannel {
@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
result.success(batteryLevel);
}
}
}
iOS原生端:
objc @interface BatteryChannel : NSObject<FlutterMethodChannel> @end @implementation BatteryChannel - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { if ([@"getBatteryLevel" isEqualToString:call.method]) { int batteryLevel = [self getBatteryLevel]; result(batteryLevel); } } - (int)getBatteryLevel { UIDevice* device = UIDevice.currentDevice; device.batteryMonitoringEnabled = true; return (int)(device.batteryLevel * 100); } @end
这个案例展示了如何通过MethodChannel在Flutter和原生端通信:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。