1. 前言
在文章Flutter框架分析(八)-Platform Channel中,我們分析了MethodChannel的原理和結構,並詳細講解了與其相關的一些核心類,例如MethodCallHandler和MethodCodec等,本文主要講解使用MethodChannel的示例。
2. 使用流程
MethodChannel可用於Flutter呼叫native的方法,也可用於native呼叫Flutter的方法,所以接下來將分別分析這兩種使用流程。
2.1 Flutter呼叫native方法
流程如下:
1)native端建立某channel name的MethodChannel。
2)native端使用setMethodCallHandler函式,設定該MethodChannel的MethodCallHandler。
3)Flutter端建立該channel name的MethodChannel。
4)Flutter端使用該MethodChannel通過invokeMethod函式向native端傳送方法呼叫,傳遞引數為方法名和方法引數。
5)native端剛剛註冊的MethodCallHandler收到傳送的訊息,在onMethodCall中處理訊息,通過reply函式進行回覆。
6)Flutter端處理該回復。
Flutter端關鍵程式碼如下:
class _MyHomePageState extends State<MethodChannelWidget> {
static const nativeChannel = const MethodChannel('flutter2/MethodChannel');
int _counter = 0;
void _incrementCounter() async {
setState(() {
_counter++;
});
String result = await nativeChannel.invokeMethod('getJavaMethod', "123");
print('methodChannelTest _incrementCounter: + $result');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("method channel test"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
複製程式碼
native端關鍵程式碼如下:
class MethodChannelActivity : FlutterActivity() {
private var mFlutter2MethodChannel: MethodChannel? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
Log.d("FirstNativeActivity", "configureFlutterEngine")
initChannel(flutterEngine)
}
private fun initChannel(flutter2Engine: FlutterEngine) {
mFlutter2MethodChannel = MethodChannel(flutter2Engine.dartExecutor, "flutter2/MethodChannel")
mFlutter2MethodChannel!!.setMethodCallHandler(MethodCallHandler {call, result ->
Log.e("methodChannelTest", "onMethodCall method:" + call.method)
if ("getJavaMethod" == call.method) {
result.success("success ")
Log.e("methodChannelTest", "success:" + call.arguments())
} else {
result.success(" unKnow method")
}
})
}
companion object {
fun startActivity(activity: Activity) {
val intent = Intent(activity, MethodChannelActivity::class.java)
activity.startActivity(intent)
}
}
}
複製程式碼
2.2 native呼叫Flutter端方法
流程如下:
1) Flutter端建立channel name的MethodChannel。
2) Flutter端使用setMethodCallHandler函式,設定該MethodChannel的Handler函式。
3) native端建立某channel name的MethodChannel。
4) native端使用該MethodChannel通過invokeMethod函式向Flutter端傳送訊息,傳遞引數為方法名和方法引數。
5) Flutter端剛剛註冊的Handler收到傳送的訊息,並處理訊息,然後通過reply函式進行回覆。
6) native端處理該回復。
Flutter端關鍵程式碼如下:
class _MyHomePageState extends State<MethodChannelWidget> {
static const nativeChannel = const MethodChannel('flutter2/MethodChannel');
int _counter = 0;
@override
void initState() {
nativeChannel.setMethodCallHandler(flutterMethod);
super.initState();
}
Future<dynamic> flutterMethod(MethodCall methodCall) async {
switch (methodCall.method) {
case 'flutterMethod':
print('methodChannelTest 原生Android呼叫了flutterMethod方法 引數是:'+methodCall.arguments);
return "hahaha";
}
}
}
複製程式碼
native端關鍵程式碼如下:
class MethodChannelActivity : FlutterActivity() {
private var mFlutter2MethodChannel: MethodChannel? = null
private var mHandler: Handler? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mHandler = Handler()
mHandler!!.postDelayed( {
Log.e("methodChannelTest", "getJavaMethod invokeFlutterMethod_toAllFlutter")
invokeFlutterMethod_toAllFlutter()
} , 3000)
}
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
Log.d("FirstNativeActivity", "configureFlutterEngine")
initChannel(flutterEngine)
}
private fun initChannel(flutter2Engine: FlutterEngine) {
mFlutter2MethodChannel = MethodChannel(flutter2Engine.dartExecutor, "flutter2/MethodChannel")
}
private fun invokeFlutterMethod_toAllFlutter() {
if (mFlutter2MethodChannel != null) {
mFlutter2MethodChannel!!.invokeMethod("flutterMethod", "我是原生Android,我將引數傳遞給Flutter裡面的一個方法", object : MethodChannel.Result {
override fun success(o: Any?) {
Log.d("methodChannelTest", "flutterMethod:$o")
}
override fun error(s: String, s1: String?, o: Any?) {}
override fun notImplemented() {}
})
}
}
companion object {
fun startActivity(activity: Activity) {
val intent = Intent(activity, MethodChannelActivity::class.java)
activity.startActivity(intent)
}
}
}
複製程式碼
3. 小結
本文主要介紹了MethodChannel的使用流程,並列舉了一個使用MethodChannel的示例。