I have this function which network connection
public boolean isNetworkConnected() {
ConnectivityManager conManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conManager.getActiveNetworkInfo();
if (netInfo == null) {
// There are no active networks.
return false;
} else {
return true;
}
}
But when i a trying to make it static so that i can use it in every activity it is throwing:
Cannot make a static reference to the non-static method getSystemService(String) from the type
I don't want to create the object of the class every time .
i.e. referring a variable using static reference implies to referring using the class name. But, to access instance variables it is a must to create an object, these are not available in the memory, before instantiation. Therefore, you cannot make static reference to non-static fields(variables) in Java.
Static Method Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.
Add the non-static dependencies as parameters:
public static boolean isNetworkConnected(Context c) {
ConnectivityManager conManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conManager.getActiveNetworkInfo();
return ( netInfo != null && netInfo.isConnected() );
}
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