简体   繁体   中英

Checking Internet connection on Android

I need to check Internet connection on Android app.

I'm using this code:

 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni!=null && ni.isAvailable() && ni.isConnected()) {
            return true;
        } else {
            return false; 
        }

And cannot pass the next error:

The method getSystemService(String) is undefined for the type ConxsMTD

I tried using getContext().getSystemService and also failed with next error:

The method getContext() is undefined for the type ConxsMTD

Any idea what I'm doing wrong?

This doesn't fix your given example, but my example does work and is more simple (in my mind).

What you want to do is send a "ping" (if you want to call it that) to check the connection. If the connection completes, you know you are still connected. If you get an IOException or a NullPointerException , then you probably timed out and are not connected anymore.

try {
    URL url = new URL("http://www.google.com");
    HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
    urlConnect.setConnectTimeout(1000);
    urlConnect.getContent();
    System.out.println("Connection established.");
} catch (NullPointerException np) {
    np.printStackTrace();
} catch (IOException io) {
    io.printStackTrace();
}

Use this snippet, I use it in every project:

public static boolean checkNetworkState(Context context) {
    ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo infos[] = conMgr.getAllNetworkInfo();
    for (NetworkInfo info : infos) {
        if (info.getState() == State.CONNECTED)
            return true;
    }
    return false;
}

So, you only must pass getApplicationContext() to this method like boolean hasConnection = checkNetworkState(getApplicationContext());

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