上一章讲述了Cordova的入口CordovaActivity
类的实现方法,在这个类中实现了webview的创建和对Html的加载,那么这章就来分析下Cordova中webview是如何封装的。
CordovaWebViewImpl类
CordovaWebViewImpl
类实现了CordovaWebView
接口,实现了接口方法。这个类在上一章的CordovaActivity中被调用,此类从上到下暴露出的主要接口设计分为以下几类:
- 构造方法
- init方法
- loadUrl方法
- CordovaWebViewEngine的方法实现
- 生命周期方法
- CordovaWebViewEngine.Client 接口的实现
构造方法
public CordovaWebViewImpl(CordovaWebViewEngine cordovaWebViewEngine) {
this.engine = cordovaWebViewEngine;
}
构造方法需要传递一个CordovaWebViewEngine
的实例,在CordovaActivity
中已经初始化了CordovaWebViewEngine 实例,并传递过来,而创建CordovaWebViewEngine 实例的方法就是调用了CordovaWebViewImpl类的createEngine方法:
public static CordovaWebViewEngine createEngine(Context context, CordovaPreferences preferences) {
String className = preferences.getString("webview", SystemWebViewEngine.class.getCanonicalName());
try {
Class<?> webViewClass = Class.forName(className);
Constructor<?> constructor = webViewClass.getConstructor(Context.class, CordovaPreferences.class);
return (CordovaWebViewEngine) constructor.newInstance(context, preferences);
} catch (Exception e) {
throw new RuntimeException("Failed to create webview. ", e);
}
}
这个方法使用反射的方式初始化了SystemWebViewEngine类,为何使用反射,是因为cordova在config.xml中可以配置自己的WebViewEngine,而cordova自带的是SystemWebViewEngine类(TODO 后续分析)。
init
方法
在CordovaActivity
中不仅调用了CordovaWebViewImpl的loadUrl方法,还调用了CordovaWebViewImpl的init方法,重现一下调用代码:
if (!appView.isInitialized()) {
appView.init(cordovaInterface, pluginEntries, preferences);
}
回过头来查看CordovaWebViewImpl的init方法,分析做了哪些工作。
@SuppressLint("Assert")
@Override
public void init(CordovaInterface cordova, List<PluginEntry> pluginEntries, CordovaPreferences preferences) {
if (this.cordova != null) {
throw new IllegalStateException();
}
// 初始化CordovaInterface
this.cordova = cor