老孟导读:这是一个读者面试时被问到的问题,这个问题前段时间我也在VIP交流群和大家一起探讨过。 这个问题涉及引擎的相关知识,如果不了解相关知识,很难回答正确,因为不管说调用几次都是错误的,下面来看一下
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.button).setOnClickListener {
startActivity(Intent(this,FlutterActivity::class.java))
}
}
}
void main() {
runApp(MyApp());
print('===main====');
}
val flutterEngine = FlutterEngine(this)
flutterEngine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
FlutterEngineCache
.getInstance()
.put("engine_id",flutterEngine)
findViewById<Button>(R.id.button).setOnClickListener {
startActivity(
FlutterActivity
.withCachedEngine("engine_id")
.build(this)
)
}
void main() {
runApp(MyApp());
print('===main====');
}
void main1() {
runApp(MyApp());
print('===main1====');
}
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val flutterEngine = FlutterEngine(this)
flutterEngine.dartExecutor.executeDartEntrypoint(
// DartExecutor.DartEntrypoint.createDefault()
createEntrypoint()
)
FlutterEngineCache
.getInstance()
.put("engine_id",flutterEngine)
findViewById<Button>(R.id.button).setOnClickListener {
startActivity(
FlutterActivity
.withCachedEngine("engine_id")
.build(this)
)
}
}
fun createEntrypoint(): DartExecutor.DartEntrypoint {
val flutterLoader: FlutterLoader = FlutterInjector.instance().flutterLoader()
return DartExecutor.DartEntrypoint(flutterLoader.findAppBundlePath(),"main1")
}
}
总结
-
入口函数 执行的次数取决于 引擎的启动次数,每启动一次引擎,执行一次入口函数 。
- 引擎的入口函数是可以指定的,默认是 main。