WebView需要花费太多时间来加载

时间:2018-04-25 05:14:36

标签: android android-layout android-studio android-fragments android-webview

我正在开发一个应用程序,我想在WebView中加载报纸链接,但问题是我的WebView需要花费太多时间来加载报纸,如果我在浏览器中打开它,那么它加载速度快。我已经编写了web设置也。请帮忙。

代码:

    webView = (WebView)findViewById(R.id.webView);//Use the WebView defined in your layout.
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    webView.getSettings().setAppCacheEnabled(true);
    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webSettings.setDomStorageEnabled(true);
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    webSettings.setUseWideViewPort(true);
    webSettings.setSavePassword(true);
    webSettings.setSaveFormData(true);
    webSettings.setEnableSmoothTransition(true);


    final Activity activity = this;
    webView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {

        }
    });
    webView.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(activity, "Some error occurred. " + description, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            progressBar.setVisibility(View.VISIBLE);
            webView.setVisibility(View.GONE);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            progressBar.setVisibility(View.GONE);
            webView.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);
        }

    });

    webView.loadUrl(url);

在Manifest中:

      <application
          android:hardwareAccelerated="true"/>

1 个答案:

答案 0 :(得分:0)

在清单文件中添加如下:

<application android:hardwareAccelerated="true">
    <activity ... />
    <activity android:hardwareAccelerated="false" />
</application>

在您使用webview的活动中,在setContentView()之前放置下面的代码:

getWindow().setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

最后,在您的代码中执行以下操作:

if (Build.VERSION.SDK_INT >= 19) {
     webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}       
else {
     webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}