2013-08-05 32 views
3

我正在尝试检查不是活动的类中的Internet连接。检查从外部类的Android连接/获取系统服务

我用下面的代码:

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

,但下面的代码行被红色下划线:

getSystemService(Context.CONNECTIVITY_SERVICE) 

我假设,这是因为它不能得到systemService。我如何获得系统服务?

回答

5

Activity你是在传递Context前derrived

public boolean isNetworkAvailable(Context c) { 
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); 

所以如果从Activity使用这样的事情来通过ActivityContext

boolean hasConnection = isNetworkAvailable(this); 

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

0

context.getSystemService(Context.CONNECTIVITY_SERVICE)使用该活动从上下文这就是为什么你可以使用getSystemService一个活动,而不必背景下,