Flutter 热更新-1.12.13+hotfix.5启动流程分析

这里分析flutter作为module情况下Android端启动流程。1.12.13版本通过下述方法启动Flutter页面。

startActivity(
   FlutterActivity.createDefaultIntent(this)
)

createDefaultIntent()

public static Intent createDefaultIntent(@NonNull Context launchContext) {
  return withNewEngine().build(launchContext);
}

public Intent build(@NonNull Context context) {
  return new Intent(context, activityClass)
      .putExtra(EXTRA_INITIAL_ROUTE, initialRoute)
      .putExtra(EXTRA_BACKGROUND_MODE, backgroundMode)
      .putExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, true);
}
 
//activityClass声明处Class<? extends FlutterActivity>
//activityClass是FlutterActivity的子类型,接下来看FlutterActivity.onCreate()
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
  switchLaunchThemeForNormalTheme();
 
  super.onCreate(savedInstanceState);
 
  lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
 
  delegate = new FlutterActivityAndFragmentDelegate(this);
  delegate.onAttach(this);
  delegate.onActivityCreated(savedInstanceState);
 
  configureWindowForTransparency();
  setContentView(createFlutterView());
  configureStatusBarForFullscreenFlutterExperience();
}
  • delegate.onAttach(this)
  • delegate.onActivityCreated(savedInstanceState)

FlutterActivityAndFragmentDelegate.onActivityCreated()

void onActivityCreated(@Nullable Bundle bundle) {
  Log.v(TAG, "onActivityCreated. Giving plugins an opportunity to restore state.");
  ensureAlive();
 
  if (host.shouldAttachEngineToActivity()) {
    flutterEngine.getActivityControlSurface().onRestoreInstanceState(bundle);
  }
}

flutterEngine.getActivityControlSurface().onRestoreInstanceState最终调用到FlutterEnginePluginRegistry.onRestoreInstanceState()

public void onRestoreInstanceState(@Nullable Bundle bundle) {
  if (isAttachedToActivity()) {
    activityPluginBinding.onRestoreInstanceState(bundle);
  } else {
    Log.e(TAG, "Attempted to notify ActivityAware plugins of onRestoreInstanceState, but no Activity was attached.");
  }
}

activityPluginBinding.onRestoreInstanceState(bundle),activityPluginBinding是FlutterEnginePluginRegistry的静态内部类FlutterEngineActivityPluginBinding;FlutterEngineActivityPluginBinding.onRestoreInstanceState()遍历OnSaveInstanceStateListener集合回调onRestoreInstanceState()方法。

void onRestoreInstanceState(@Nullable Bundle bundle) {
  for (OnSaveInstanceStateListener listener : onSaveInstanceStateListeners) {
    listener.onRestoreInstanceState(bundle);
  }
}

onSaveInstanceStateListeners是FlutterEngineActivityPluginBinding成员变量

private final Set<OnSaveInstanceStateListener> onSaveInstanceStateListeners = new HashSet<>();

看看它在哪里被赋值,FlutterEngineActivityPluginBinding

@Override
public void addOnSaveStateListener(@NonNull OnSaveInstanceStateListener listener) {
  onSaveInstanceStateListeners.add(listener);
}

addOnSaveStateListener是ActivityPluginBinding接口方法,FlutterEngine通过FlutterEnginePluginRegistry注册一些PluginBinding同步对应组件的信息,ActivityPluginBinding中就有我们很熟悉的一些Activity回调,类似的FlutterEnginePluginRegistry中FlutterEngineServicePluginBinding实现了ServicePluginBinding接口。

public interface ActivityPluginBinding {
  @NonNull
  Activity getActivity();

  @NonNull
  Object getLifecycle();

  void addRequestPermissionsResultListener(@NonNull PluginRegistry.RequestPermissionsResultListener listener);

  void removeRequestPermissionsResultListener(@NonNull PluginRegistry.RequestPermissionsResultListener listener);

  void addActivityResultListener(@NonNull PluginRegistry.ActivityResultListener listener);

  void removeActivityResultListener(@NonNull PluginRegistry.ActivityResultListener listener);

  void addOnNewIntentListener(@NonNull PluginRegistry.NewIntentListener listener);

  void removeOnNewIntentListener(@NonNull PluginRegistry.NewIntentListener listener);

  void addOnUserLeaveHintListener(@NonNull PluginRegistry.UserLeaveHintListener listener);

  void removeOnUserLeaveHintListener(@NonNull PluginRegistry.UserLeaveHintListener listener);

  void addOnSaveStateListener(@NonNull OnSaveInstanceStateListener listener);

  void removeOnSaveStateListener(@NonNull OnSaveInstanceStateListener listener);

  interface OnSaveInstanceStateListener {
    void onSaveInstanceState(@NonNull Bundle bundle);

    void onRestoreInstanceState(@Nullable Bundle bundle);
  }
}

FlutterActivityAndFragmentDelegate.onAttach()

