how to close the android application if there is no internet
我正在尝试创建一个基于谷歌表单的Android项目,我希望应用程序关闭或不显示链接,如果它无法连接到互联网,这里是代码,尝试使用退出,但它没有工作,任何帮助 会很棒。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | package tscolari.mobile_sample; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class AndroidMobileAppSampleActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView mainWebView = (WebView) findViewById(R.id.mainWebView); WebSettings webSettings = mainWebView.getSettings(); webSettings.setJavaScriptEnabled(true); mainWebView.setWebViewClient(new MyCustomWebViewClient()); mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); mainWebView.loadUrl("the url of form"); } private class MyCustomWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } } i want something like this if(mainwebview==null)//not able to load page { //close the application } |
用它来检查互联网连接:
[注意:这不是我原来的代码。 我从教程中接过它,但我不知道哪一个]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class CheckNetworkConnection { public static boolean isConnectionAvailable(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected() && netInfo.isConnectedOrConnecting() && netInfo.isAvailable()) { return true; } } return false; } } |
基本上,只需要做一个
编辑:正如Xaver Kapeller在评论中澄清的那样,
我正在检查互联网连接
1 2 3 4 5 6 7 8 9 10 11 12 | public static boolean isInternetAvailable(Context cxt) { final ConnectivityManager conMgr = (ConnectivityManager) cxt .getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo i = conMgr.getActiveNetworkInfo(); // if there is no active internet connection if (i == null || !i.isConnected() || !i.isAvailable()) { return false; } return true; } |
您可以使用finish()退出应用程序,但是您应该让用户知道为什么要关闭应用程序。