To determine when the device has a network connection, request the permission <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
and then you can check with the following code. First define these variables as class variables.
private Context c;
private boolean isConnected = true;
In your onCreate()
method initialize c = this;
Then check for connectivity.
ConnectivityManager connectivityManager = (ConnectivityManager)
c.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni.getState() != NetworkInfo.State.CONNECTED) {
// record the fact that there is not connection
isConnected = false;
}
}
Then to intercept the WebView
requets, you could do something like the following. If you use this, you will probably want to customize the error messages to include some of the information that is available in the onReceivedError
method.
final String offlineMessageHtml = "DEFINE THIS";
final String timeoutMessageHtml = "DEFINE THIS";
WebView browser = (WebView) findViewById(R.id.webview);
browser.setNetworkAvailable(isConnected);
browser.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (isConnected) {
// return false to let the WebView handle the URL
return false;
} else {
// show the proper "not connected" message
view.loadData(offlineMessageHtml, "text/html", "utf-8");
// return true if the host application wants to leave the current
// WebView and handle the url itself
return true;
}
}
@Override
public void onReceivedError (WebView view, int errorCode,
String description, String failingUrl) {
if (errorCode == ERROR_TIMEOUT) {
view.stopLoading(); // may not be needed
view.loadData(timeoutMessageHtml, "text/html", "utf-8");
}
}
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…