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

夙愿已清 提交于 2019-12-03 13:06:02

问题


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 .


回答1:


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



回答2:


getSystemService is a non static method of the Context class, so in order to access it you need an object from the class Context.Typically you call it from inside an Activty where this is also an object of Context . In order to fix you could pass a Context to your method isNetworkConnected




回答3:


now we can use static function getContext() to get the context which inherit from Cocos2dxActivity.java



来源:https://stackoverflow.com/questions/17992637/cannot-make-a-static-reference-to-the-non-static-method-getsystemservicestring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!