Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check android connection from outside class / get system service

Tags:

android

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?

like image 856
Zapnologica Avatar asked Jan 25 '26 19:01

Zapnologica


1 Answers

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

like image 154
codeMagic Avatar answered Jan 29 '26 12:01

codeMagic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!