从外部类/获取系统服务检查android连接

Zap*_*ica 3 android

我正在尝试检查非活动类的互联网连接.

我使用以下代码:

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();        
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

但是下面的代码行用红色加下划线:

getSystemService(Context.CONNECTIVITY_SERVICE)
Run Code Online (Sandbox Code Playgroud)

我假设它是因为它无法获得systemService.我怎样才能获得系统服务?

cod*_*gic 5

传递ContextActivity你在

public boolean isNetworkAvailable(Context c) {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
Run Code Online (Sandbox Code Playgroud)

因此,如果从调用Activity使用像这样打发ActivityContext

boolean hasConnection = isNetworkAvailable(this);
Run Code Online (Sandbox Code Playgroud)

显然在创建了封闭类的实例之后