Flutter-Android-加载

FlutterApplication 启动

FlutterApplication.onCreate

[FlutterApplication.java]

public void onCreate() {
    ...
    FlutterMain.startInitialization(this);
}

startInitialization

[FlutterMain.java]

    public static void startInitialization(Context applicationContext, FlutterMain.Settings settings) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new IllegalStateException("startInitialization must be called on the main thread");
        } else if (sSettings == null) {
            sSettings = settings;
            long initStartTimestampMillis = SystemClock.uptimeMillis();
            initConfig(applicationContext);
            initAot(applicationContext);
            initResources(applicationContext);
            if (sResourceUpdater == null) {
                // 加载libflutter.so
                System.loadLibrary("flutter");
            } else {
                sResourceExtractor.waitForCompletion();
                File lib = new File(PathUtils.getDataDirectory(applicationContext), "libflutter.so");
                if (lib.exists()) {
                    System.load(lib.getAbsolutePath());
                } else {
                    System.loadLibrary("flutter");
                }
            }

            long initTimeMillis = SystemClock.uptimeMillis() - initStartTimestampMillis;
            nativeRecordStartTimestamp(initTimeMillis);
        }
    }

这个方法主要做的事情:

  • 初始化配置,获取是否预编译模式,初始化并提取资源文件;
  • 加载libflutter.so库;
  • 记录启动时间戳;

initConfig

[FlutterMain.java]

    private static void initConfig(Context applicationContext) {
        try {
            // metaData 信息
            Bundle metadata = applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), 128).metaData;
            if (metadata != null) {
                sAotSharedLibraryPath = metadata.getString(PUBLIC_AOT_AOT_SHARED_LIBRARY_PATH, "app.so");
                sAotVmSnapshotData = metadata.getString(PUBLIC_AOT_VM_SNAPSHOT_DATA_KEY, "vm_snapshot_data");
                sAotVmSnapshotInstr = metadata.getString(PUBLIC_AOT_VM_SNAPSHOT_INSTR_KEY, "vm_snapshot_instr");
                sAotIsolateSnapshotData = metadata.getString(PUBLIC_AOT_ISOLATE_SNAPSHOT_DATA_KEY, "isolate_snapshot_data");
                sAotIsolateSnapshotInstr = metadata.getString(PUBLIC_AOT_ISOLATE_SNAPSHOT_INSTR_KEY, "isolate_snapshot_instr");
                sFlx = metadata.getString(PUBLIC_FLX_KEY, "app.flx");
                sFlutterAssetsDir = metadata.getString(PUBLIC_FLUTTER_ASSETS_DIR_KEY, "flutter_assets");
            }

        } catch (NameNotFoundException var2) {
            throw new RuntimeException(var2);
        }
    }

初始化FlutterMain的相关配置信息,当metadata数据没有配置初值则采用默认值

initAot

[FlutterMain.java]

    private static void initAot(Context applicationContext) {
        Set assets = listAssets(applicationContext, "");
        sIsPrecompiledAsBlobs = assets.containsAll(Arrays.asList(sAotVmSnapshotData, sAotVmSnapshotInstr, sAotIsolateSnapshotData, sAotIsolateSnapshotInstr));
        sIsPrecompiledAsSharedLibrary = assets.contains(sAotSharedLibraryPath);
        // 当assets中存在共享库app.so和Dart虚拟机快照,则是预编译应用抛出异常
        if (sIsPrecompiledAsBlobs && sIsPrecompiledAsSharedLibrary) {
            throw new RuntimeException("Found precompiled app as shared library and as Dart VM snapshots.");
        }
    }

initResources

    private static void initResources(Context applicationContext) {
        Context context = applicationContext;
        (new ResourceCleaner(applicationContext)).start();
        Bundle metaData = null;

        try {
            metaData = context.getPackageManager().getApplicationInfo(context.getPackageName(), 128).metaData;
        } catch (NameNotFoundException var4) {
            ...
        }
        // 资源更新
        if (metaData != null && metaData.getBoolean("DynamicPatching")) {
            sResourceUpdater = new ResourceUpdater(applicationContext);
            if (sResourceUpdater.getDownloadMode() == DownloadMode.ON_RESTART || sResourceUpdater.getDownloadMode() == DownloadMode.ON_RESUME) {
                sResourceUpdater.startUpdateDownloadOnce();
                // 异步操作
                if (sResourceUpdater.getInstallMode() == InstallMode.IMMEDIATE) {
                    sResourceUpdater.waitForDownloadCompletion();
                }
            }
        }
        // 资源提取
        sResourceExtractor = new ResourceExtractor(applicationContext);
        sResourceExtractor.addResource(fromFlutterAssets(sFlx)).addResource(fromFlutterAssets(sAotVmSnapshotData)).addResource(fromFlutterAssets(sAotVmSnapshotInstr)).addResource(fromFlutterAssets(sAotIsolateSnapshotData)).addResource(fromFlutterAssets(sAotIsolateSnapshotInstr)).addResource(fromFlutterAssets("kernel_blob.bin"));
        if (sIsPrecompiledAsSharedLibrary) {
            sResourceExtractor.addResource(sAotSharedLibraryPath);
        } else {
            sResourceExtractor.addResource(sAotVmSnapshotData).addResource(sAotVmSnapshotInstr).addResource(sAotIsolateSnapshotData).addResource(sAotIsolateSnapshotInstr);
        }

        if (sResourceUpdater != null) {
            sResourceExtractor.addResource("libflutter.so");
        }

        sResourceExtractor.start();
    }

资源初始化主要包括对资源文件的清理、更新以及提前操作,这个过程都是在异步线程执行完成。

System.loadLibrary

不论是System.loadLibrary(),还是System.load()最终都会调用到该加载库中的JNI_OnLoad()方法,

[flutter/shell/platform/android/library_loader.cc]

JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
  // 初始化Java虚拟机
  fml::jni::InitJavaVM(vm);
  // 将当前线程和JavaVM建立关联
  JNIEnv* env = fml::jni::AttachCurrentThread();
  bool result = false;

  // 注册FlutterMain
  result = shell::FlutterMain::Register(env);

  // 注册PlatformView
  result = shell::PlatformViewAndroid::Register(env);

  // 注册VSyncWaiter
  result = shell::VsyncWaiterAndroid::Register(env);
  return JNI_VERSION_1_4;
}

InitJavaVM

jni_util.cc

void InitJavaVM(JavaVM* vm) {
  g_jvm = vm;
}

JNIEnv* AttachCurrentThread() {
  JNIEnv* env = nullptr;
  jint ret = g_jvm->AttachCurrentThread(&env, nullptr);
  FML_DCHECK(JNI_OK == ret);
  return env;
}

将当前进程的JavaVM实例保存在静态变量,再将当前线程和JavaVM建立关联,获取JNIEnv实例,每个线程对应一个JNIEnv实例。

FlutterMain::Register

flutter_main.cc

bool FlutterMain::Register(JNIEnv* env) {
  static const JNINativeMethod methods[] = {
      {
          .name = "nativeInit",
          .signature = "(Landroid/content/Context;[Ljava/lang/String;Ljava/"
                       "lang/String;Ljava/lang/String;Ljava/lang/String;)V",
          .fnPtr = reinterpret_cast(&Init),
      },
      {
          .name = "nativeRecordStartTimestamp",
          .signature = "(J)V",
          .fnPtr = reinterpret_cast(&RecordStartTimestamp),
      },
  };

  jclass clazz = env->FindClass("io/flutter/embedding/engine/FlutterJNI");
  ...
  return env->RegisterNatives(clazz, methods, fml::size(methods)) == 0;
}

注册了FlutterMain的nativeInit和nativeRecordStartTimestamp的两方法

PlatformViewAndroid::Register

platform_view_android_jni.cc

bool PlatformViewAndroid::Register(JNIEnv* env) {
  if (env == nullptr) {
    return false;
  }
  // FlutterCallbackInformation(String,String)
  g_flutter_callback_info_class = new fml::jni::ScopedJavaGlobalRef(
      env, env->FindClass("io/flutter/view/FlutterCallbackInformation"));
  ...
  g_flutter_callback_info_constructor = env->GetMethodID(
      g_flutter_callback_info_class->obj(), "",
      "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
  ...
  // FlutterJNI
  g_flutter_jni_class = new fml::jni::ScopedJavaGlobalRef(
      env, env->FindClass("io/flutter/embedding/engine/FlutterJNI"));
  ...
  // SurfaceTexture.attachToGLContext(int)
  g_surface_texture_class = new fml::jni::ScopedJavaGlobalRef(
      env, env->FindClass("android/graphics/SurfaceTexture"));
  ...
  g_attach_to_gl_context_method = env->GetMethodID(
      g_surface_texture_class->obj(), "attachToGLContext", "(I)V");
  ...
  // SurfaceTexture.updateTexImage()
  g_update_tex_image_method =
      env->GetMethodID(g_surface_texture_class->obj(), "updateTexImage", "()V");
  ...
  // SurfaceTexture.getTransformMatrix(float[])
  g_get_transform_matrix_method = env->GetMethodID(
      g_surface_texture_class->obj(), "getTransformMatrix", "([F)V");
  ...
  // SurfaceTexture.detachFromGLContext()
  g_detach_from_gl_context_method = env->GetMethodID(
      g_surface_texture_class->obj(), "detachFromGLContext", "()V");
  ...
  return RegisterApi(env);
}
bool RegisterApi(JNIEnv* env) {
  static const JNINativeMethod flutter_jni_methods[] = {
      // Start of methods from FlutterJNI
      {
          .name = "nativeAttach",
          .signature = "(Lio/flutter/embedding/engine/FlutterJNI;Z)J",
          .fnPtr = reinterpret_cast(&AttachJNI),
      },
      ...
      {
          .name = "nativeLookupCallbackInformation",
          .signature = "(J)Lio/flutter/view/FlutterCallbackInformation;",
          .fnPtr = reinterpret_cast(&LookupCallbackInformation),
      },
  };

  if (env->RegisterNatives(g_flutter_jni_class->obj(), flutter_jni_methods,
                           fml::size(flutter_jni_methods)) != 0) {
    return false;
  }

  g_handle_platform_message_method =
      env->GetMethodID(g_flutter_jni_class->obj(), "handlePlatformMessage",
                       "(Ljava/lang/String;[BI)V");
  ...
  if (g_on_engine_restart_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate onEngineRestart method";
    return false;
  }

  return true;
}

该方法的主要工作:通过RegisterNatives()注册一些类的Native方法,用于Java调用C++的过程;通过GetMethodID()等方法记录了一些Java方法的jmethodID,用于C++调用Java的过程。

VsyncWaiterAndroid::Register

vsync_waiter_android.cc

bool VsyncWaiterAndroid::Register(JNIEnv* env) {
  static const JNINativeMethod methods[] = {{
      .name = "nativeOnVsync",
      .signature = "(JJJ)V",
      .fnPtr = reinterpret_cast(&OnNativeVsync),
  }};

  jclass clazz = env->FindClass("io/flutter/embedding/engine/FlutterJNI");
  g_vsync_waiter_class = new fml::jni::ScopedJavaGlobalRef(env, clazz);
  g_async_wait_for_vsync_method_ = env->GetStaticMethodID(
      g_vsync_waiter_class->obj(), "asyncWaitForVsync", "(J)V");
  return env->RegisterNatives(clazz, methods, fml::size(methods)) == 0;
}

该注册过程主要工作:

  • 将Java层的VsyncWaiter类的nativeOnVsync()方法,映射到C++层的OnNativeVsync()方法,用于该方法的Java调用C++的过程;
  • 将Java层的VsyncWaiter类的asyncWaitForVsync()方法,保存到C++层的g_async_wait_for_vsync_method_变量,用于该方法C++调用Java的过程。

FlutterActivity 启动流程

FlutterActivity.onCreate

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.eventDelegate.onCreate(savedInstanceState);
}

