marchest marchest - 9 days ago 5
Android Question

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

Im trying to check connection to the internet or if the device is connected to a wireless network.But can not resolved getSystemService error is occured.
Any advice ?

Full code is below,

public boolean isConnected(){

ConnectivityManager cm =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =cm.getActiveNetworkInfo();
if(networkInfo!=null && networkInfo.isConnectedOrConnecting()){
return true;
}
else{
return false;
}

}


Thanks in advance!

Answer

getSystemService is a method of Context.

Seeing as this can not be resolved, I can assume that you are not calling it from the context of an Activity, which extends Context itself.

Whichever object you are currently in, needs to be passed the context object from the calling activity.

This object can be retrieved using getApplicationContext().