void onAttach(@NonNull Context context) {
  ensureAlive();
 
  if (flutterEngine == null) {
    setupFlutterEngine();
  }
 
  platformPlugin = host.providePlatformPlugin(host.getActivity(), flutterEngine);
 
  if (host.shouldAttachEngineToActivity()) {
    //FlutterEnginePluginRegistry.attachToActivity()
    flutterEngine.getActivityControlSurface().attachToActivity(
        host.getActivity(),
        host.getLifecycle()
    );
  }
 
  host.configureFlutterEngine(flutterEngine);
}

ensureAlive()

private void ensureAlive() {
    //host是前面delegate = new FlutterActivityAndFragmentDelegate(this)传入的this即FlutterActivity
    if (host == null) {
      throw new IllegalStateException("Cannot execute method on a destroyed FlutterActivityAndFragmentDelegate.");
    }
  }

setupFlutterEngine()

void setupFlutterEngine() {
  String cachedEngineId = host.getCachedEngineId();
  if (cachedEngineId != null) {
    //flutterEngine缓存池
    flutterEngine = FlutterEngineCache.getInstance().get(cachedEngineId);
    isFlutterEngineFromHost = true;
    if (flutterEngine == null) {
      throw new IllegalStateException("The requested cached FlutterEngine did not exist in the FlutterEngineCache: '" + cachedEngineId + "'");
    }
    return;
  }
 
  flutterEngine = host.provideFlutterEngine(host.getContext());
  if (flutterEngine != null) {
    isFlutterEngineFromHost = true;
    return;
  }
 
  //初始化FlutterEngine
  flutterEngine = new FlutterEngine(host.getContext(), host.getFlutterShellArgs().toArray());
  isFlutterEngineFromHost = false;
}

FlutterEngine()

public FlutterEngine(@NonNull Context context, @Nullable String[] dartVmArgs) {
  this(context, FlutterLoader.getInstance(), new FlutterJNI(), dartVmArgs, true);
}

public FlutterEngine(
    @NonNull Context context,
    @NonNull FlutterLoader flutterLoader,
    @NonNull FlutterJNI flutterJNI,
    @Nullable String[] dartVmArgs,
    boolean automaticallyRegisterPlugins
) {
  this.flutterJNI = flutterJNI;
  flutterLoader.startInitialization(context);
  flutterLoader.ensureInitializationComplete(context, dartVmArgs);
 
  flutterJNI.addEngineLifecycleListener(engineLifecycleListener);
  attachToJni();
 
  this.dartExecutor = new DartExecutor(flutterJNI, context.getAssets());
  this.dartExecutor.onAttachedToJNI();
 
  this.renderer = new FlutterRenderer(flutterJNI);
 
  accessibilityChannel = new AccessibilityChannel(dartExecutor, flutterJNI);
  keyEventChannel = new KeyEventChannel(dartExecutor);
  lifecycleChannel = new LifecycleChannel(dartExecutor);
  localizationChannel = new LocalizationChannel(dartExecutor);
  navigationChannel = new NavigationChannel(dartExecutor);
  platformChannel = new PlatformChannel(dartExecutor);
  settingsChannel = new SettingsChannel(dartExecutor);
  systemChannel = new SystemChannel(dartExecutor);
  textInputChannel = new TextInputChannel(dartExecutor);
 
  platformViewsController = new PlatformViewsController();
 
  this.pluginRegistry = new FlutterEnginePluginRegistry(
    context.getApplicationContext(),
    this,
    flutterLoader
  );
 
  if (automaticallyRegisterPlugins) {
    registerPlugins();
  }
}
  • flutterLoader.startInitialization(context)
  • flutterLoader.ensureInitializationComplete(context, dartVmArgs)

FlutterLoader.startInitialization()

