这一节我们要继续接着上一节的内容,来讲讲插件的加载过程。

二. 插件加载过程:从Bundle 步入 BundleLauncher
上一节我们读到loadBundle中,里面涉及一个方法prepareForLaunch,我没有继续往下详解,搬来这里继续给大家做个介绍。
(1)步入BundleLauncher的 loadBundle的前期准备。
1 | private static void loadBundles(List<Bundle> bundles) { |
sBundleLaunchers这个变量已经很熟悉,在前面已经多次出现了,我们来回忆一下。
里面只有三个类ApkBundleLauncher、ActivityLauncher、WebBundleLauncher,前面已经作了部分解释,从上图可知。三者的祖先都是BundleLauncher,resolveBundle方法定义在此处。
1 | /** |
这里会继续调用preloadBundle的方法来判断,然后我发现preloadBundle在ActivityLauncher和SoBundleLauncher(直接影响ApkBundleLauncher、WebBundleLauncher)中重载了。
1.ActivityLauncher的preloadBundle
1 |
|
sActivityClasses是在ActivityLauncher setUp被填充的,它里面有宿主已经注册好的Activity。sActivityClasses一般不会为null,因此都进入判断pkg地方,pkg即包路径,因此preloadBundle会返回false,resolveBundle也会返回false,导致ActivityLauncher会被略过。
ActivityLauncher 它的作用是启动宿主的Activity。如果bundle.json里pkg为空或者pkg为”main”的bundle,ActivityLauncher也不做特殊处理,因为loadBundle在ActivityLauncher中不被重载,仍为空方法。当启动的时候,把bundle里的uri当作Activity的类名。URI转换为Activity的名字规则如下:如果URI是空的,默认是MainActivity,否则使用URI,如果类不存在,加“Activity”后缀再进行查找。
2.SoBundleLauncher的preloadBundle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
public boolean preloadBundle(Bundle bundle) {
String packageName = bundle.getPackageName();
if (packageName == null) return false;
// Check if supporting
String[] types = getSupportingTypes();
if (types == null) return false;
boolean supporting = false;
String bundleType = bundle.getType();
if (bundleType != null) {
//这里为了解除对先前版本对包名的限制(*.lib.*或者*.app.*),如果在bundle.json声明type属性为“lib”或者“app”,将忽略包名限制
// Consider user-defined type in `bundle.json'
for (String type : types) {
if (type.equals(bundleType)) {
supporting = true;
break;
}
}
} else {
// Consider explicit type specify in package name as following:
// - com.example.[type].any
// - com.example.[type]any
String[] pkgs = packageName.split("\\.");
int N = pkgs.length;
String aloneType = N > 1 ? pkgs[N - 2] : null;
String lastComponent = pkgs[N - 1];
for (String type : types) {
if ((aloneType != null && aloneType.equals(type))
|| lastComponent.startsWith(type)) {
supporting = true;
break;
}
}
}
if (!supporting) return false;
// Initialize the extract path
File extractPath = getExtractPath(bundle);//重载在ApkBundleLauncher和WebBundleLauncher中,定义不同的路径。
if (extractPath != null) {
if (!extractPath.exists()) {
extractPath.mkdirs();
}
bundle.setExtractPath(extractPath);
}
//至此,存储的目录准备好了
// Select the bundle entry-point, `built-in' or `patch'
File plugin = bundle.getBuiltinFile();
BundleParser parser = BundleParser.parsePackage(plugin, packageName);
File patch = bundle.getPatchFile();
BundleParser patchParser = BundleParser.parsePackage(patch, packageName);
if (parser == null) {
if (patchParser == null) {
return false;
} else {
parser = patchParser; // use patch
plugin = patch;
}
} else if (patchParser != null) {
if (patchParser.getPackageInfo().versionCode <= parser.getPackageInfo().versionCode) {
//排除补丁版本号过低
Log.d(TAG, "Patch file should be later than built-in!");
patch.delete();
} else {
parser = patchParser; // use patch
plugin = patch;
}
}
bundle.setParser(parser);
// Check if the plugin has not been modified
long lastModified = plugin.lastModified();
long savedLastModified = Small.getBundleLastModified(packageName);
if (savedLastModified != lastModified) {//文件已被修改
// If modified, verify (and extract) each file entry for the bundle
if (!parser.verifyAndExtract(bundle, this)) {//校验CRC、签名等,通过安排解压IO事项
bundle.setEnabled(false);
return true; // Got it, but disabled
}
Small.setBundleLastModified(packageName, lastModified);//标记最后修改时间
}
// Record version code for upgrade
PackageInfo pluginInfo = parser.getPackageInfo();
bundle.setVersionCode(pluginInfo.versionCode);
bundle.setVersionName(pluginInfo.versionName);
return true;
}
BundleParser 是一个精简版的PackageParser.java,用来解析AndroidManifest文件,获取package.versionCode,package.versionName,package.theme,activities,同时也会收集每个Activity对应的intent-filter。 这个类里还定义了一个内部类R,R文件里包含一个styleable类,此文件定义了平台公共资源ID,例如版本号id,版本名称id,主题Id等。
(2)步入BundleLauncher的 loadBundle
这里loadBundle方法在SoBundleLauncher子类(ApkBundleLauncher、AssetBundleLauncher)中被重载,先挑一个简短的看看,也就是AssetBundleLauncher的loadBundle。
- AssetBundleLauncher的loadBundle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public void loadBundle(Bundle bundle) {
String packageName = bundle.getPackageName();
File unzipDir = new File(getBasePath(), packageName);
File indexFile = new File(unzipDir, getIndexFileName());
// Prepare index url
String uri = indexFile.toURI().toString();
if (bundle.getQuery() != null) {
uri += "?" + bundle.getQuery();
}
URL url;
try {
url = new URL(uri);
} catch (MalformedURLException e) {
Log.e(TAG, "Failed to parse url " + uri + " for bundle " + packageName);
return;
}
String scheme = url.getProtocol();
if (!scheme.equals("http") &&
!scheme.equals("https") &&
!scheme.equals("file")) {
Log.e(TAG, "Unsupported scheme " + scheme + " for bundle " + packageName);
return;
}
bundle.setURL(url);
}
这个过程主要是尝试将默认的index.html 转换成URL对象。
- ApkBundleLauncher的loadBundle
这里主要是通过BundleParser解释AndroidManifest.xml,收集其中的activities,初始化LoadedApk的一些信息,加载Dex文件以及lib库。
1 |
|
使用sLoadedActivities记录插件中的activities来实现Intent重定向,使用sLoadedIntentFilters记录intent-filters来实现隐式调用。
(3)重新回到Bundle.loadBundles,分发到各个launcher postSetUp()
postSetUp前后都等待WebView 初始化完成,避免WebView asset路径影响。
1 | private static void loadBundles(List<Bundle> bundles) { |
有效的postSetUp仅存与ApkBundleLauncher:
1 |
|
这里可以看到它通过ReflectAccelerator.mergeResources去合并资源,里面特意增加对Android7.0的WebView Assets处理。这些过程都在反射的协助下完成。
1 | AssetManager newAssetManager; |
继续通过ReflectAccelerator.expandDexPathList合并Dex
1 | public static boolean expandDexPathList(ClassLoader cl, String[] dexPaths, DexFile[] dexFiles) { |
ReflectAccelerator.expandNativeLibraryDirectories继续加载JNI Native库:
1 | public static void expandNativeLibraryDirectories(ClassLoader classLoader, List<File> libPath) { |
往下就对每个插件的Application的OnCreate事件进行分发。
1 | // Trigger all the bundle application `onCreate' event |
这里还会加载Provider的内容。
1 | // Lazy init content providers |
Small.preSetUp 已有对providers的处理1
2
3
4
5
6
7
8
9
10
11// Get providers
try {
f = thread.getClass().getDeclaredField("mBoundApplication");
f.setAccessible(true);
Object/*AppBindData*/ data = f.get(thread);
f = data.getClass().getDeclaredField("providers");
f.setAccessible(true);
providers = (List<ProviderInfo>) f.get(data);
} catch (Exception e) {
throw new RuntimeException("Failed to get providers from thread: " + thread);
}
这里重新加载,是为了增添一些容错处理。
1 |
|
至此,启动流程的插件加载也说完了。整个启动过程基本就到这里了。
下一节我会介绍继续Small的更新流程的源码。
敬请期待!!!