调用代理的onCreate方法

FlutterActivityDelegate.onCreate

public void onCreate(Bundle savedInstanceState) {
    // 设置Widow相关属性
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = activity.getWindow();
        window.addFlags(LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(0x40000000);
        window.getDecorView().setSystemUiVisibility(PlatformPlugin.DEFAULT_SYSTEM_UI);
    }
    // 从Intent中提取参数
    String[] args = getArgsFromIntent(this.activity.getIntent());
    // 初始数据
    FlutterMain.ensureInitializationComplete(this.activity.getApplicationContext(), args);
    // 此处viewFactory便是FlutterActivity,该方法目前返回值为null
    this.flutterView = this.viewFactory.createFlutterView(this.activity);
    if (this.flutterView == null) {// 默认会走到这里
        // 这里默认为空
        FlutterNativeView nativeView = this.viewFactory.createFlutterNativeView();
        // 初始 FlutterView 下面有讲到
        this.flutterView = new FlutterView(this.activity, (AttributeSet)null, nativeView);
        // 将flutterView设置到Activity中
        this.flutterView.setLayoutParams(matchParent);
        this.activity.setContentView(this.flutterView);
        this.launchView = this.createLaunchView();
        // 过度的View
        if (this.launchView != null) {
            this.addLaunchView();
        }
    }

    if (!this.loadIntent(this.activity.getIntent())) {
        String appBundlePath = FlutterMain.findAppBundlePath(this.activity.getApplicationContext());
        if (appBundlePath != null) {
            this.runBundle(appBundlePath);
        }

    }
}

FlutterMain.ensureInitializationComplete

public static void ensureInitializationComplete(Context applicationContext, String[] args) {
    if (Looper.myLooper() != Looper.getMainLooper()) {
        throw new IllegalStateException("ensureInitializationComplete must be called on the main thread");
    } else if (sSettings == null) { // 保证sSettings完成初始化赋值;
        throw new IllegalStateException("ensureInitializationComplete must be called after startInitialization");
    } else if (!sInitialized) {
        try {
            // 保证sResourceExtractor完成资源文件的提取工作
            sResourceExtractor.waitForCompletion();
            // 拼接参数
            List shellArgs = new ArrayList();
            shellArgs.add("--icu-symbol-prefix=_binary_icudtl_dat");
            ApplicationInfo applicationInfo = applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), 128);
            shellArgs.add("--icu-native-lib-path=" + applicationInfo.nativeLibraryDir + File.separator + "libflutter.so");
            if (args != null) {
                Collections.addAll(shellArgs, args);
            }

            if (sIsPrecompiledAsSharedLibrary) {
                shellArgs.add("--aot-shared-library-path=" + new File(PathUtils.getDataDirectory(applicationContext), sAotSharedLibraryPath));
            } else {
                if (sIsPrecompiledAsBlobs) {
                    shellArgs.add("--aot-snapshot-path=" + PathUtils.getDataDirectory(applicationContext));
                } else {
                    shellArgs.add("--cache-dir-path=" + PathUtils.getCacheDirectory(applicationContext));
                    shellArgs.add("--aot-snapshot-path=" + PathUtils.getDataDirectory(applicationContext) + "/" + sFlutterAssetsDir);
                }

                shellArgs.add("--vm-snapshot-data=" + sAotVmSnapshotData);
                shellArgs.add("--vm-snapshot-instr=" + sAotVmSnapshotInstr);
                shellArgs.add("--isolate-snapshot-data=" + sAotIsolateSnapshotData);
                shellArgs.add("--isolate-snapshot-instr=" + sAotIsolateSnapshotInstr);
            }

            if (sSettings.getLogTag() != null) {
                shellArgs.add("--log-tag=" + sSettings.getLogTag());
            }

            String appBundlePath = findAppBundlePath(applicationContext);
            String appStoragePath = PathUtils.getFilesDir(applicationContext);
            String engineCachesPath = PathUtils.getCacheDirectory(applicationContext);
            // 初始化native相关信息
            nativeInit(applicationContext, (String[])shellArgs.toArray(new String[0]), appBundlePath, appStoragePath, engineCachesPath);
            sInitialized = true;
        } catch (Exception var7) {
            Log.e("FlutterMain", "Flutter initialization failed.", var7);
            throw new RuntimeException(var7);
        }
    }
}

这个方法主要的工作:

  • 保证该操作运行在主线程;
  • 保证sSettings完成初始化赋值;
  • 保证sResourceExtractor完成资源文件的提取工作;
  • 拼接所有相关的shellArgs,包括intent中的参数;
  • 执行nativeInit来初始化native相关信息;

FlutterMain::Init

在上面的(FlutterMain::Register)分析中 nativeInit所对应的方法FlutterMain::Init()

void FlutterMain::Init(JNIEnv* env,
                       jclass clazz,
                       jobject context,
                       jobjectArray jargs,
                       jstring bundlePath,
                       jstring appStoragePath,
                       jstring engineCachesPath) {
  std::vector args;
  args.push_back("flutter");
  for (auto& arg : fml::jni::StringArrayToVector(env, jargs)) {
    args.push_back(std::move(arg));
  }
  auto command_line = fml::CommandLineFromIterators(args.begin(), args.end());
  // 根据args生成Settings结构体,记录所有相关参数
  auto settings = SettingsFromCommandLine(command_line);

  settings.assets_path = fml::jni::JavaStringToString(env, bundlePath);

  flutter::DartCallbackCache::SetCachePath(
      fml::jni::JavaStringToString(env, appStoragePath));

  fml::paths::InitializeAndroidCachesPath(
      fml::jni::JavaStringToString(env, engineCachesPath));
  // 从磁盘中加载缓存
  flutter::DartCallbackCache::LoadCacheFromDisk();

  if (!flutter::DartVM::IsRunningPrecompiledCode()) {
    auto application_kernel_path =
        fml::paths::JoinPaths({settings.assets_path, "kernel_blob.bin"});
    if (fml::IsFile(application_kernel_path)) {
      settings.application_kernel_asset = application_kernel_path;
    }
  }
  // 初始化observer的增加和删除方法
  settings.task_observer_add = [](intptr_t key, fml::closure callback) {
    fml::MessageLoop::GetCurrent().AddTaskObserver(key, std::move(callback));
  };

  settings.task_observer_remove = [](intptr_t key) {
    fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);
  };
  // 
  g_flutter_main.reset(new FlutterMain(std::move(settings)));
}

