Flutter框架分析-MethodChannel

1,881 阅读2分钟

1. 前言

在文章Flutter框架分析(八)-Platform Channel中,我们分析了MethodChannel的原理和结构,并详细讲解了与其相关的一些核心类,例如MethodCallHandlerMethodCodec等,本文主要讲解使用MethodChannel的示例。

2. 使用流程

MethodChannel可用于Flutter调用native的方法,也可用于native调用Flutter的方法,所以接下来将分别分析这两种使用流程。

2.1  Flutter调用native方法

流程如下:

1)native端创建某channel name的MethodChannel

2)native端使用setMethodCallHandler函数,设置该MethodChannelMethodCallHandler

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函数,设置该MethodChannelHandler函数。

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的示例。