Erwin Daez
Erwin Daez

Reputation: 145

How to check if an android device is online

My server constantly checks if my android application is online. May I ask what are the ways that I can do on my android application

Upvotes: 4

Views: 18861

Answers (2)

Umanda
Umanda

Reputation: 4843

public boolean isOnline() {
    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connManager.getActiveNetworkInfo();

    if(networkInfo != null && networkInfo.isConnectedOrConnecting()){
     return true;
    } 
    else{
       return false
    }
 }

Upvotes: 0

Bidhan
Bidhan

Reputation: 10687

Create a helper method called isNetworkAvailable() that will return true or false depending upon whether the network is available or not. It will look something like this

private boolean isNetworkAvailable() {
    ConnectivityManager manager =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        // Network is present and connected
        isAvailable = true;
    }
    return isAvailable;
}

Don't forget to add the following permission to your Manifest file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Edit: The above method only checks if the network is available. It doesn't check if the device can actually connect to the internet. The best way to check if there is an Internet connection present is to try and connect to some known server using HTTP

public static boolean checkActiveInternetConnection() {
if (isNetworkAvailable()) {
    try {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500); 
        urlc.connect();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error: ", e);
    }
} else {
    Log.d(LOG_TAG, "No network present");
}
 return false;
}

By the way, take care not to run the above method on your Main thread or it will give your NetworkOnMainThreadException. Use an AsyncTask or something equivalent.

Upvotes: 21

Related Questions