该方法主要功能args以及各种资源文件路径细信息都保存在Settings结构体,记录在FlutterMain中,最后记录在g_flutter_main静态变量。

FlutterView 初始化

public FlutterView(Context context, AttributeSet attrs, FlutterNativeView nativeView) {
        super(context, attrs);
        ...
        Activity activity = getActivity(this.getContext());
        if (activity == null) {
            throw new IllegalArgumentException("Bad context");
        } else {
            if (nativeView == null) {
                // 初始化FlutterNativeView
                this.mNativeView = new FlutterNativeView(activity.getApplicationContext());
            } else {
                this.mNativeView = nativeView;
            }

            this.dartExecutor = this.mNativeView.getDartExecutor();
            this.flutterRenderer = new FlutterRenderer(this.mNativeView.getFlutterJNI());
            this.mIsSoftwareRenderingEnabled = FlutterJNI.nativeGetIsSoftwareRenderingEnabled();
            ...
            // 关联activity
            this.mNativeView.attachViewAndActivity(this, activity);
            this.mSurfaceCallback = new Callback() {
                public void surfaceCreated(SurfaceHolder holder) {
                    FlutterView.this.assertAttached();
                    FlutterView.this.mNativeView.getFlutterJNI().onSurfaceCreated(holder.getSurface());
                }

                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                    FlutterView.this.assertAttached();
                    FlutterView.this.mNativeView.getFlutterJNI().onSurfaceChanged(width, height);
                }

                public void surfaceDestroyed(SurfaceHolder holder) {
                    FlutterView.this.assertAttached();
                    FlutterView.this.mNativeView.getFlutterJNI().onSurfaceDestroyed();
                }
            };
            this.getHolder().addCallback(this.mSurfaceCallback);
            ...
            // 创建所有的平台通道channels
            this.navigationChannel = new NavigationChannel(this.dartExecutor);
            ...
            
            // 创建并设置插件
            PlatformPlugin platformPlugin = new PlatformPlugin(activity, this.platformChannel);
            this.addActivityLifecycleListener(platformPlugin);
            this.mImm = (InputMethodManager)this.getContext().getSystemService("input_method");
            ...

            // 发送初始化平台台的消息发送给Dart
            this.sendLocalesToDart(this.getResources().getConfiguration());
            this.sendUserPlatformSettingsToDart();
        }
    }

这个方法主要做的事情

  • 初始化变量
  • 初始化 FlutterNativeView
  • 创建所有的平台通道channels
  • 创建并设置插件

FlutterNativeView 初始化

public FlutterNativeView(@NonNull Context context, boolean isBackgroundView) {
    this.mContext = context;
    this.mPluginRegistry = new FlutterPluginRegistry(this, context);
    this.mFlutterJNI = new FlutterJNI();
    this.mFlutterJNI.setRenderSurface(new FlutterNativeView.RenderSurfaceImpl());
    this.dartExecutor = new DartExecutor(this.mFlutterJNI);
    this.mFlutterJNI.addEngineLifecycleListener(new FlutterNativeView.EngineLifecycleListenerImpl());
    this.attach(this, isBackgroundView);
    this.assertAttached();
}

这个方法主要做的是,对一些变量的初始操作,包括 FlutterPluginRegistry FlutterJNI RenderSurfaceImpl DartExecutor。并执行Attached方法

FlutterNativeView.attach

private void attach(FlutterNativeView view, boolean isBackgroundView) {
    this.mFlutterJNI.attachToNative(isBackgroundView);
    this.dartExecutor.onAttachedToJNI();
}
@UiThread
public void attachToNative(boolean isBackgroundView) {
    this.ensureNotAttachedToNative();
    this.nativePlatformViewId = this.nativeAttach(this, isBackgroundView);
}

AttachJNI

platform_view_android_jni.cc

static jlong AttachJNI(JNIEnv* env,
                       jclass clazz,
                       jobject flutterJNI,
                       jboolean is_background_view) {
  fml::jni::JavaObjectWeakGlobalRef java_object(env, flutterJNI);
  // 在引擎层初始化AndroidShellHolder对象
  auto shell_holder = std::make_unique(
      FlutterMain::Get().GetSettings(), java_object, is_background_view);
  if (shell_holder->IsValid()) {
    return reinterpret_cast(shell_holder.release());
  } else {
    return 0;
  }
}

Flutter引擎启动

AndroidShellHolder 初始化

