How to check if an Android device is turned on
2 answers
Create a helper method called isNetworkAvailable () that will return true or false depending on network availability 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 permissions to your manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Edit: The above method checks if the network is available. It does not check if the device can actually connect to the Internet. The best way to check for an internet connection is to try connecting to a 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 in the main thread, otherwise it will throw your NetworkOnMainThreadException. Use AsyncTask or something similar.
+14
source to share
public boolean isOnline() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnectedOrConnecting()){
return true;
}
else{
return false
}
}
0
source to share