Android 原生项目集成flutter模块 混编

1.FlutterView

结合Lifecycle自定义的view



import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import io.flutter.embedding.android.FlutterView
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor

class FlutterLifecycleView : FlutterView, LifecycleObserver {

    companion object {
        fun createEngine(
            context: Context,
            flutterEngineId: String,
            dartEntrypointFunctionName: String = ""
        ): FlutterEngine {
            var engine = FlutterEngineCache.getInstance().get(flutterEngineId)
            if (engine == null) {
                engine = FlutterEngine(context.applicationContext)
                val createDefault = if (dartEntrypointFunctionName == "") {
                    DartExecutor.DartEntrypoint.createDefault()
                } else {
                    DartExecutor.DartEntrypoint(
                        App.instance!!.flutterLoader.findAppBundlePath(),
                        dartEntrypointFunctionName
                    )
                }
                engine.dartExecutor.executeDartEntrypoint(createDefault)
                FlutterEngineCache.getInstance().put(flutterEngineId, engine)
            }
            return engine
        }
    }

    var mLifecycle: Lifecycle? = null
    var mEngine: FlutterEngine? = null

    /**
     *
     * constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    }
     */
    constructor(context: Context, engine: FlutterEngine, lifecycle: Lifecycle) : super(context) {
        lifecycle.addObserver(this)
        attachToFlutterEngine(engine)
        mLifecycle = lifecycle
        mEngine = engine
        mEngine?.lifecycleChannel?.appIsInactive()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        mEngine?.lifecycleChannel?.appIsResumed()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        mEngine?.lifecycleChannel?.appIsPaused()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        mEngine?.lifecycleChannel?.appIsDetached()
        detachFromFlutterEngine()
        mLifecycle?.removeObserver(this)
    }
}

在activity上使用

import android.os.Bundle
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import io.flutter.embedding.android.FlutterView


class MainActivity : AppCompatActivity() {

    private val flutterEngineId = "flutterEngineId"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        createFlutterView()
    }

    private fun createFlutterView(): FlutterView {
        val engine = FlutterLifecycleView.createEngine(this, flutterEngineId)
        val flutterView = FlutterLifecycleView(this, engine, lifecycle)
        val params = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        addContentView(flutterView, params)
        return flutterView
    }
}

在application初始化flutter

import android.app.Application
import io.flutter.FlutterInjector
import io.flutter.embedding.engine.loader.FlutterLoader

class App : Application() {
    lateinit var flutterLoader: FlutterLoader

    companion object {
        var instance: App? = null
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        /**
         *
        //        FlutterMain.startInitialization(this)
        //        FlutterLoader.getInstance().startInitialization(this)
         */
        flutterLoader = FlutterInjector.Builder()
            .build()
            .flutterLoader()
        flutterLoader.startInitialization(this)
    }
}

在setting.gradle上增加


setBinding(new Binding([gradle: this]))
evaluate(new File(
        settingsDir.parentFile,
        'module_flutter/.android/include_flutter.groovy'
))

原生项目同级目录下执行 以下语句
flutter create -t module module_flutter
androidx 项目也可以使用 flutter create --androidx -t module module_flutter

最终效果

2. FlutterFragment

import io.flutter.embedding.android.FlutterFragment

class BaseFlutterFragment : FlutterFragment() {

    companion object {
        fun create(): FlutterFragment {
//            return createDefault()
            return withNewEngine()
                    //可写可不写
                .appBundlePath(App.instance!!.flutterLoader.findAppBundlePath())
                    //指定加载的方法名字
                .dartEntrypoint("mai22")
                    //路由名字对于dart里面的 window.defaultRouteName
                .initialRoute("route2")
                .build()
        }
    }
}

 在activity上使用

import android.os.Bundle
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import io.flutter.embedding.android.FlutterView


class MainActivity : AppCompatActivity() {

    private val flutterEngineId = "flutterEngineId"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//        createFlutterView()
        supportFragmentManager.beginTransaction()
            .replace(R.id.ffContainer, BaseFlutterFragment.create())
            .commit()
    }
}

参考文献:Android 原生项目集成flutter模块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落后程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值