在android中加载webview时如何进行/忽略错误?

时间:2017-04-24 13:03:35

标签: android android-webview

我正在尝试在android中使用webview加载网址。这就是我的webview的样子

public class WebViewFragment extends Fragment {
private static final String LOG_TAG = WebViewFragment.class.getName();

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.web_view_fragment, container, false);
    init(rootView);
    return rootView;
}

private void init(View rootView) {
    Bundle bundle = getArguments();

    ImageView backButtonIV = (ImageView) rootView.findViewById(R.id.backButtonImage);
    backButtonIV.setOnClickListener(new PopBackStackClickListener(getActivity()));

    String title = bundle.getString(BundleConstants.WEB_HEADER_TEXT);
    TextView headerTextTV = (TextView) rootView.findViewById(R.id.pageTitle);
    headerTextTV.setText(title);

    WebView webView = (WebView) rootView.findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadsImagesAutomatically(true);
    webView.setWebViewClient(new MyWebView());

    String urlToLoad = bundle.getString(BundleConstants.WEB_URL);
    Log.d(LOG_TAG, "Opening url :" + urlToLoad);
    webView.loadUrl(urlToLoad);
}

private class MyWebView extends WebViewClient {
    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        return super.shouldInterceptRequest(view, request);
    }

    @Override
    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
        super.onReceivedHttpError(view, request, errorResponse);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        view.loadUrl(request.getUrl().toString());
        return true;
    }
}
}

我在onReceivedHttpEror上放了一个断点,发现有两个“未找到”的错误。基本上有两个.png文件找不到。因此,webview停止加载页面。如何忽略这些错误并继续?因为在android之外,如果我尝试打开链接,网页加载正常,错误只是记录在控制台中。但它不会妨碍页面的加载。如何在android webview中实现相同的功能并成功加载页面?

2 个答案:

答案 0 :(得分:0)

尝试用简单的日志记录替换onReceivedError和onReceivedHttpError覆盖中的代码(不要调用super)。

答案 1 :(得分:0)

试试这个,如果你不打电话,它应该起作用:

@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
    Log.d(LOG_TAG, "onReceivedError :" + error);
}

@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
    Log.d(LOG_TAG, "onReceivedHttpError:" + errorResponse);
}