在混合開發(fā)中,無(wú)論哪種技術(shù)手段都避免不了native與框架的互相調(diào)用牢贸。Flutter基于以下方法實(shí)現(xiàn)了與native的互相調(diào)用忙厌。
Flutter稱這種操作叫platform-specific
接下來(lái)要實(shí)現(xiàn)一個(gè)栗子、Flutter端獲取Native的電量娶视,并且當(dāng)電量改變時(shí)會(huì)通知Flutter端隘蝎。
一购啄、Flutter調(diào)用Native
使用android端實(shí)現(xiàn)
1、創(chuàng)建一個(gè)項(xiàng)目
2嘱么、在Flutter端封裝一個(gè)獲取手機(jī)電量的方法
import 'package:flutter/services.dart';
class BatteryManager {
/// MethodChannel name是一個(gè)唯一標(biāo)記狮含,不重復(fù)就好
static const platform =
const MethodChannel('org.tiny.platformspecific/battery');
/// 遠(yuǎn)程調(diào)用需要異步操作, 把這個(gè)方法生命成 async
static Future<int> getBattery() async {
// 處理異常
try {
// getBatteryLevel 是遠(yuǎn)程方法的名字
final int result = await platform.invokeMethod('getBatteryLevel');
return Future.value(result);
} on PlatformException catch (e) {
return Future.value(-1);
}
}
}
3、Android端具體實(shí)現(xiàn)
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曼振、注冊(cè)
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几迄、總結(jié)
以上完成了Flutter到Android端的調(diào)用、套路還是很簡(jiǎn)單的冰评,總結(jié)一下:
1映胁、Flutter端創(chuàng)建 MethodChannel,使用 invokeMethod 調(diào)用遠(yuǎn)程方法
2甲雅、Native端創(chuàng)建 MethodChannel解孙,實(shí)現(xiàn) MethodCallHandler
3、Native完成注冊(cè)
二抛人、Flutter對(duì)Native設(shè)置監(jiān)聽
因?yàn)殡娏渴且粋€(gè)不斷變化的值弛姜,所以就需要Flutter對(duì)Native的監(jiān)聽這時(shí)候使用MethodChannel是不行的,所以有請(qǐng)下一個(gè)EventChannel妖枚,還是先上代碼廷臼。
1、Flutter端創(chuàng)建
參照之前的Flutter代碼進(jìn)行了修改,使電量管理成為一個(gè)單例
import 'dart:async';
import 'package:flutter/services.dart';
class BatteryManager {
static BatteryManager _instance;
final MethodChannel _methodChannel;
final EventChannel _eventChannel;
StreamSubscription _eventStreamSubscription;
/// _私有構(gòu)造方法
BatteryManager._(this._methodChannel, this._eventChannel);
/// 創(chuàng)建單例
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);
}
}
/// 監(jiān)聽電量的變化
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 代碼離奇報(bào)錯(cuò)
我在android studio中編輯代碼的時(shí)候掠剑,出現(xiàn)了各種莫名其妙的錯(cuò)誤,比如
顯示我現(xiàn)在最小sdk版本是1郊愧?wtf。所以我直接用as打開了flutter中的android項(xiàng)目井佑, 啥毛病也沒(méi)有了
2属铁、取消廣播
就android端實(shí)現(xiàn)而言,獲取電量是通過(guò)廣播獲取的躬翁, 所以要在生命周期中加入取消的動(dòng)作焦蘑,flutter頁(yè)面被銷毀時(shí)調(diào)用了dispose方法,結(jié)果我得到的是一堆報(bào)錯(cuò)盒发,說(shuō)明沒(méi)有調(diào)用unregisterReceiver例嘱,天地良心,我確實(shí)寫了宁舰,但flutter并沒(méi)有為我調(diào)用dispose拼卵。
原因是這樣的, 我在flutter使用hot reload蛮艰,直接在首頁(yè)調(diào)用了(整個(gè)應(yīng)用只有一個(gè)頁(yè)面)直接按back鍵退出時(shí)腋腮,可能是reload的問(wèn)題,導(dǎo)致了dispose不調(diào)用壤蚜。我把代碼修改成了這個(gè)樣子即寡。
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();
}
}