AndroidShellHolder::AndroidShellHolder(
    flutter::Settings settings,
    fml::jni::JavaObjectWeakGlobalRef java_object,
    bool is_background_view)
    : settings_(std::move(settings)), java_object_(java_object) {
  static size_t shell_count = 1;
  auto thread_label = std::to_string(shell_count++);
  //创建线程私有的key
  FML_CHECK(pthread_key_create(&thread_destruct_key_, ThreadDestructCallback) ==
            0);

  //创建目标线程
  if (is_background_view) {
    ...
  } else {
    thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU |
                                      ThreadHost::Type::IO};
  }

  // Detach from JNI when the UI and GPU threads exit.
  // 当UI和GPU线程退出时从JNI分离。
  auto jni_exit_task([key = thread_destruct_key_]() {
    FML_CHECK(pthread_setspecific(key, reinterpret_cast(1)) == 0);
  });
  thread_host_.ui_thread->GetTaskRunner()->PostTask(jni_exit_task);
  if (!is_background_view) {
    thread_host_.gpu_thread->GetTaskRunner()->PostTask(jni_exit_task);
  }

  fml::WeakPtr weak_platform_view;
  Shell::CreateCallback on_create_platform_view =
      [is_background_view, java_object, &weak_platform_view](Shell& shell) {
        std::unique_ptr platform_view_android;
        if (is_background_view) {
            ...
        } else {
          platform_view_android = std::make_unique(
              shell,                   // delegate
              shell.GetTaskRunners(),  // task runners
              java_object,             // java object handle for JNI interop
              shell.GetSettings()
                  .enable_software_rendering  // use software rendering
          );
        }
        weak_platform_view = platform_view_android->GetWeakPtr();
        return platform_view_android;
      };

  Shell::CreateCallback on_create_rasterizer = [](Shell& shell) {
    return std::make_unique(shell, shell.GetTaskRunners());
  };

  // The current thread will be used as the platform thread. Ensure that the
  // message loop is initialized.
  // 当前主线程初始化MesageLoop
  fml::MessageLoop::EnsureInitializedForCurrentThread();
  // gpu,ui,io 三个线程
  fml::RefPtr gpu_runner;
  fml::RefPtr ui_runner;
  fml::RefPtr io_runner;
  fml::RefPtr platform_runner =
      fml::MessageLoop::GetCurrent().GetTaskRunner();
  if (is_background_view) {
    ...
  } else {
    gpu_runner = thread_host_.gpu_thread->GetTaskRunner();
    ui_runner = thread_host_.ui_thread->GetTaskRunner();
    io_runner = thread_host_.io_thread->GetTaskRunner();
  }
  // 创建task_runners对象
  flutter::TaskRunners task_runners(thread_label,     // label
                                    platform_runner,  // platform
                                    gpu_runner,       // gpu
                                    ui_runner,        // ui
                                    io_runner         // io
  );
  // 创建Shell对象
  shell_ =
      Shell::Create(task_runners,             // task runners
                    settings_,                // settings
                    on_create_platform_view,  // platform view create callback
                    on_create_rasterizer      // rasterizer create callback
      );

  platform_view_ = weak_platform_view;
  is_valid_ = shell_ != nullptr;
  if (is_valid_) { // 可用
    // 提升ui线程和gpu线程的优先级
    task_runners.GetGPUTaskRunner()->PostTask([]() {
      // Android describes -8 as "most important display threads, for
      // compositing the screen and retrieving input events". Conservatively
      // set the GPU thread to slightly lower priority than it.
      if (::setpriority(PRIO_PROCESS, gettid(), -5) != 0) {
        // Defensive fallback. Depending on the OEM, it may not be possible
        // to set priority to -5.
        if (::setpriority(PRIO_PROCESS, gettid(), -2) != 0) {
          FML_LOG(ERROR) << "Failed to set GPU task runner priority";
        }
      }
    });
    task_runners.GetUITaskRunner()->PostTask([]() {
      if (::setpriority(PRIO_PROCESS, gettid(), -1) != 0) {
        FML_LOG(ERROR) << "Failed to set UI task runner priority";
      }
    });
  }
}

该方法的主要功能:

  • 创建ui,gpu,io这3个线程,并分别初始化MessageLoop
  • on_create_platform_view on_create_rasterizer
  • 创建Shell对象,TaskRunners对象

ThreadHost

看一下线程创建的过程
thread_host.cc

ThreadHost::ThreadHost(std::string name_prefix, uint64_t mask) {
  if (mask & ThreadHost::Type::Platform) {
    platform_thread = std::make_unique(name_prefix + ".platform");
  }

  if (mask & ThreadHost::Type::UI) {
    ui_thread = std::make_unique(name_prefix + ".ui");
  }

  if (mask & ThreadHost::Type::GPU) {
    gpu_thread = std::make_unique(name_prefix + ".gpu");
  }

  if (mask & ThreadHost::Type::IO) {
    io_thread = std::make_unique(name_prefix + ".io");
  }
}

根据传递的参数,可知首次创建AndroidShellHolder实例的过程,会创建1.ui, 1.gpu, 1.io这3个线程。每个线程Thread初始化过程,都会创建相应的MessageLoop、TaskRunner对象,然后进入pollOnce轮询等待状态

Shell::Create

std::unique_ptr Shell::Create(
    TaskRunners task_runners,
    Settings settings,
    Shell::CreateCallback on_create_platform_view,
    Shell::CreateCallback on_create_rasterizer) {
  // 初始化对应平台信息。比如设置日志输入,记录启动时间,Skia初始化等
  PerformInitializationTasks(settings);
  PersistentCache::SetCacheSkSL(settings.cache_sksl);

  // 创建虚拟机
  auto vm = DartVMRef::Create(settings);
  FML_CHECK(vm) << "Must be able to initialize the VM.";
  auto vm_data = vm->GetVMData();

  return Shell::Create(std::move(task_runners),             //
                       std::move(settings),                 //
                       vm_data->GetIsolateSnapshot(),       // isolate snapshot
                       std::move(on_create_platform_view),  //
                       std::move(on_create_rasterizer),     //
                       std::move(vm)                        //
  );
}

该方法的主要功能:更加传递的参数,设置一些属性等

DartVMRef::Create

dart_vm_lifecycle.cc

DartVMRef DartVMRef::Create(Settings settings,
                            fml::RefPtr vm_snapshot,
                            fml::RefPtr isolate_snapshot) {
  std::scoped_lock lifecycle_lock(gVMMutex);


  // If there is already a running VM in the process, grab a strong reference to
  // it.
  // 当该进程存在一个正在运行虚拟机,则获取其强引用,复用该虚拟机
  if (auto vm = gVM.lock()) {
    FML_DLOG(WARNING) << "Attempted to create a VM in a process where one was "
                         "already running. Ignoring arguments for current VM "
                         "create call and reusing the old VM.";
    // There was already a running VM in the process,
    return DartVMRef{std::move(vm)};
  }

  std::scoped_lock dependents_lock(gVMDependentsMutex);
  // reset()
  gVMData.reset();
  gVMServiceProtocol.reset();
  gVMIsolateNameServer.reset();
  gVM.reset();

  // If there is no VM in the process. Initialize one, hold the weak reference
  // and pass a strong reference to the caller.
  auto isolate_name_server = std::make_shared();
  //创建虚拟机
  auto vm = DartVM::Create(std::move(settings),          //
                           std::move(vm_snapshot),       //
                           std::move(isolate_snapshot),  //
                           isolate_name_server           //
  );


  gVMData = vm->GetVMData();
  gVMServiceProtocol = vm->GetServiceProtocol();
  gVMIsolateNameServer = isolate_name_server;
  gVM = vm;

  if (settings.leak_vm) {
    gVMLeak = new std::shared_ptr(vm);
  }

  return DartVMRef{std::move(vm)};
}

