【问题标题】:Cannot make a static reference to the non-static method getSystemService(String) from the type无法从类型中对非静态方法 getSystemService(String) 进行静态引用
【发布时间】:2013-08-02 07:00:57
【问题描述】:

我有这个功能哪个网络连接

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

但是当我试图将其设为静态以便我可以在它抛出的每个活动中使用它时:

无法对非静态方法进行静态引用 getSystemService(String) 从类型中

我不想每次都创建类的对象。

【问题讨论】:

    标签: android android-intent android-networking android-internet


    【解决方案1】:

    现在我们可以使用静态函数getContext() 来获取继承自Cocos2dxActivity.java 的上下文

    【讨论】:

    • 请提供使用示例
    【解决方案2】:

    添加非静态依赖作为参数:

    public static boolean isNetworkConnected(Context c) {
          ConnectivityManager conManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo netInfo = conManager.getActiveNetworkInfo();
          return ( netInfo != null && netInfo.isConnected() );
    }
    

    【讨论】:

    • 什么是非静态依赖(什么应该作为参数传递)
    【解决方案3】:

    getSystemServiceContext 类的非静态方法,因此为了访问它,您需要一个来自类 Context 的对象。通常您从 Activty 内部调用它,其中 this 也是Context 。为了修复,您可以将 Context 传递给您的方法 isNetworkConnected

    【讨论】:

    • @marthajames 不清楚“将上下文传递给您的方法”的哪一部分?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多