Zeige Netzwerkfehler in Android
Ich habe Appliction mit Webview erstellt. Wenn ich eine Aktion ausgeführt habe und das Netz nicht verbunden ist, möchte ich eine Warnung anzeigen. Ich habe Folgendes versucht:
hat dies in der Methode oncreate hinzugefügt.
public class AndroidNetTestActivity extends Activity {
public static WebView webview;
private Handler mHandler = new Handler();
private boolean isConnected = true;
final String offlineMessageHtml = "Net is disconnected";
final String timeoutMessageHtml = "Connection timed out";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview=(WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/www/index.htm");
webview.addJavascriptInterface(new MyJavaScriptInterface(), "Android");
isConnected=isNetworkAvailable();
webview.setNetworkAvailable(isConnected);
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
isConnected=isNetworkAvailable();
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");
}
}
});
webview.setWebChromeClient(new WebChromeClient());
}
final class MyJavaScriptInterface
{
public void ProcessJavaScript(final String scriptname, final String args)
{
mHandler.post(new Runnable()
{
public void run()
{
//ToDo
}
});
}
}
public boolean isNetworkAvailable() {
Context context = getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
//boitealerte(this.getString(R.string.alert),"getSystemService rend null");
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
Wenn ich auf die Schaltfläche "Anmelden" klicke, sollte eine Fehlermeldung angezeigt werden, wenn das Netz nicht verfügbar ist.
aber es funktioniert nicht. Bitte überprüfen Sie meinen Code und sagen Sie mir, was ich falsch gemacht habe