Flutter中调用原生-platform channels(平
上一次介绍过Flutter中调用原生相册/相机功能,这个是因为flutter官网提供了三方的ImagePicker插件,可以快速实现访问相机功能,但是,如果像某些原生的信息,没有很好的插件,我们只能通过platform channels(平台通道)来获取信息。
以一个Flutter中文网的显示电池电量的例子,来介绍下MethodChannel
来实现客户端(UI)和宿主(平台)之间的信息传递。
platform channels(平台通道)
使用平台通道在客户端(Flutter UI)和宿主(iOS平台 & Android平台)之间传递消息,如下图所示(Flutter中文网提供):
001.png消息和响应是异步传递的,以确保用户界面保持响应(不会挂起)。
002.png调用过程大致如下:
1.在客户端,MethodChannel
(API)可以发送与方法调用相对应的消息;
2.平台端(iOS、Android端)接收方法,并返回结果;
iOS端通过FlutterMethodChannel做出响应;
Android端通过MethodChannel做出响应;
实战过程:
我们这里创建一个获取电池电量信息的项目,分别通过iOS和Android原生代码来获取对应的信息:
1.Step 1: 创建一个新的Flutter应用程序项目
① 首先创建一个新的Flutter应用程序:在终端运行中:flutter create batterylevel
目前默认创建的Flutter项目,对应iOS的编程语言是Swift,对应Android的编程语言是kotlin
如果我们希望指定编程语言,比如iOS编程语言为Objective-C,Android的编程语言为Java
flutter create -i objc -a java batterylevel2
② 使用Android studio打开创建的项目,Flutter端获取当前电量信息代码如下
class _MyHomePageState extends State<MyHomePage> {
int _level = 0;
static const platform = const MethodChannel("flutter.com/battery");
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'剩余电量:',
),
Text(
'$_level',
style: Theme.of(context).textTheme.headline4,
),
RaisedButton(
child: Text("获取剩余电量"),
onPressed: _getBatteryInfo,
),
],
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
/// 获取电量信息
void _getBatteryInfo() async {
final result = await platform.invokeMethod("flutter.com/battery");
setState(() {
_level = result;
});
}
}
Step 2: 打开batterylevel下的iOS的Runner工程,
003.png
iOS端对应的获取电量信息的代码如下:
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// 实现获取电池信息的功能
// 1.获取FlutterViewController
let controller: FlutterViewController = window.rootViewController as! FlutterViewController ;
// 2.创建FlutterMethodChannel
let channel = FlutterMethodChannel(name: "flutter.com/battery", binaryMessenger: controller.binaryMessenger);
// 3.监听channel调用方法(Flutter中platform.invokeMethod方法调用,下面这个函数回调就会执行)
channel.setMethodCallHandler { (call:FlutterMethodCall,result: @escaping FlutterResult) in
//3.1 判断当前方法是否是getBatteryInfo
guard call.method == "getBatteryInfo" else {
result(FlutterMethodNotImplemented);
return;
}
//3.2获取电池信息
let device = UIDevice.current;
device.isBatteryMonitoringEnabled = true;
//3.3获取电量信息
if device.batteryState == UIDevice.BatteryState.unknown {
result(FlutterError(code:"unknow", message:"batter info is unknow",details:nil));
// result(1000);
} else {
result(Int(device.batteryLevel * 100));
}
};
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Step 3: 打开batterylevel下的android的工程
004.png
android端对应的获取电量信息的代码如下(kotlin):
class MainActivity: FlutterActivity() {
private val channel = "flutter.com/battery"
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
// 1.创建MethodChannel对象
val methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channel)
// 2.添加调用方法的回调
methodChannel.setMethodCallHandler {
// Note: this method is invoked on the main thread.
call, result ->
// 2.1.如果调用的方法是getBatteryInfo,那么正常执行
if (call.method == "getBatteryInfo") {
// 2.1.1.调用另外一个自定义方法回去电量信息
val batteryLevel = getBatteryLevel()
// 2.1.2. 判断是否正常获取到
if (batteryLevel != -1) {
// 获取到返回结果
result.success(batteryLevel)
} else {
// 获取不到抛出异常
result.error("UNAVAILABLE", "Battery level not available.", null)
}
} else {
// 2.2.如果调用的方法是getBatteryInfo,那么正常执行
result.notImplemented()
}
}
}
private fun getBatteryLevel(): Int {
val batteryLevel: Int
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
}
return batteryLevel
}
}
andriod运行效果如下:
005.jpg至此,Flutter中和原生的通信暂时学习记录至此,后续有有新的用法将持续更新。
DEMO下载.