Shell::Create

std::unique_ptr Shell::Create(
    TaskRunners task_runners,
    Settings settings,
    fml::RefPtr isolate_snapshot,
    Shell::CreateCallback on_create_platform_view,
    Shell::CreateCallback on_create_rasterizer,
    DartVMRef vm) {
  ...
  fml::AutoResetWaitableEvent latch;
  std::unique_ptr shell;
  fml::TaskRunner::RunNowOrPostTask(
      task_runners.GetPlatformTaskRunner(),
      fml::MakeCopyable([&latch,                                          //
                         vm = std::move(vm),                              //
                         &shell,                                          //
                         task_runners = std::move(task_runners),          //
                         settings,                                        //
                         isolate_snapshot = std::move(isolate_snapshot),  //
                         on_create_platform_view,                         //
                         on_create_rasterizer                             //
  ]() mutable {
        // 创建shell的地方
        shell = CreateShellOnPlatformThread(std::move(vm),
                                            std::move(task_runners),      //
                                            settings,                     //
                                            std::move(isolate_snapshot),  //
                                            on_create_platform_view,      //
                                            on_create_rasterizer          //
        );
        latch.Signal();
      }));
  latch.Wait();
  return shell;
}

Shell::CreateShellOnPlatformThread

std::unique_ptr Shell::CreateShellOnPlatformThread(
    DartVMRef vm,
    TaskRunners task_runners,
    Settings settings,
    fml::RefPtr isolate_snapshot,
    Shell::CreateCallback on_create_platform_view,
    Shell::CreateCallback on_create_rasterizer) {

  // new Shell
  auto shell =
      std::unique_ptr(new Shell(std::move(vm), task_runners, settings));

  // Create the rasterizer on the GPU thread.
  // GPU 线程创建 rasterizer
  std::promise> rasterizer_promise;
  auto rasterizer_future = rasterizer_promise.get_future();
  std::promise> snapshot_delegate_promise;
  auto snapshot_delegate_future = snapshot_delegate_promise.get_future();
  fml::TaskRunner::RunNowOrPostTask(
      task_runners.GetGPUTaskRunner(), [&rasterizer_promise,  //
                                        &snapshot_delegate_promise,
                                        on_create_rasterizer,  //
                                        shell = shell.get()    //
  ]() {
        TRACE_EVENT0("flutter", "ShellSetupGPUSubsystem");
        std::unique_ptr rasterizer(on_create_rasterizer(*shell));
        snapshot_delegate_promise.set_value(rasterizer->GetSnapshotDelegate());
        rasterizer_promise.set_value(std::move(rasterizer));
      });

  // Create the platform view on the platform thread (this thread).
  // 在主线程创建 platform view
  auto platform_view = on_create_platform_view(*shell.get());

  // Ask the platform view for the vsync waiter. This will be used by the engine
  // to create the animator.
  // 创建 vsync_waiter
  auto vsync_waiter = platform_view->CreateVSyncWaiter();

  // Create the IO manager on the IO thread. The IO manager must be initialized
  // first because it has state that the other subsystems depend on. It must
  // first be booted and the necessary references obtained to initialize the
  // other subsystems.
  std::promise> io_manager_promise;
  auto io_manager_future = io_manager_promise.get_future();
  std::promise> weak_io_manager_promise;
  auto weak_io_manager_future = weak_io_manager_promise.get_future();
  std::promise> unref_queue_promise;
  auto unref_queue_future = unref_queue_promise.get_future();
  auto io_task_runner = shell->GetTaskRunners().GetIOTaskRunner();

  fml::TaskRunner::RunNowOrPostTask(
      io_task_runner,
      [&io_manager_promise,                          //
       &weak_io_manager_promise,                     //
       &unref_queue_promise,                         //
       platform_view = platform_view->GetWeakPtr(),  //
       io_task_runner                                //
  ]() {
        // 在io线程中创建ShellIOManager对象
        auto io_manager = std::make_unique(
            platform_view.getUnsafe()->CreateResourceContext(), io_task_runner);
        weak_io_manager_promise.set_value(io_manager->GetWeakPtr());
        unref_queue_promise.set_value(io_manager->GetSkiaUnrefQueue());
        io_manager_promise.set_value(std::move(io_manager));
      });

  // Send dispatcher_maker to the engine constructor because shell won't have
  // platform_view set until Shell::Setup is called later.
  auto dispatcher_maker = platform_view->GetDispatcherMaker();

  // Create the engine on the UI thread.
  std::promise> engine_promise;
  auto engine_future = engine_promise.get_future();
  fml::TaskRunner::RunNowOrPostTask(
      shell->GetTaskRunners().GetUITaskRunner(),
      fml::MakeCopyable([&engine_promise,                                 //
                         shell = shell.get(),                             //
                         &dispatcher_maker,                               //
                         isolate_snapshot = std::move(isolate_snapshot),  //
                         vsync_waiter = std::move(vsync_waiter),          //
                         &weak_io_manager_future,                         //
                         &snapshot_delegate_future,                       //
                         &unref_queue_future                              //
  ]() mutable {
        
        const auto& task_runners = shell->GetTaskRunners();

        // The animator is owned by the UI thread but it gets its vsync pulses
        // from the platform.
        // 创建Animator对象 
        auto animator = std::make_unique(*shell, task_runners,
                                                   std::move(vsync_waiter));
        // 在ui线程中创建Engine对象
        engine_promise.set_value(std::make_unique(
            *shell,                         //
            dispatcher_maker,               //
            *shell->GetDartVM(),            //
            std::move(isolate_snapshot),    //
            task_runners,                   //
            shell->GetSettings(),           //
            std::move(animator),            //
            weak_io_manager_future.get(),   //
            unref_queue_future.get(),       //
            snapshot_delegate_future.get()  //
            ));
      }));

  if (!shell->Setup(std::move(platform_view),  //
                    engine_future.get(),       //
                    rasterizer_future.get(),   //
                    io_manager_future.get())   //
  ) {
    return nullptr;
  }

  return shell;
}

