Android Nullpointerexception getSystemService

Android Nullpointerexception getSystemService,android,Android,如果我连接到WLAN,以下行仅不会导致nullpointer异常: ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 否则我会得到一个空指针异常?我怎样才能解决这个问题?我希望我的后台服务仅在连接到wlan时工作。但是Nullpointerexception只会杀死整个应用程序…在清单中添加以下行: <uses-permission android:

如果我连接到WLAN,以下行仅不会导致nullpointer异常:

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

否则我会得到一个空指针异常?我怎样才能解决这个问题?我希望我的后台服务仅在连接到wlan时工作。但是Nullpointerexception只会杀死整个应用程序…

在清单中添加以下行:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

是的,我迟到了,但万一有人还在找

ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

getSystemService()
参数中不需要
Context

你确定是这一行引发了异常吗?似乎更可能的是
getSystemService()
会返回
null
,然后当您尝试使用
cm
时会抛出
null点异常。我和你有同样的想法。但我仔细检查了线路。正是这个。你能把堆栈跟踪贴出来吗?我不熟悉Android的工作原理,但在普通的JVM中,如果上下文是连接服务,那么该行不能抛出
NullPointerException
getSystemService()
方法可能会抛出这样一个异常,但该异常会显示在堆栈跟踪中。表示
连接\u服务
上下文
的静态成员。既然你忽略了它,我想你已经有了一个静态导入?
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();