如何使用API​​从Flutter插件启动活动 [英] How to start an activity from flutter plugin using an API

查看:65
本文介绍了如何使用API​​从Flutter插件启动活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在制作Flutter插件,并且尝试在Android上运行Kotlin代码.问题是,此代码运行的方法尝试在没有意图上的 FLAG_ACTIVITY_NEW_TASK 标志的情况下启动活动.问题在于它在尝试实例化方法本身内部的实例时,也没有办法给它一个 intent实例.该方法希望从存储在UI上并从中调用的按钮或其他方法调用.但是,由于是从Flutter插件中的 onMethodCall 方法调用的,因此它似乎不起作用.我尝试了许多解决方法,例如在Activity中添加方法,并在从flutter插件类中调用它时在其中运行代码.我也尝试过使用UIThread,也没有运气.任何解决方法?

So I am making a Flutter plugin and I am attempting to run Kotlin code on Android. The problem is, this code runs a method which attempts to start an activity without the FLAG_ACTIVITY_NEW_TASK flag on the intent. The problem with this is that it also does NOT have a way to give it an intent instance as it attempts to instantiate an instance inside the method itself. The method expects to be called from a button or other method that is stored on the UI and called from it. However, since it is called from the onMethodCall method in the Flutter plugin, it does not seem to work. I have attempted many workarounds such as adding a method inside the Activity and running the code inside while calling it from the flutter plugin class. I have also tried using the UIThread and no luck either. Any workarounds?

注意:由于未隐藏此API,因此我未提供任何代码.应该只知道我正在通过 onMethodCall 事件运行代码.

Note: I have not provided any code due to keeping this API hidden. It should only be known that I am running the code from the onMethodCall event.

错误:从Activity上下文外部调用startActivity()需要FLAG_ACTIVITY_NEW_TASK标志.这真的是您想要的吗?

推荐答案

您可以扩展插件以在插件类中实现 ActivityAware ,当您实现它时,会得到几个回调,这些回调可以您当前的活动.像这样:

You can extend your plugin to implement ActivityAware in your plugin class, when you implement it, you get a couple of callbacks that gives you the current activity. Like this :

lateinit activity: Activity? = null
override fun onDetachedFromActivity() {
    activity = null
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    activity = binding.activity
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    activity = binding.activity
  }

  override fun onDetachedFromActivityForConfigChanges() {
    activity = null
  }

之后,您可以从分配的活动变量中启动startActivity.

After that you can just startActivity from the assigned activity variable.

如果您需要进一步的帮助,请告诉我.

Let me know if you need further help.

这篇关于如何使用API​​从Flutter插件启动活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