该方法的主要功能:

  • new Shell
  • GPU线程创建 rasterizer
  • 主线程创建 platform view
  • 创建 vsync_waiter
  • io线程中创建ShellIOManager对象
  • 创建Animator对象
  • ui线程中创建Engine对象
new Shell
Shell::Shell(DartVMRef vm, TaskRunners task_runners, Settings settings)
    : task_runners_(std::move(task_runners)),
      settings_(std::move(settings)),
      vm_(std::move(vm)),
      weak_factory_(this),
      weak_factory_gpu_(nullptr) {
  
  // Generate a WeakPtrFactory for use with the GPU thread. This does not need
  // to wait on a latch because it can only ever be used from the GPU thread
  // from this class, so we have ordering guarantees.
  fml::TaskRunner::RunNowOrPostTask(
      task_runners_.GetGPUTaskRunner(), fml::MakeCopyable([this]() mutable {
        this->weak_factory_gpu_ =
            std::make_unique>(this);
      }));

  // Install service protocol handlers.
  // 运行在主线程,设置service protocol handlers
  service_protocol_handlers_[ServiceProtocol::kScreenshotExtensionName] = {
      task_runners_.GetGPUTaskRunner(),
      std::bind(&Shell::OnServiceProtocolScreenshot, this,
                std::placeholders::_1, std::placeholders::_2)};
  ...
}

创建Shell对象,成员变量task_runners_、settings_以及vm_赋初值

PlatformViewAndroid

platform_view 的创建过程

platform_view_android.cc

platform_view_android = std::make_unique(
              shell,                   // delegate
              shell.GetTaskRunners(),  // task runners
              java_object,             // java object handle for JNI interop
              shell.GetSettings()
                  .enable_software_rendering  // use software rendering
          );
PlatformViewAndroid::PlatformViewAndroid(
    PlatformView::Delegate& delegate,
    flutter::TaskRunners task_runners,
    fml::jni::JavaObjectWeakGlobalRef java_object,
    bool use_software_rendering)
    : PlatformView(delegate, std::move(task_runners)),
      java_object_(java_object),
      android_surface_(AndroidSurface::Create(use_software_rendering)) {
  FML_CHECK(android_surface_)
      << "Could not create an OpenGL, Vulkan or Software surface to setup "
         "rendering.";
}
AndroidSurface::Create
std::unique_ptr AndroidSurface::Create(
    bool use_software_rendering) {
  if (use_software_rendering) {
    auto software_surface = std::make_unique();
    return software_surface->IsValid() ? std::move(software_surface) : nullptr;
  }
#if SHELL_ENABLE_VULKAN
  auto vulkan_surface = std::make_unique();
  return vulkan_surface->IsValid() ? std::move(vulkan_surface) : nullptr;
#else   // SHELL_ENABLE_VULKAN
  auto gl_surface = std::make_unique();
  return gl_surface->IsOffscreenContextValid() ? std::move(gl_surface)
                                               : nullptr;
#endif  // SHELL_ENABLE_VULKAN
}

三种不同的AndroidSurface,目前android_surface_默认数据类型为AndroidSurfaceGL

Engine初始化

engine.cc

Engine::Engine(Delegate& delegate,
               const PointerDataDispatcherMaker& dispatcher_maker,
               DartVM& vm,
               fml::RefPtr isolate_snapshot,
               TaskRunners task_runners,
               Settings settings,
               std::unique_ptr animator,
               fml::WeakPtr io_manager,
               fml::RefPtr unref_queue,
               fml::WeakPtr snapshot_delegate)
    : delegate_(delegate),
      settings_(std::move(settings)),
      animator_(std::move(animator)),
      activity_running_(true),
      have_surface_(false),
      image_decoder_(task_runners,
                     vm.GetConcurrentWorkerTaskRunner(),
                     io_manager),
      task_runners_(std::move(task_runners)),
      weak_factory_(this) {
  // Runtime controller is initialized here because it takes a reference to this
  // object as its delegate. The delegate may be called in the constructor and
  // we want to be fully initilazed by that point.
  // 创建RuntimeController对象
  runtime_controller_ = std::make_unique(
      *this,                        // runtime delegate
      &vm,                          // VM
      std::move(isolate_snapshot),  // isolate snapshot
      task_runners_,                // task runners
      std::move(snapshot_delegate),
      std::move(io_manager),                 // io manager
      std::move(unref_queue),                // Skia unref queue
      image_decoder_.GetWeakPtr(),           // image decoder
      settings_.advisory_script_uri,         // advisory script uri
      settings_.advisory_script_entrypoint,  // advisory script entrypoint
      settings_.idle_notification_callback,  // idle notification callback
      settings_.isolate_create_callback,     // isolate create callback
      settings_.isolate_shutdown_callback,   // isolate shutdown callback
      settings_.persistent_isolate_data      // persistent isolate data
  );

  pointer_data_dispatcher_ = dispatcher_maker(*this);
}
RuntimeController

runtime_controller.cc

