Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an android device is online

Tags:

android

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

like image 409
Erwin Daez Avatar asked Nov 29 '22 10:11

Erwin Daez


1 Answers

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.

like image 159
Bidhan Avatar answered Dec 15 '22 22:12

Bidhan