Nullpointerexception getSystemService
Following line will only not result in a nullpointer exception if I'm connected to a WLAN:
ConnectivityManager cm = (ConnectivityManager) getSystem开发者_运维百科Service(Context.CONNECTIVITY_SERVICE);
Otherwise I get a nullpointer-exception straight ahead? How can I fix this? I want my background service to only work, when it is connected to wlan. But that Nullpointerexception just kills the whole app...
Add to the manifest the following line:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Yes, I am late but in case someone is still looking,
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
no need of Context
in the getSystemService()
argument.
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == 1) {
// CONNECTION_WIFI = true;
}
精彩评论