RuntimeController::RuntimeController(
    RuntimeDelegate& p_client,
    DartVM* p_vm,
    fml::RefPtr p_isolate_snapshot,
    fml::RefPtr p_shared_snapshot,
    TaskRunners p_task_runners,
    fml::WeakPtr p_snapshot_delegate,
    fml::WeakPtr p_io_manager,
    std::string p_advisory_script_uri,
    std::string p_advisory_script_entrypoint,
    std::function idle_notification_callback,
    WindowData p_window_data)
    : client_(p_client),
      vm_(p_vm),
      isolate_snapshot_(std::move(p_isolate_snapshot)),
      shared_snapshot_(std::move(p_shared_snapshot)),
      task_runners_(p_task_runners),
      snapshot_delegate_(p_snapshot_delegate),
      io_manager_(p_io_manager),
      advisory_script_uri_(p_advisory_script_uri),
      advisory_script_entrypoint_(p_advisory_script_entrypoint),
      idle_notification_callback_(idle_notification_callback),
      window_data_(std::move(p_window_data)),
      root_isolate_(
          //[见小节4.12.4]
          DartIsolate::CreateRootIsolate(vm_->GetVMData()->GetSettings(),
                                         isolate_snapshot_,
                                         shared_snapshot_,
                                         task_runners_,
                                         //[见小节4.12.3]
                                         std::make_unique(this),
                                         snapshot_delegate_,
                                         io_manager_,
                                         p_advisory_script_uri,
                                         p_advisory_script_entrypoint)) {
  std::shared_ptr root_isolate = root_isolate_.lock();
  root_isolate->SetReturnCodeCallback([this](uint32_t code) {
    root_isolate_return_code_ = {true, code};
  });
  if (auto* window = GetWindowIfAvailable()) {
    tonic::DartState::Scope scope(root_isolate);
    window->DidCreateIsolate();
    if (!FlushRuntimeStateToIsolate()) {
      FML_DLOG(ERROR) << "Could not setup intial isolate state.";
    }
  }
}
DartIsolate::CreateRootIsolate

dart_isolate.cc

std::weak_ptr DartIsolate::CreateRootIsolate(
    const Settings& settings,
    fml::RefPtr isolate_snapshot,
    fml::RefPtr shared_snapshot,
    TaskRunners task_runners,
    std::unique_ptr window,
    fml::WeakPtr snapshot_delegate,
    fml::WeakPtr io_manager,
    std::string advisory_script_uri,
    std::string advisory_script_entrypoint,
    Dart_IsolateFlags* flags) {
  TRACE_EVENT0("flutter", "DartIsolate::CreateRootIsolate");
  Dart_Isolate vm_isolate = nullptr;
  std::weak_ptr embedder_isolate;

  //创建DartIsolate
  auto root_embedder_data = std::make_unique>(
      std::make_shared(
          settings, std::move(isolate_snapshot),
          std::move(shared_snapshot), task_runners,                 
          std::move(snapshot_delegate), std::move(io_manager),        
          advisory_script_uri, advisory_script_entrypoint,    
          nullptr));
  //创建Isolate
  std::tie(vm_isolate, embedder_isolate) = CreateDartVMAndEmbedderObjectPair(
      advisory_script_uri.c_str(), advisory_script_entrypoint.c_str(),  
      nullptr, nullptr, flags,                               
      root_embedder_data.get(), true, &error);

  std::shared_ptr shared_embedder_isolate = embedder_isolate.lock();
  if (shared_embedder_isolate) {
    //只有root isolates能和window交互
    shared_embedder_isolate->SetWindow(std::move(window));
  }
  root_embedder_data.release();
  return embedder_isolate;
}

加载Dart代码

FlutterActivityDelegate.runBundle

private void runBundle(String appBundlePath) {
    if (!this.flutterView.getFlutterNativeView().isApplicationRunning()) {
        FlutterRunArguments args = new FlutterRunArguments();
        ArrayList bundlePaths = new ArrayList();
        ResourceUpdater resourceUpdater = FlutterMain.getResourceUpdater();
        if (resourceUpdater != null) {
            File patchFile = resourceUpdater.getInstalledPatch();
            JSONObject manifest = resourceUpdater.readManifest(patchFile);
            if (resourceUpdater.validateManifest(manifest)) {
                bundlePaths.add(patchFile.getPath());
            }
        }
        bundlePaths.add(appBundlePath);
        args.bundlePaths = (String[])bundlePaths.toArray(new String[0]);
        // 默认是 main。 entrypoint 是指最终回调执行的主函数名
        args.entrypoint = "main";
        this.flutterView.runFromBundle(args);
    }

}

runFromBundle

public void runFromBundle(FlutterRunArguments args) {
    ...
    this.mNativeView.runFromBundle(args);
    ...
}
public void runFromBundle(FlutterRunArguments args) {
        boolean hasBundlePaths = args.bundlePaths != null && args.bundlePaths.length != 0;
        ...
        if (hasBundlePaths) {
            this.runFromBundleInternal(args.bundlePaths, args.entrypoint, args.libraryPath);
        } else {
            this.runFromBundleInternal(new String[]{args.bundlePath, args.defaultPath}, args.entrypoint, args.libraryPath);
        }
    }

runFromBundleInternal

private void runFromBundleInternal(String[] bundlePaths, String entrypoint, String libraryPath) {
    ...
    this.mFlutterJNI.runBundleAndSnapshotFromLibrary(bundlePaths, entrypoint, libraryPath, this.mContext.getResources().getAssets());
    ...
}

runBundleAndSnapshotFromLibrary

    public void runBundleAndSnapshotFromLibrary(@NonNull String[] prioritizedBundlePaths, @Nullable String entrypointFunctionName, @Nullable String pathToEntrypointFunction, @NonNull AssetManager assetManager) {
        ...
        this.nativeRunBundleAndSnapshotFromLibrary(this.nativePlatformViewId, prioritizedBundlePaths, entrypointFunctionName, pathToEntrypointFunction, assetManager);
    }

nativeRunBundleAndSnapshotFromLibrary

nativeRunBundleAndSnapshotFromLibrary这是一个Native方法,签名已介绍过,对应的方法为RunBundleAndSnapshotFromLibrary。

你可能感兴趣的:(Flutter-Android-加载)