美文网首页Flutter相关
Flutter怎么与原生交互

Flutter怎么与原生交互

作者: 码农朱同学 | 来源:发表于2022-08-01 17:48 被阅读0次

Flutter与原生交互

flutter端:


///flutter和原生相互传递数据
class FlutterMethodChannel {
  ///与原生互联的key
  final String methodChannelKey = "com.xxxxxx.channel";

  factory FlutterMethodChannel() => _getInstance();
  static FlutterMethodChannel? _instance;

  static FlutterMethodChannel _getInstance() {
    _instance ??= FlutterMethodChannel._internal();
    return _instance!;
  }

  late MethodChannel _channel;

  FlutterMethodChannel._internal() {
    _channel = MethodChannel(methodChannelKey);
  }

  ///获取channel对象
  MethodChannel get channel => _channel;

  /// 调用原生方法,不带参数
  callNative(String methodType) {
    callNativeWithMap(methodType, {});
  }

  /// 调用原生方法,带参数
  callNativeWithMap(String methodType, Map map) {
    try {
      if (map.isEmpty) {
        _channel.invokeMethod<String>(methodType);
      } else {
        _channel.invokeMethod<String>(methodType, map);
      }
    } catch (e) {}
  }

  Future<dynamic> callNativeFuture(String methodType, Map map) async {
    if (map.isEmpty) {
      return await _channel.invokeMethod(methodType);
    } else {
      return await _channel.invokeMethod(methodType, map);
    }
  }

  startWebView(String url) {
    _channel.invokeMethod("startWeb", {"url": url});
  }

  //初始化极光推送
  initThirdSDK() {
    if (_channel != null) {
      _channel.invokeMethod(MethodTypeConfig.InitThirdSDK);
    }
  }

  //获取推送通知是否开启 方法
  getAppVersion(Function(String) cb) async {
    try {
      var result =
          await _channel.invokeMethod<String>(MethodTypeConfig.GetAppVersion);
      cb(result!);
    } catch (e) {
      return cb("1.0.0");
    }
  }

  //获取推送通知是否开启 方法
  getAppNotice(Function(String) click) async {
    try {
      var result =
          await _channel.invokeMethod<String>(MethodTypeConfig.GetAppNotice);
      click(result!);
    } catch (e) {
      return click("未开启");
    }
  }

  //通知设置
  pushSystemNotice() {
    if (_channel != null) {
      _channel.invokeMethod(MethodTypeConfig.PushSystemNotice);
    }
  }

  //更新
  versionCheckUpdate(bool doAfter, bool activeTrigger) {
    if (_channel != null) {
      Map _map = {};
      _map["doAfter"] = doAfter;
      _map["activeTrigger"] = activeTrigger;
      _channel.invokeMethod(MethodTypeConfig.VersionCheckUpdate, _map);
    }
  }
}
//调用原生方法的类别
class MethodTypeConfig {
  static const String PushSystemNotice = "push_system_notice"; //跳转到设置页面 开启推送
  static const String GetAppVersion = "get_app_version"; //获取推送通知是否开启
  static const String GetAppNotice = "get_app_notice"; //获取推送通知是否开启
  static const String FinishParam = "finish_flutter"; //完全关闭flutter页面
  static const String InitThirdSDK = "init_third_sdk"; //初始化第三方SDK
  static const String VersionCheckUpdate = "version_check_update"; //版本检查升级
}

Andoid端:

class MethodType {
    companion object {
        const val PushSystemNotice = "push_system_notice"   //跳转到设置页面 开启推送
        const val GetAppVersion = "get_app_version"   //获取应用版本号。
        const val GetAppNotice = "get_app_notice"   //获取应用通知是否开启方法。
        const val FinishParam = "finish_flutter"//完全关闭flutter页面
        const val InitThirdSDK = "init_third_sdk"; //初始化第三方SDK
        const val VersionCheckUpdate = "version_check_update";//版本检查升级
        const val StartWeb = "startWeb";//版本检查升级
    }
}

/**
 * @author zhxh
 * @time 2021/8/9
 * 原生与flutter的互调
 */
