安卓Webview网页秒开策略探索

痛点是什么?
网页加载缓慢,白屏,使用卡顿。
为何有这种问题?
1.调用loadUrl()方法的时候,才会开始网页加载流程
2.js臃肿问题
3.加载图片太多
4.webview本身问题
webiew是怎么加载网页的呢?
webview初始化->DOM下载→DOM解析→CSS请求+下载→CSS解析→渲染→绘制→合成
优化方向是?
1.webview本身优化

提前内核初始化
代码:

public class App extends Application {

private WebView mWebView ;
@Override
public void onCreate() {
    super.onCreate();
    mWebView = new WebView(new MutableContextWrapper(this));
}

}
复制代码效果:初次内核初始化大概2000ms,第二次50ms以内

webview复用池
代码:

public class WebPools {
private final Queue mWebViews;
private Object lock = new Object();
private static WebPools mWebPools = null;
private static final AtomicReference mAtomicReference = new AtomicReference<>();
private static final String TAG=WebPools.class.getSimpleName();

private WebPools() {
    mWebViews = new LinkedBlockingQueue<>();
}
public static WebPools getInstance() {
    for (; ; ) {
        if (mWebPools != null)
            return mWebPools;
        if (mAtomicReference.compareAndSet(null, new WebPools()))
            return mWebPools=mAtomicReference.get();
    }
}
public void recycle(WebView webView) {
    recycleInternal(webView);
}
public WebView acquireWebView(Activity activity) {
    return acquireWebViewInternal(activity);
}
private WebView acquireWebViewInternal(Activity activity) {
    WebView mWebView = mWebViews.poll();
    LogUtils.i(TAG,"acquireWebViewInternal  webview:"+mWebView);
    if (mWebView == null) {
        synchronized (lock) {
            return new WebView(new MutableContextWrapper(activity));
        }
    } else {
        MutableContextWrapper mMutableContextWrapper = (MutableContextWrapper) mWebView.getContext();
        mMutableContextWrapper.setBaseContext(activity);
        return mWebView;
    }
}
private void recycleInternal(WebView webView) {
    try {
        if (webView.getContext() instanceof MutableContextWrapper) {
            MutableContextWrapper mContext = (MutableContextWrapper) webView.getContext();
         mContext.setBaseContext(mContext.getApplicationContext());
            LogUtils.i(TAG,"enqueue  webview:"+webView);
            mWebViews.offer(webView);
        }
        if(webView.getContext() instanceof  Activity){
            //throw new RuntimeException("leaked");
            LogUtils.i(TAG,"Abandon this webview  , It will cause leak if enqueue !");
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

}
复制代码带来的问题:内存泄漏

独立进程,进程预加载
代码:

    <service
        android:name=".PreWebService"
        android:process=":web"/>
    <activity
        android:name=".WebActivity"
        android:process=":web"/>

复制代码启动webview页面前,先启动PreWebService把[web]进程创建了,当启动WebActivity时,系统发

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值