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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With