class NativeMethodChannel(var context: Context, messenger: BinaryMessenger) :
    MethodChannel.MethodCallHandler {
    val TAG = "NativeMethodChannel"
    private var channel: MethodChannel = MethodChannel(messenger, "com.xxxxxx.channel")

    init {
        channel.setMethodCallHandler(this)
    }

    fun sendLoginData(data: Any) {
        channel.invokeMethod("login", data)
    }

    fun loginOut() {
        channel.invokeMethod("loginOut", "")
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        try {
            when (call.method) {
                //通知设置 方法
                MethodType.PushSystemNotice -> {
                    NoticeUtils.toSystemPushSwitch(context)
                }
                //获取版本名
                MethodType.GetAppVersion -> {
                    val v = AppInfo.versionName
                    result.success(v)
                }
                //获取是否开启通知权限 方法
                MethodType.GetAppNotice -> {
                    val notificationStatus = NoticeUtils.getNotificationStatus(context)
                    result.success(if (notificationStatus) "已开启" else "未开启")
                }
                MethodType.FinishParam -> {
                    (context as? Activity)?.let {
                        it.finish()
                    }
                }
                //版本检查升级
                MethodType.VersionCheckUpdate -> {
                    val doAfter: Boolean = call.argument("doAfter") ?: false
                    val activeTrigger: Boolean = call.argument("activeTrigger") ?: false
                    UpgradeTask.getInstance(context).beginUpgradeTask(doAfter, activeTrigger)
                }
                //初始化第三方SDK
                MethodType.InitThirdSDK -> {
                    AppInfo.application.initThirdSDK()
                }
                MethodType.StartWeb -> {
                    call.argument<String>("url")?.let {
                        WebViewUtils.startActivity(it)
                    }
                }
            }

        } catch (e: Exception) {
            print("NetMethodChannel:onMethodCall+$e")
        }
    }
}

open class BaseFlutterActivity : FlutterActivity() {
    lateinit var channel: NativeMethodChannel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        FlutterAppManager.getInstance().addActivity(this)
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        channel = NativeMethodChannel(this,flutterEngine.dartExecutor)
    }

    override fun onDestroy() {
        super.onDestroy()
        FlutterAppManager.getInstance().removeActivity(this)
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.close_enter, R.anim.close_exit)
    }

    @TargetApi(17)
    override fun getResources(): Resources {
        val resources = super.getResources();
        val configContext = createConfigurationContext(resources.configuration)
        return configContext.resources.apply {
            configuration.fontScale = 1.0f
            displayMetrics.scaledDensity = displayMetrics.density * configuration.fontScale
        }
    }
}

原生调用flutter方法:

class _AppContentState extends State<AppContent> {
  @override
  void initState() {
    super.initState();
    FlutterMethodChannel().channel.setMethodCallHandler(_methodCallHandler);
  }

  Future<dynamic> _methodCallHandler(MethodCall call) async {
    switch (call.method) {
      case "login":
        AppManager().processLoginSuccess(context, call.arguments);
        break;
      case "loginOut":
        AppManager().processLoginOut(context);
        break;
      case "flutterPop":
        RouterUtil.pop();
        break;
    }
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    //静默登录
    AppManager().processSilentLogin(context);
  }

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      navigatorKey: navigatorKey,
      title: '应用名称',
      debugShowCheckedModeBanner: false,
      initialRoute: RouterConstant.navigation_page,
      getPages: RouterUtil.routers,
      builder: EasyLoading.init(),
    );
  }
}

NativeMethodChannel类中的方法:

    MethodChannel.MethodCallHandler {
    val TAG = "NativeMethodChannel"
    private var channel: MethodChannel = MethodChannel(messenger, "com.puze.channel")

    init {
        channel.setMethodCallHandler(this)
    }

    fun sendLoginData(data: Any) {
        channel.invokeMethod("login", data)
    }

    fun loginOut() {
        channel.invokeMethod("loginOut", "")
    }

调用:

class FundFlutterActivity : BaseFlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        UtilsActivityBar.setImmersionBar(this, false, true, true)
    }


    @Subscribe
    fun onMainEvent(data: String) {
        if (data.equals("loginout")) {
            UserInfo.token = ""
            channel.loginOut()
        } else {
            val map = Gson().fromJson(data, Map::class.java)
            (map["token"] as? String)?.let { token ->
                UserInfo.token = token
            }
            channel.sendLoginData(map)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}

相关文章

网友评论

    本文标题:Flutter怎么与原生交互

    本文链接:https://www.haomeiwen.com/subject/ukzlwrtx.html