我正在尝试检查非活动类的互联网连接.
我使用以下代码:
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.我怎样才能获得系统服务?
传递Context从Activity你在
public boolean isNetworkAvailable(Context c) {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
Run Code Online (Sandbox Code Playgroud)
因此,如果从调用Activity使用像这样打发Activity的Context
boolean hasConnection = isNetworkAvailable(this);
Run Code Online (Sandbox Code Playgroud)
显然在创建了封闭类的实例之后
| 归档时间: |
|
| 查看次数: |
1816 次 |
| 最近记录: |