如果我连接到WLAN,以下行只会导致空指针异常:
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
否则我会直接得到一个nullpointer-exception?我怎样才能解决这个问题?我希望我的后台服务只有在与wlan连接时才能工作。但是Nullpointerexception只会杀死整个应用......
答案 0 :(得分:2)
向清单添加以下行:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 1 :(得分:-1)
是的,我迟到了,万一有人还在看,
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
Context
参数中不需要getSystemService()
。
答案 2 :(得分:-2)
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == 1) {
// CONNECTION_WIFI = true;
}