当互联网不可用时,如何在webview中加载自定义错误页面?

时间:2014-03-05 19:50:57

标签: android webview loading

我想在没有互联网连接时加载自定义html页面。我不想使用常规的,所以有人可以填写缺少的东西吗?我对此很陌生,所以我按照说明操作。如果需要其他任何许可,请告诉我。 这是我的代码:

MainActivity:

package com.example.app;

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);
        mWebView.loadUrl("http://domain.com");

    // Force links and redirects to open in the WebView instead of in a browser
    mWebView.setWebViewClient(new WebViewClient());
    // Stop local links and redirects from opening in browser instead of WebView
    mWebView.setWebViewClient(new MyAppWebViewClient());

    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.getSettings().setUseWideViewPort(true);
    mWebView.setInitialScale(1);
}

@Override
// Detect when the back button is pressed
public void onBackPressed() {
    if(mWebView.canGoBack()) {
        mWebView.goBack();
    } else {
        // Let the system handle the back button
        super.onBackPressed();
    }
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

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

}

1 个答案:

答案 0 :(得分:4)

检查互联网是否已连接..

   private boolean haveNetworkConnection() {
      boolean haveConnectedWifi = false;
      boolean haveConnectedMobile = false;

      ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo[] netInfo = cm.getAllNetworkInfo();

  for (NetworkInfo ni : netInfo) {
     if (ni.getTypeName().equalsIgnoreCase("WIFI"))
        if (ni.isConnected())
            haveConnectedWifi = true;
    if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
        if (ni.isConnected())
            haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}

现在在加载页面时检查条件

    if(haveNetworkConnection()){
        mWebView.loadUrl("http://domain.com");
   } else {
    mWebView.loadUrl("file:///android_asset/custom.html");
   }

将此权限添加到您的清单文件中。

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