不能让一个静态引用从类型的非静态方法getSystemService(字符串) [英] Cannot make a static reference to the non-static method getSystemService(String) from the type

查看:902
本文介绍了不能让一个静态引用从类型的非静态方法getSystemService(字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能,网络连接

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

但是,当IA试图使其静态的,这样我可以用它在每一个活动是扔的无法从类型使静态引用非静态方法getSystemService(字符串) 我不想创建该类的每一次的对象。

But when i a trying to make it static so that i can use it in every activity it is throwing a 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 .

推荐答案

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

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

这也是依赖注入的最基本的形式。

This is also the most basic form of dependency injection.

这篇关于不能让一个静态引用从类型的非静态方法getSystemService(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