在混合开发中,无论哪种技术手段都避免不了native与框架的互相调用。Flutter基于以下方法实现了与native的互相调用。
Flutter称这种操作叫platform-specific
接下来要实现一个栗子、Flutter端获取Native的电量,并且当电量改变时会通知Flutter端。
一、Flutter调用Native
使用android端实现
1、创建一个项目
项目创建2、在Flutter端封装一个获取手机电量的方法
import 'package:flutter/services.dart';
class BatteryManager {
/// MethodChannel name是一个唯一标记,不重复就好
static const platform =
const MethodChannel('org.tiny.platformspecific/battery');
/// 远程调用需要异步操作, 把这个方法生命成 async
static Future<int> getBattery() async {
// 处理异常
try {
// getBatteryLevel 是远程方法的名字
final int result = await platform.invokeMethod('getBatteryLevel');
return Future.value(result);
} on PlatformException catch (e) {
return Future.value(-1);
}
}
}
3、Android端具体实现
package org.tiny.platformspecific;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.view.FlutterView;
/**
* Created by tiny on 2/21/2019.
*/
public class BatteryManager implements MethodChannel.MethodCallHandler {
private static final String CHANNEL = "org.tiny.platformspecific/battery";
private Context mContext;
static void registerWith(FlutterActivity activity) {
new BatteryManager(activity.getFlutterView());
}
private BatteryManager(FlutterView view) {
mContext = view.getContext();
new MethodChannel(view, CHANNEL).setMethodCallHandler(this);
}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
String method = methodCall.method;
switch (method) {
case "getBatteryLevel":
result.success(getBatteryLevel());
break;
default:
result.notImplemented();
break;
}
}
private int getBatteryLevel() {
Intent intent = new ContextWrapper(mContext.getApplicationContext()).
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
if (intent == null) return -1;
return intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
}
}
4、注册
package org.tiny.platformspecific;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
BatteryManager.registerWith(this);
}
}
5、总结
以上完成了Flutter到Android端的调用、套路还是很简单的,总结一下:
1、Flutter端创建 MethodChannel,使用 invokeMethod 调用远程方法
2、Native端创建 MethodChannel,实现 MethodCallHandler
3、Native完成注册
二、Flutter对Native设置监听
因为电量是一个不断变化的值,所以就需要Flutter对Native的监听这时候使用MethodChannel是不行的,所以有请下一个EventChannel,还是先上代码。
1、Flutter端创建
参照之前的Flutter代码进行了修改,使电量管理成为一个单例
import 'dart:async';
import 'package:flutter/services.dart';
class BatteryManager {
static BatteryManager _instance;
final MethodChannel _methodChannel;
final EventChannel _eventChannel;
StreamSubscription _eventStreamSubscription;
/// _私有构造方法
BatteryManager._(this._methodChannel, this._eventChannel);
/// 创建单例
static BatteryManager getInstance() {
if (_instance == null) {
final MethodChannel methodChannel =
const MethodChannel('org.tiny.platformspecific/battery');
final EventChannel eventChannel =
const EventChannel('org.tiny.platformspecific/charging');
_instance = BatteryManager._(methodChannel, eventChannel);
}
return _instance;
}
/// 得到电量
Future<int> getBatteryLevel() async {
try {
final int level = await _methodChannel.invokeMethod('getBatteryLevel');
return Future.value(level);
} on PlatformException catch (e) {
return Future.value(-1);
}
}
/// 监听电量的变化
StreamSubscription setOnBatteryListener(void onEvent(int battery)) {
if (_eventStreamSubscription == null) {
_eventStreamSubscription = _eventChannel
.receiveBroadcastStream()
.listen((data) => onEvent(data));
}
return _eventStreamSubscription;
}
}
2、Android端代码
package org.tiny.platformspecific;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
/**
* Created by tiny on 2/21/2019.
*/
public class BatteryManager implements MethodChannel.MethodCallHandler, EventChannel.StreamHandler {
private static final String METHOD = "org.tiny.platformspecific/battery";
private static final String EVENT = "org.tiny.platformspecific/charging";
private FlutterActivity mFlutterActivity;
private BroadcastReceiver mChargingStateChangeReceiver;
static void registerWith(FlutterActivity activity) {
new BatteryManager(activity);
}
private BatteryManager(FlutterActivity activity) {
mFlutterActivity = activity;
new MethodChannel(mFlutterActivity.getFlutterView(), METHOD).setMethodCallHandler(this);
new EventChannel(mFlutterActivity.getFlutterView(), EVENT).setStreamHandler(this);
}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
String method = methodCall.method;
switch (method) {
case "getBatteryLevel":
result.success(getBatteryLevel());
break;
default:
result.notImplemented();
break;
}
}
private int getBatteryLevel() {
Intent intent = new ContextWrapper(mFlutterActivity.getApplicationContext()).
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
if (intent == null) return -1;
return intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
}
@Override
public void onListen(Object arguments, final EventChannel.EventSink eventSink) {
mChargingStateChangeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int battery = intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
eventSink.success(battery);
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mFlutterActivity.registerReceiver(mChargingStateChangeReceiver, filter);
}
@Override
public void onCancel(Object arguments) {
if (mChargingStateChangeReceiver != null) {
mFlutterActivity.unregisterReceiver(mChargingStateChangeReceiver);
}
}
}
3、使用
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
int _battery = 0;
StreamSubscription _streamSubscription;
@override
void initState() {
_getBattery();
super.initState();
}
void _getBattery() async {
int battery = await BatteryManager.getInstance().getBatteryLevel();
_setBattery(battery);
_streamSubscription =
BatteryManager.getInstance().setOnBatteryListener(_setBattery);
}
void _setBattery(int battery) {
setState(() {
_battery = battery;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Battery: $_battery'),
),
);
}
@override
void dispose() {
_streamSubscription?.cancel();
super.dispose();
}
}
三、遇到的一些坑
1、android studio 代码离奇报错
我在android studio中编辑代码的时候,出现了各种莫名其妙的错误,比如
显示我现在最小sdk版本是1?wtf。所以我直接用as打开了flutter中的android项目, 啥毛病也没有了
2、取消广播
就android端实现而言,获取电量是通过广播获取的, 所以要在生命周期中加入取消的动作,flutter页面被销毁时调用了dispose方法,结果我得到的是一堆报错,说明没有调用unregisterReceiver,天地良心,我确实写了,但flutter并没有为我调用dispose。
原因是这样的, 我在flutter使用hot reload,直接在首页调用了(整个应用只有一个页面)直接按back键退出时,可能是reload的问题,导致了dispose不调用。我把代码修改成了这个样子。
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:platform_specific/battery_manager.dart';
void main() => runApp(Main());
class Main extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Hello(),
);
}
}
class Hello extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: Center(
child: RaisedButton(
child: Text('Hello'),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) {
return MyApp();
}));
},
),
),
));
}
}
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
int _battery = 0;
StreamSubscription _streamSubscription;
@override
void initState() {
_getBattery();
super.initState();
}
void _getBattery() async {
int battery = await BatteryManager.getInstance().getBatteryLevel();
_setBattery(battery);
_streamSubscription =
BatteryManager.getInstance().setOnBatteryListener(_setBattery);
}
void _setBattery(int battery) {
setState(() {
_battery = battery;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Battery: $_battery'),
),
);
}
@override
void dispose() {
_streamSubscription?.cancel();
super.dispose();
}
}
网友评论