简体   繁体   English

使用缓存引擎启动 FlutterActivity 子类

[英]Start a FlutterActivity subclass using a cached engine

I'm currently adding a view developed using Flutter to an existing Android app.我目前正在将使用 Flutter 开发的视图添加到现有的 Android 应用程序中。 I have been following the tutorials found in the Flutter website and decided to used a cached engine in order to minimize the delay that users may experience when navigating to the Flutter portion of the app.我一直在关注 Flutter 网站上的教程,并决定使用缓存引擎,以最大限度地减少用户在导航到应用程序的 Flutter 部分时可能遇到的延迟。 In order to do so, you must launch your Flutter activity like为此,您必须启动 Flutter 活动,例如

startActivity(
    FlutterActivity
      .withCachedEngine("my_engine_id")
      .build(this) // this is a Context

) )

After a while I need to wirte a method channel to communicate from the Flutter portion of the app back to the Android host app, so I followed the instructions found in another of Flutter's tutorials , where it is shown that the activity that implements the channel must extend FlutterActivity .过了一会儿,我需要编写一个方法通道来从应用程序的 Flutter 部分与 Android 主机应用程序进行通信,所以我按照 Flutter 的另一个教程中的说明进行操作,其中显示实现通道的活动必须扩展FlutterActivity

So my problem is that I'm not sure how to initialize this activity using a cached engine, since I obviously can't use FlutterActivity.withCachedEngine anymore.所以我的问题是我不确定如何使用缓存引擎来初始化这个活动,因为我显然不能再使用FlutterActivity.withCachedEngine了。 Has anyone solved this already?有没有人已经解决了这个问题?

After looking at FlutterActivity documentation I found the provideFlutterEngine method .查看FlutterActivity文档后,我找到了provideFlutterEngine 方法 The doc description clearly states that:文档描述清楚地指出:

This hook is where a cached FlutterEngine should be provided, if a cached FlutterEngine is desired.如果需要缓存的 FlutterEngine,这个钩子就是应该提供缓存的 FlutterEngine 的地方。

So the final implementation of my class looks like this now所以我的 class 的最终实现现在看起来像这样

class MyActivity : FlutterActivity() {

    override fun provideFlutterEngine(context: Context): FlutterEngine? =
        FlutterEngineCache.getInstance().get(FlutterConstants.ENGINE_ID)

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "my-channel")
            .setMethodCallHandler { call, result ->
                if (call.method == "my-method") {
                    myMethod()
                    result.success(null)
                } else {
                    result.notImplemented()
                }
            }
    }

    private fun myMethod() {
        // Do native stuff
    }

}

And I simply start it writing startActivity(Intent(this, MyActivity::class.java))我只是开始写startActivity(Intent(this, MyActivity::class.java))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM