I am trying to check for a internet connection in a class that is not an activity.
i am using the following code:
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
but the following line of code is underlined red:
getSystemService(Context.CONNECTIVITY_SERVICE)
I am assuming that it is because it cannot get systemService. How can i get the system service?
Pass the Context from the Activity you are in
public boolean isNetworkAvailable(Context c) {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
So if calling from an Activity use something like this to pass the Activity's Context
boolean hasConnection = isNetworkAvailable(this);
Obviously after creating an instance of the enclosing class
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