public void startInitialization(@NonNull Context applicationContext) {
        startInitialization(applicationContext, new Settings());
}
public void startInitialization(@NonNull Context applicationContext, @NonNull Settings settings) {
        if (this.settings != null) {
          return;
        }
        if (Looper.myLooper() != Looper.getMainLooper()) {
          throw new IllegalStateException("startInitialization must be called on the main thread");
        }

        this.settings = settings;

        long initStartTimestampMillis = SystemClock.uptimeMillis();
        initConfig(applicationContext);
        initResources(applicationContext);

        System.loadLibrary("flutter");

        VsyncWaiter
            .getInstance((WindowManager) applicationContext.getSystemService(Context.WINDOW_SERVICE))
            .init();

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

//initConfig 初始化资源文件
private void initConfig(@NonNull Context applicationContext) {
        Bundle metadata = getApplicationInfo(applicationContext).metaData;

        if (metadata == null) {
            return;
        }

        //so包名称
        aotSharedLibraryName = metadata.getString(PUBLIC_AOT_SHARED_LIBRARY_NAME, DEFAULT_AOT_SHARED_LIBRARY_NAME);
        //flutterAsset
        flutterAssetsDir = metadata.getString(PUBLIC_FLUTTER_ASSETS_DIR_KEY, DEFAULT_FLUTTER_ASSETS_DIR);
        //BuildConfig.DEBUG || BuildConfig.JIT_RELEASE使用,AOT Release版本flutter代码打包成so包。
        //ensureInitializationComplete()中可以验证
        vmSnapshotData = metadata.getString(PUBLIC_VM_SNAPSHOT_DATA_KEY, DEFAULT_VM_SNAPSHOT_DATA);
        isolateSnapshotData = metadata.getString(PUBLIC_ISOLATE_SNAPSHOT_DATA_KEY, DEFAULT_ISOLATE_SNAPSHOT_DATA);
}
//initResources 初始化资源,方法名自解释。
private void initResources(@NonNull Context applicationContext) {
        new ResourceCleaner(applicationContext).start();

        if (BuildConfig.DEBUG || BuildConfig.JIT_RELEASE) {
            final String dataDirPath = PathUtils.getDataDirectory(applicationContext);
            final String packageName = applicationContext.getPackageName();
            final PackageManager packageManager = applicationContext.getPackageManager();
            final AssetManager assetManager = applicationContext.getResources().getAssets();
            resourceExtractor = new ResourceExtractor(dataDirPath, packageName, packageManager, assetManager);

            resourceExtractor
                .addResource(fullAssetPathFrom(vmSnapshotData))
                .addResource(fullAssetPathFrom(isolateSnapshotData))
                .addResource(fullAssetPathFrom(DEFAULT_KERNEL_BLOB));

            resourceExtractor.start();
        }
}

ensureInitializationComplete()

public void ensureInitializationComplete(@NonNull Context applicationContext, @Nullable String[] args) {
    if (initialized) {
        return;
    }
    if (Looper.myLooper() != Looper.getMainLooper()) {
      throw new IllegalStateException("ensureInitializationComplete must be called on the main thread");
    }
    if (settings == null) {
      throw new IllegalStateException("ensureInitializationComplete must be called after startInitialization");
    }
    try {
        if (resourceExtractor != null) {
            resourceExtractor.waitForCompletion();
        }
 
        List<String> shellArgs = new ArrayList<>();
        shellArgs.add("--icu-symbol-prefix=_binary_icudtl_dat");
 
        ApplicationInfo applicationInfo = getApplicationInfo(applicationContext);
        shellArgs.add("--icu-native-lib-path=" + applicationInfo.nativeLibraryDir + File.separator + DEFAULT_LIBRARY);
 
        if (args != null) {
            Collections.addAll(shellArgs, args);
        }
 
        String kernelPath = null;
        //DEBUG/JIT_RELEASE加载逻辑
        if (BuildConfig.DEBUG || BuildConfig.JIT_RELEASE) {
            String snapshotAssetPath = PathUtils.getDataDirectory(applicationContext) + File.separator + flutterAssetsDir;
            kernelPath = snapshotAssetPath + File.separator + DEFAULT_KERNEL_BLOB;
            shellArgs.add("--" + SNAPSHOT_ASSET_PATH_KEY + "=" + snapshotAssetPath);
            shellArgs.add("--" + VM_SNAPSHOT_DATA_KEY + "=" + vmSnapshotData);
            shellArgs.add("--" + ISOLATE_SNAPSHOT_DATA_KEY + "=" + isolateSnapshotData);
        } else {//AOT Release加载逻辑
            shellArgs.add("--" + AOT_SHARED_LIBRARY_NAME + "=" + aotSharedLibraryName);

            //热更新可指定AOT_SHARED_LIBRARY_NAME为hotfix.so地址
            //hotfix.so拷贝到data/data/package/app_libs/目录下
            shellArgs.add("--" + AOT_SHARED_LIBRARY_NAME + "=" + applicationInfo.nativeLibraryDir + File.separator + aotSharedLibraryName);
        }
 
        shellArgs.add("--cache-dir-path=" + PathUtils.getCacheDirectory(applicationContext));
        if (settings.getLogTag() != null) {
            shellArgs.add("--log-tag=" + settings.getLogTag());
        }
 
        String appStoragePath = PathUtils.getFilesDir(applicationContext);
        String engineCachesPath = PathUtils.getCacheDirectory(applicationContext);
        FlutterJNI.nativeInit(applicationContext, shellArgs.toArray(new String[0]),
            kernelPath, appStoragePath, engineCachesPath);
 
        initialized = true;
    } catch (Exception e) {
        Log.e(TAG, "Flutter initialization failed.", e);
        throw new RuntimeException(e);
    }
}

shellArgs.add("--" + AOT_SHARED_LIBRARY_NAME + "=" + aotSharedLibraryName)

shellArgs是个数组,包含so包和资源文件,最终调用FlutterJNI.nativeInit()加载flutter资源。实现热更新可以从这个数组入手。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,793评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,567评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,342评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,825评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,814评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,680评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,033评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,687评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,175评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,668评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,775评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,419评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,020评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,206评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,092评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,510评论 2 343

推荐阅读更多精彩内容