如何在WebView Android中添加自定义错误消息?

时间:2015-03-06 18:03:05

标签: android

大家好我正在为大学项目创建一个Web视图应用

问题是,当互联网不可用时,网络视图显示网页不可用

但我想要的是显示消息或图像说你需要连接到互联网才能使用这个应用程序

那我该如何实施呢?

2 个答案:

答案 0 :(得分:1)

实施您自己的WebViewClient并处理您收到的错误:

 private WebViewClient webViewClient = new WebViewClient() {

@Override
public void onPageFinished(WebView view, String url) {

}

public void onReceivedSslError(WebView view, SslErrorHandler handler,
    SslError error) {

}

public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

        Toast.makeText(yourContext,"Check your connection",Toast.LENGHT_LONG).show();
        //check for the type of your error in errorCode and treat errors as you wish. You can even make the webview load something else(like an image you choose) when you encounter an error.
}
};

 yourWebView.setWebViewClient(webViewClient);

答案 1 :(得分:0)

使用此方法检查是否存在Internet连接

public class ConnectivityDetector {

private Context ctxt;

public ConnectivityDetector(Context context){
    this.ctxt = context;
}

public boolean isConnectedToInternet(){
    ConnectivityManager connectivityManager = (ConnectivityManager)ctxt.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null){
        NetworkInfo[] infos = connectivityManager.getAllNetworkInfo();
        if (infos != null)
            for (int i = 0; i < infos.length; i++)
                if (infos[i].getState() == NetworkInfo.State.CONNECTED){
                    return true;
                }
    }
    return false;
}

}

然后,在使用webview的活动中,执行此操作

ConnectivityDetector cd = new ConnectivityDetector(context);
Boolean isConnected = cd.isConnectedToInternet;
// this will return true if connected and false if not.

现在,在您的xml中,创建一个带有初始可见性的文本视图。

现在,在活动中,

if (isConnectedToInternet){
    //do nothing
  } else {
     webview.setVisibility(GONE);
     txtview.setText("Please connect to Internet");
     txtview.setVisibility(VISIBLE);
  }

您可以选择自己的方式来显示其他部分

中无法使用互联网连接