Flutter and native interactive learning

 

PlatformChannel Features

PlatformChannel into BasicMessageChannel, MethodChannel and EventChannel three. The main purpose of each of which are as follows:

  • BasicMessageChannel: for transmitting data. Flutter and native resources project is not shared, icons and other resources can be obtained through the Native project BasicMessageChannel.
  • MethodChannel: delivery method call. Flutter initiative to call a method of Native and obtain the corresponding return value. Such as access to electricity system, launch Toast and other system call API, this can be done.
  • EventChannel: pass the event. Here is a Native event notification to Flutter. For example Flutter need to monitor network conditions, this time MethodChannel can not be qualified for this needs. EventChannel can be a listening Flutter handed Native, Native done listening to the network broadcast, when the broadcast is received by means of registered listeners EventChannel call Flutter, Flutter completion of the event notification.

In fact, we can see that both transfer method or transfer events are passing data on its nature, but some logic upper package is different.

 

flutter

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ChannelPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _ChannelPageState();
  }
}

class _ChannelPageState extends State<ChannelPage> {

  //获取到插件与原生的交互通道
  static const jumpPlugin = const MethodChannel('com.example.jump/plugin');
  static const counterPlugin = const EventChannel('com.example.counter/plugin');
  var _count;
  StreamSubscription _counterSub;
  @override
  void initState() {
    super.initState();
    _startCounterPlugin();
  }

  @override
  void dispose() {
    super.dispose();
    _endCounterPlugin();
  }
  void _startCounterPlugin(){
    if(_counterSub == null){
      _counterSub =  counterPlugin.receiveBroadcastStream().listen(_onCounterEvent,onError: _onCounterError);
    }
  }

  void _endCounterPlugin(){
    if(_counterSub != null){
      _counterSub.cancel();
    }
  }
  void _onCounterError(Object error) {
    setState(() {
      _count = "计时器异常";
      print(error);
    });
  }

  void _onCounterEvent(Object event) {
    setState(() {
      _count = event;
    });
  }


  Future<Null> _jumpToNative() async {
    String result = await jumpPlugin.invokeMethod('oneAct');

    print(result);
  }

  Future<Null> _jumpToNativeWithValue() async {

    Map<String, String> map = { "flutter": "这是一条来自flutter的参数" };

    String result = await jumpPlugin.invokeMethod('twoAct', map);

    print(result);
  }


  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Channel"),
        centerTitle: true,
      ),
      body: new Center(
          child: new ListView(
            children: <Widget>[
              new Padding(
                padding: const EdgeInsets.only(left: 10.0, top: 10.0, right: 10.0),
                child: new RaisedButton(
                    textColor: Colors.black,
                    child: new Text('跳转到原生界面'),
                    onPressed: () {
                      _jumpToNative();
                    }),
              ),
              new Padding(
                padding: const EdgeInsets.only(
                    left: 10.0, Top: 10.0, right: 10.0 ),
                Child: new new RaisedButton ( 
                    textColor: Colors.black, 
                    Child: new new the Text ( 'jump to the native interface (parameters)' ), 
                    onPressed: () { 
                      _jumpToNativeWithValue (); 
                    }), 
              ), 

              new new the padding ( 
                padding: const EdgeInsets.only ( 
                    left: 10.0, Top: 10.0, right: 10.0 ), 
                Child: new new the Text ( 'this is the data a transmitted from a native over: $ _ COUNT' ), 
              ), 


            ], 
          ) 
      ), 
    );
  }
}

android

package com.example.flutter_app.plugins;

import android.app.Activity;
import android.util.Log;


import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.PluginRegistry;


public class FlutterPluginCounter implements EventChannel.StreamHandler {

    public static String CHANNEL = "com.example.counter/plugin";

    static EventChannel channel;

    private Activity activity;


    private FlutterPluginCounter(Activity activity) {
        this.activity = activity;
    }

    public static void registerWith(PluginRegistry.Registrar registrar) {
        channel = new EventChannel(registrar.messenger(), CHANNEL);
        FlutterPluginCounter instance = new FlutterPluginCounter(registrar.activity());
        channel.setStreamHandler(instance);
       // basicMessageChannel = new BasicMessageChannel<String> ("foo", StringCodec.INSTANCE);
    }

    @Override
    public void onListen(Object o, final EventChannel.EventSink eventSink) {
        eventSink.success(123456);
    }

    @Override
    public void onCancel(Object o) {
        Log.i("FlutterPluginCounter", "FlutterPluginCounter:onCancel");
    }

}
package com.example.flutter_app.plugins;

import android.app.Activity;
import android.content.Intent;


import com.example.flutter_app.OneActivity;
import com.example.flutter_app.TwoActivity;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.PluginRegistry;

public class FlutterPluginJumpToAct implements MethodCallHandler {

    public static String CHANNEL = "com.example.jump/plugin";

    static MethodChannel channel;

    private Activity activity;

    private FlutterPluginJumpToAct(Activity activity) {
        this.activity = activity;
    }

    public static void registerWith(PluginRegistry.Registrar registrar) {
        channel = new MethodChannel(registrar.messenger(), CHANNEL);
        FlutterPluginJumpToAct instance = new FlutterPluginJumpToAct(registrar.activity());
        //setMethodCallHandler在此通道上接收方法调用的回调
        channel.setMethodCallHandler(instance);
    }

    @Override
    public  void onMethodCall (MethodCall Call, MethodChannel.Result Result) { 

        // available through MethodCall method name and parameters, and then find the corresponding service platform, in this case made of two jump operations 

        // receive instructions from the flutter oneAct 
        IF (call.method.equals ( "oneAct" )) { 

            // Jump to the Activity 
            the Intent Intent = new new the Intent (Activity, OneActivity. class ); 
            activity.startActivity (Intent); 

            // returned to flutter parameter 
            result. Success ( "Success" ); 
        } 
        // receiving instructions from the flutter twoAct 
        the else  IF (call.method.equals ( "twoAct" )) { 

            // resolution parameters
            = Call.argument text String ( "Flutter" ); 

            // with the specified parameter to jump to the Activity 
            the Intent Intent = new new the Intent (Activity, TwoActivity. Class ); 
            intent.putExtra (TwoActivity.VALUE, text); 
            activity.startActivity (Intent ); 

            // returns to the parameter flutter of 
            result.success ( "Success" ); 
        } 
        the else { 
            result.notImplemented (); 
        } 
    } 

}
package com.example.flutter_app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class OneActivity extends Activity implements View.OnClickListener {

    private Button mGoFlutterBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_one);

        mGoFlutterBtn = findViewById(R.id.go_flutter);

        mGoFlutterBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.go_flutter:
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                break;
        }
    }

}
package com.example.flutter_app;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TwoActivity extends Activity{

    private TextView mTextView;

    public static final String VALUE = "value";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_two);

        mTextView = findViewById(R.id.text);

        String text = getIntent().getStringExtra(VALUE);

        mTextView.setText(text);

    }

}
package com.example.flutter_app;

import android.os.Bundle;

import com.example.flutter_app.plugins.FlutterPluginCounter;
import com.example.flutter_app.plugins.FlutterPluginJumpToAct;

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);
    FlutterPluginJumpToAct.registerWith(this.registrarFor(FlutterPluginJumpToAct.CHANNEL));//注册
    FlutterPluginCounter.registerWith(this.registrarFor(FlutterPluginCounter.CHANNEL));//注册

  }
}

effect:

 

Guess you like

Origin www.cnblogs.com/loaderman/p/11353174.html