我想从创建的资产文件夹中加载错误页面。一切工作正常,但如果没有互联网,则无法加载错误页面(即404.html)。我在MainActivity.java文件中使用以下代码段。

public class MainActivity extends ActionBarActivity {
    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.activity_main_webview);
        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.loadUrl("file:///android_asset/www/index.html");
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebViewClient(new MyAppWebViewClient());

        mWebView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                mWebView.loadUrl("file:///android_asset/www/404.html");

            }
        });

最佳答案

使用此方法检查互联网连接:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}


如果返回false,则显示错误页面

你会需要

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


清单中的ACCESS_NETWORK_STATE权限

编辑这样做:

public class MainActivity extends ActionBarActivity {
    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.activity_main_webview);
        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        if(isNetworkAvailable())
            mWebView.loadUrl("file:///android_asset/www/index.html");
        else
            mWebView.loadUrl("file:///android_asset/www/404.html");
    }

    private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

08-06 17:50