从源码看Flutter Android端的启动流程
在Flutter中,Android端的启动流程可以概要如下:
io.flutter.app.FlutterApplication
类在AndroidManifest.xml中被声明为应用的Application类。FlutterApplication
类的onCreate
方法中初始化了Flutter引擎 (FlutterEngine
),并且可以选择将其设置为全局引擎。- 如果在
FlutterApplication
中设置了全局引擎,则可以在任何活动(Activity)中通过FlutterEngine
的getDartExecutor()
方法来运行Dart代码。 - 在
MainActivity
中,onCreate
方法创建了一个FlutterView
并将其添加到了Activity的视图层次结构中。
以下是一个简化的代码片段,展示了如何在 FlutterApplication
中初始化Flutter引擎,并在 MainActivity
中启动Flutter UI:
// FlutterApplication.java
public class FlutterApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
FlutterEngine flutterEngine = new FlutterEngine(this);
flutterEngine.getDartExecutor().executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
);
FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine);
}
}
// MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FlutterEngine flutterEngine = FlutterEngineCache.getInstance().get("my_engine_id");
if (flutterEngine == null) {
flutterEngine = new FlutterEngine(this);
flutterEngine.getDartExecutor().executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
);
}
FlutterView flutterView = new FlutterView(this, true);
flutterView.setLayoutParams(match_parent);
setContentView(flutterView);
flutterEngine.getNavigationChannel().setInitialRoute("main_route");
flutterView.attachToFlutterEngine(flutterEngine);
}
}
这个例子中,FlutterApplication
初始化了默认的Flutter引擎,并把它设置为全局可访问的。在 MainActivity
中,它获取这个引擎,创建一个 FlutterView
,并将它添加到Activity的视图层次结构中。这样,当 MainActivity
启动时,Flutter UI就会显示出来。
评论已关闭