简体   繁体   中英

android application crashes if no internet

I am using this code to check the network availability for the android application.

public boolean isOnline(Context ctx) {
        ConnectivityManager conMgr =  (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo i = conMgr.getActiveNetworkInfo();
          if (i == null)
            return false;
          if (!i.isConnected())
            return false;
          if (!i.isAvailable())
            return false;
          return true;
    }

But if am connect to a WiFi network but no internet is accessible in that network then how I will check that internet is not available, actually my application crashes and I want to show alert box instead of crashing the application!

Does somebody know how to check internet availability?

This is error log:

http://licrp.dnsalias.net:8000/iteam/images/error.jpg

If you just want to be sure that you are connected to wifi and have an internet connection you could just ping a known adress, for example google which is usually online :)

URL url = new URL("http://www.google.com");
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
int responseCode = conn.getResponseCode();
//if responseCode = 200 - THEn CONN is connected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM