デバイスがネットワークに接続されているかどうかを判断するには、アクセス許可<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
を要求してから、次のコードで確認できます。まず、これらの変数をクラス変数として定義します。
private Context c;
private boolean isConnected = true;
onCreate()
メソッドで初期化しますc = this;
次に、接続を確認します。
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;
}
}
次に、リクエストをインターセプトするにはWebView
、次のようにします。これを使用する場合、おそらくエラー メッセージをカスタマイズして、onReceivedError
メソッドで利用可能な情報の一部を含めることをお勧めします。
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");
}
}
});