Flutter与Android原生消息交互

Flutter与Android原生消息交互

///以下为自己学习记录,仅供参考

MedthodChannel

原生实现MedthodChannel

import android.content.Context;
import android.widget.Toast;
import androidx.annotation.NonNull;
import io.flutter.Log;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class CusMethodChannelHandler implements MethodChannel.MethodCallHandler {

    private Context context;

    public CusMethodChannelHandler(Context context){
        this.context=context;

    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        Toast.makeText(context,call.method,Toast.LENGTH_SHORT).show();
        //方法名,原生与dart保持一致
        if(call.method.equals("sendInfoToAndroid")){
           String message=  call.argument("message");
            Log.d("flutter传过来的值==========",message);
            if (TextUtils.isEmpty(message)) {
                /**
                 * 错误返回
                 */
                result.error("Data is Null",null,null);
            }else {
                android.util.Log.d("flutter传过来的值==========", "onMethodCall: "+message);
                /**
                 * 成功返回
                 */
                result.success("is ok");
            }
        }

    }
}

原生注册MethodChannel

import android.os.Bundle;
import androidx.annotation.Nullable;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.MethodChannel;


public class pushActivity extends FlutterActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MethodChannel channel=new MethodChannel(getFlutterEngine().getDartExecutor(),"你的channelName");
        channel.setMethodCallHandler(new CusMethodChannelHandler(this));
    }

}

flutter端代码

MethodChannel _channel = MethodChannel("你的channelName");
  Future<String> sendInfoToAndroid(String message) async {
    final String version = await _channel.invokeMethod('sendInfoToAndroid',{"message":message});
    return version;
  }

EventChannel

原生端实现EventChannel
import android.util.Log;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.EventChannel;

public class CusEventChannelHandler implements EventChannel.StreamHandler {
static EventChannel.EventSink eventSink;
public static String CHANNEL = “sendToFlutter”;

static EventChannel channel;

public static void registerWith(BinaryMessenger messenger) {
    channel = new EventChannel(messenger, CHANNEL);
    CusEventChannelHandler flutterPluginEventTest = new CusEventChannelHandler();
    channel.setStreamHandler(flutterPluginEventTest);
}

static void sendMessageToFlutter(String messgae){
    if(null!=eventSink){
        eventSink.success(messgae);
    }
}

@Override
public void onListen(Object arguments, EventChannel.EventSink events) {
    Log.d("listen===========","他来了");
    eventSink = events;

}

@Override
public void onCancel(Object arguments) {

}

}

注册EventChannel
import android.os.Bundle;
import androidx.annotation.Nullable;
import io.flutter.embedding.android.FlutterActivity;

public class pushActivity extends FlutterActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CusEventChannelHandler.registerWith(getFlutterEngine().getDartExecutor());
}

}

flutter端代码

static const EventChannel _eventChannel = const EventChannel("sendToFlutter");

  StreamSubscription _subscription = null;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _subscription = _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
    getData();

  }

  void _onEvent(Object event) {
    print('Flutter - 发送过来的内容: $event');


  }

  void _onError(Object error) {
    print('Flutter - 返回的错误');

  }
  
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if(null!=_subscription){
      _subscription.cancel();
    }
  }

版权声明:本文为ck600800原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。