Cannot make a static reference to the non-static method getSystemService(String) from the type

Developer picture Developer · Aug 1, 2013 · Viewed 16.7k times · Source

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 .

Answer

S.D. picture S.D. · Aug 1, 2013

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() );
}