我们知道在使用webview的时候需要先创建一个weview,即
WebView webView = new WebView(context)
今天我们通过源码来分析这个WebView的创建过程。当我们使用上面的代码创建webview之后,会调用到下面WebView的构造方法中,这里除了context参数之后其他的都是默认值
protected WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes,
Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
super(context, attrs, defStyleAttr, defStyleRes);
// WebView is important by default, unless app developer overrode attribute.
if (getImportantForAutofill() == IMPORTANT_FOR_AUTOFILL_AUTO) {
setImportantForAutofill(IMPORTANT_FOR_AUTOFILL_YES);
}
if (context == null) {
throw new IllegalArgumentException("Invalid context argument");
}
sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >=
Build.VERSION_CODES.JELLY_BEAN_MR2;
//1.线程检查
checkThread();
//2.创建WebViewProvider
ensureProviderCreated();
//3.初始化WebViewProvider
mProvider.init(javaScriptInterfaces, privateBrowsing);
// Post condition of creating a webview is the CookieSyncManager.getInstance() is allowed.
CookieSyncManager.setGetInstanceIsAllowed();
}
从上面的创建过程可以知道这里主要分3步
- 进行线程检查
- 初始化WebViewProvider
- 初始化这个provider。
接下来我们仔细分析下第二和第三步
创建WebViewProvider
我们看下创建WebViewProvider的源码过程,也就是WebView中ensureProviderCreated()方法
private void ensureProviderCreated() {
checkThread();
if (mProvider == null) {
// As this can get called during the base class constructor chain, pass the minimum
// number of dependencies here; the rest are deferred to init().
//主要过程分为两步
//1.getFactory
//2.createWebView
mProvider = getFactory().createWebView(this, new PrivateAccess());
}
}
private static WebViewFactoryProvider getFactory() {
return WebViewFactory.getProvider();
}
这里会调用WebViewFactory 的getProvider方法:
- getProv