Flutter启动流程

Flutter Embedder层启动

一、FlutterApplication 阶段:初始化Flutter Engine(和FlutterEngine不同) so库

  1. @Override
  2. @CallSuper
  3. public void onCreate() {
  4. super.onCreate();
  5. FlutterInjector.instance().flutterLoader().startInitialization(this);
  6. }

二、FlutterActivity#onCreate 阶段:初始化FlutterEngine(Java 类)和FlutterView

  1. @Override
  2. protected void onCreate(@Nullable Bundle savedInstanceState) {
  3. switchLaunchThemeForNormalTheme();
  4. super.onCreate(savedInstanceState);
  5. // 创建代理类
  6. delegate = new FlutterActivityAndFragmentDelegate(this);
  7. // 初始化FlutterEngine
  8. delegate.onAttach(this);
  9. delegate.onRestoreInstanceState(savedInstanceState);
  10. lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
  11. configureWindowForTransparency();
  12. // 初始化FlutterView
  13. setContentView(createFlutterView());
  14. configureStatusBarForFullscreenFlutterExperience();
  15. }

2.1 初始化FlutterEngine(Java 类)

  1. // FlutterActivityAndFragmentDelegate
  2. void onAttach(@NonNull Context context) {
  3. ensureAlive();
  4. if (flutterEngine == null) {
  5. // 初始化FlutterEngine
  6. setupFlutterEngine();
  7. }
  8. if (host.shouldAttachEngineToActivity()) {
  9. flutterEngine.getActivityControlSurface().attachToActivity(this, host.getLifecycle());
  10. }
  11. @VisibleForTesting
  12. void setupFlutterEngine() {
  13. // 首先,若指明缓存则使用
  14. String cachedEngineId = host.getCachedEngineId();
  15. if (cachedEngineId != null) {
  16. flutterEngine = FlutterEngineCache.getInstance().get(cachedEngineId);
  17. isFlutterEngineFromHost = true;
  18. if (flutterEngine == null) {
  19. throw new IllegalStateException(
  20. "The requested cached FlutterEngine did not exist in the FlutterEngineCache: '"
  21. + cachedEngineId
  22. + "'");
  23. }
  24. return;
  25. }
  26. // 其次,若Host(FlutterActivity或者FlutterFragment)提供则使用
  27. flutterEngine = host.provideFlutterEngine(host.getContext());
  28. if (flutterEngine != null) {
  29. isFlutterEngineFromHost = true;
  30. return;
  31. }
  32. // 最后新建一个实例
  33. flutterEngine =
  34. new FlutterEngine(
  35. host.getContext(),
  36. host.getFlutterShellArgs().toArray(),
  37. /*automaticallyRegisterPlugins=*/ false,
  38. /*willProvideRestorationData=*/ host.shouldRestoreAndSaveState());
  39. isFlutterEngineFromHost = false;
  40. }
  41. // FlutterEngine
  42. public FlutterEngine(
  43. @NonNull Context context,
  44. @Nullable FlutterLoader flutterLoader,
  45. @NonNull FlutterJNI flutterJNI,
  46. @NonNull PlatformViewsController platformViewsController,
  47. @Nullable String[] dartVmArgs,
  48. boolean automaticallyRegisterPlugins,
  49. boolean waitForRestorationData) {
  50. AssetManager assetManager;
  51. try {
  52. assetManager = context.createPackageContext(context.getPackageName(), 0).getAssets();
  53. } catch (NameNotFoundException e) {
  54. assetManager = context.getAssets();
  55. }
  56. FlutterInjector injector = FlutterInjector.instance();
  57. if (flutterJNI == null) {
  58. flutterJNI = injector.getFlutterJNIFactory().provideFlutterJNI();
  59. }
  60. this.flutterJNI = flutterJNI;
  61. // 创建DartExecutor,负责Embedder 和 Framework 通信
  62. this.dartExecutor = new DartExecutor(flutterJNI, assetManager);
  63. // 设置FlutterJNI中处理Framework消息的 PlatformMessageHandler
  64. this.dartExecutor.onAttachedToJNI();
  65. DeferredComponentManager deferredComponentManager =
  66. FlutterInjector.instance().deferredComponentManager();
  67. // 提供给Framework的平台能力封装
  68. accessibilityChannel = new AccessibilityChannel(dartExecutor, flutterJNI);
  69. deferredComponentChannel = new DeferredComponentChannel(dartExecutor);
  70. keyEventChannel = new KeyEventChannel(dartExecutor);
  71. lifecycleChannel = new LifecycleChannel(dartExecutor);
  72. localizationChannel = new LocalizationChannel(dartExecutor);
  73. mouseCursorChannel = new MouseCursorChannel(dartExecutor);
  74. navigationChannel = new NavigationChannel(dartExecutor);
  75. platformChannel = new PlatformChannel(dartExecutor);
  76. restorationChannel = new RestorationChannel(dartExecutor, waitForRestorationData);
  77. settingsChannel = new SettingsChannel(dartExecutor);
  78. systemChannel = new SystemChannel(dartExecutor);
  79. textInputChannel = new TextInputChannel(dartExecutor);
  80. if (deferredComponentManager != null) {
  81. deferredComponentManager.setDeferredComponentChannel(deferredComponentChannel);
  82. }
  83. this.localizationPlugin = new LocalizationPlugin(context, localizationChannel);
  84. if (flutterLoader == null) {
  85. flutterLoader = injector.flutterLoader();
  86. }
  87. if (!flutterJNI.isAttached()) {// 确保初始化完成
  88. // 此方法在FlutterApplication中会初始化一次
  89. flutterLoader.startInitialization(context.getApplicationContext());
  90. // 初始化一系列参数,比如:Framework 和 dart业务代码的加载
  91. // 初始化参数,通过flutterJNI.init --> FlutterJNI.nativeInit
  92. flutterLoader.ensureInitializationComplete(context, dartVmArgs);
  93. }
  94. flutterJNI.addEngineLifecycleListener(engineLifecycleListener);
  95. flutterJNI.setPlatformViewsController(platformViewsController);
  96. flutterJNI.setLocalizationPlugin(localizationPlugin);
  97. flutterJNI.setDeferredComponentManager(injector.deferredComponentManager());
  98. // It should typically be a fresh, unattached JNI. But on a spawned engine, the JNI instance
  99. // is already attached to a native shell. In that case, the Java FlutterEngine is created around
  100. // an existing shell.
  101. if (!flutterJNI.isAttached()) {
  102. attachToJni(); // 建立 Embedder和Engine连接,触发 flutterJNI.attachToNative();
  103. // --> performNativeAttach --> nativeAttach(flutterJNI);
  104. }
  105. // TODO(mattcarroll): FlutterRenderer is temporally coupled to attach(). Remove that coupling if
  106. // possible.
  107. this.renderer = new FlutterRenderer(flutterJNI);
  108. this.platformViewsController = platformViewsController;
  109. this.platformViewsController.onAttachedToJNI();
  110. this.pluginRegistry =
  111. new FlutterEngineConnectionRegistry(context.getApplicationContext(), this, flutterLoader);
  112. // Only automatically register plugins if both constructor parameter and
  113. // loaded AndroidManifest config turn this feature on.
  114. if (automaticallyRegisterPlugins && flutterLoader.automaticallyRegisterPlugins()) {
  115. GeneratedPluginRegister.registerGeneratedPlugins(this);
  116. }
  117. }

2.2 初始化FlutterView

  1. @NonNull
  2. private View createFlutterView() {
  3. return delegate.onCreateView(
  4. /* inflater=*/ null,
  5. /* container=*/ null,
  6. /* savedInstanceState=*/ null,
  7. /*flutterViewId=*/ FLUTTER_VIEW_ID,
  8. /*shouldDelayFirstAndroidViewDraw=*/ getRenderMode() == RenderMode.surface);
  9. }
  10. // FlutterActivityAndFragmentDelegate
  11. @NonNull
  12. View onCreateView(
  13. LayoutInflater inflater,
  14. @Nullable ViewGroup container,
  15. @Nullable Bundle savedInstanceState,
  16. int flutterViewId,
  17. boolean shouldDelayFirstAndroidViewDraw) {
  18. Log.v(TAG, "Creating FlutterView.");
  19. ensureAlive();
  20. if (host.getRenderMode() == RenderMode.surface) {
  21. FlutterSurfaceView flutterSurfaceView =
  22. new FlutterSurfaceView(
  23. host.getContext(), host.getTransparencyMode() == TransparencyMode.transparent);
  24. // Allow our host to customize FlutterSurfaceView, if desired.
  25. host.onFlutterSurfaceViewCreated(flutterSurfaceView);
  26. // Create the FlutterView that owns the FlutterSurfaceView.
  27. flutterView = new FlutterView(host.getContext(), flutterSurfaceView);
  28. } else {
  29. FlutterTextureView flutterTextureView = new FlutterTextureView(host.getContext());
  30. flutterTextureView.setOpaque(host.getTransparencyMode() == TransparencyMode.opaque);
  31. // Allow our host to customize FlutterSurfaceView, if desired.
  32. host.onFlutterTextureViewCreated(flutterTextureView);
  33. // Create the FlutterView that owns the FlutterTextureView.
  34. flutterView = new FlutterView(host.getContext(), flutterTextureView);
  35. }
  36. // Add listener to be notified when Flutter renders its first frame.
  37. flutterView.addOnFirstFrameRenderedListener(flutterUiDisplayListener);
  38. Log.v(TAG, "Attaching FlutterEngine to FlutterView.");
  39. flutterView.attachToFlutterEngine(flutterEngine);
  40. flutterView.setId(flutterViewId);
  41. SplashScreen splashScreen = host.provideSplashScreen();
  42. if (splashScreen != null) {
  43. Log.w(
  44. TAG,
  45. "A splash screen was provided to Flutter, but this is deprecated. See"
  46. + " flutter.dev/go/android-splash-migration for migration steps.");
  47. FlutterSplashView flutterSplashView = new FlutterSplashView(host.getContext());
  48. flutterSplashView.setId(ViewUtils.generateViewId(FLUTTER_SPLASH_VIEW_FALLBACK_ID));
  49. flutterSplashView.displayFlutterViewWithSplash(flutterView, splashScreen);
  50. return flutterSplashView;
  51. }
  52. if (shouldDelayFirstAndroidViewDraw) {
  53. delayFirstAndroidViewDraw(flutterView);
  54. }
  55. return flutterView;
  56. }

三、FlutterActivity#onStart阶段:执行Dart入口代码

  1. @Override
  2. protected void onStart() {
  3. super.onStart();
  4. lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START);
  5. if (stillAttachedForEvent("onStart")) {
  6. delegate.onStart();
  7. }
  8. }
  9. // FlutterActivityAndFragmentDelegate
  10. void onStart() {
  11. Log.v(TAG, "onStart()");
  12. ensureAlive();
  13. doInitialFlutterViewRun();
  14. flutterView.setVisibility(View.VISIBLE);
  15. }
  16. private void doInitialFlutterViewRun() {
  17. // Don't attempt to start a FlutterEngine if we're using a cached FlutterEngine.
  18. if (host.getCachedEngineId() != null) {
  19. return;
  20. }
  21. if (flutterEngine.getDartExecutor().isExecutingDart()) {
  22. // No warning is logged because this situation will happen on every config
  23. // change if the developer does not choose to retain the Fragment instance.
  24. // So this is expected behavior in many cases.
  25. return;
  26. }
  27. String initialRoute = host.getInitialRoute();
  28. if (initialRoute == null) {
  29. initialRoute = maybeGetInitialRouteFromIntent(host.getActivity().getIntent());
  30. if (initialRoute == null) {
  31. initialRoute = DEFAULT_INITIAL_ROUTE;
  32. }
  33. }
  34. @Nullable String libraryUri = host.getDartEntrypointLibraryUri();
  35. flutterEngine.getNavigationChannel().setInitialRoute(initialRoute);
  36. String appBundlePathOverride = host.getAppBundlePath();
  37. if (appBundlePathOverride == null || appBundlePathOverride.isEmpty()) {
  38. appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath();
  39. }
  40. // Configure the Dart entrypoint and execute it.
  41. DartExecutor.DartEntrypoint entrypoint =
  42. libraryUri == null
  43. ? new DartExecutor.DartEntrypoint(
  44. appBundlePathOverride, host.getDartEntrypointFunctionName())
  45. : new DartExecutor.DartEntrypoint(
  46. appBundlePathOverride, libraryUri, host.getDartEntrypointFunctionName());
  47. // 最终通过flutterJNI.runBundleAndSnapshotFromLibrary 启动flutter的framework层
  48. flutterEngine.getDartExecutor().executeDartEntrypoint(entrypoint, host.getDartEntrypointArgs());
  49. }

Flutter Engine层启动

在启动过程中,通过API回调或者JNI主动调用,Embedder已经多次调用了Engine的逻辑,其中有5处对于Engnie至关重要:

  1. JNI_OnLoad:在System.loadLibrary时触发,将完成Engine接口和Embedder接口的绑定注册。
  2. nativeInit:FlutterLoader主动调用,在相关资源准备完成后调用,主要负责向Engine传递必要的初始化参数
  3. nativeAttach:Embedder的FlutterEngine对象在完成必要的初始化后调用,将触发Engine中关键类的初始化逻辑()
  4. nativeSurfaceCreated:Java侧的Surface对象(SurfaceView)准备完成后调用,将触发Engine中有关绘制的逻辑的初始化。
  5. runBundleAndSnapshotFromLibrary:FlutterEngine和FlutterView均初始化完成后,在Host(比如:FlutterActivity)的onStart生命周期中主动调用,用于触发framework的相关初始化工作。

    Flutter Framework层启动

    Flutter 内核源码剖析 - 图1

    Flutter 渲染管道