I always get a null pointer exception, even when I'm connected to the wifi on this piece of code:
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
Log.d("Problem", connectivityManager.getActiveNetworkInfo().toString());
My permissions are:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.SEND_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_UPDATES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CONNECTIVITY_CHANGE" />
What am I missing :/? I just need to know if when he's connected to a wifi spot and when this changes. But the connectivity manager always returns null on the ActiveNetworkInfo
use this to know that WIFI is connected or not .
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class Network {
private Context context;
private ConnectivityManager connManager;
public Network(Context ctx) {
this.context = ctx;
}
public boolean getConnectivityStatus() {
connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connManager.getActiveNetworkInfo();
if (info != null)
return info.isConnected(); // WIFI connected
else
return false; // no info object implies no connectivity
}
}
connectivityManager.getActiveNetworkInfo()
update:
return the current device's active network connect, if your device has only wifi and wifi is not opened, it always null.
suggestion register the action receive: ConnectivityManager.CONNECTIVITY_ACTION
when receive the action you can check the connect using follow code:
NetworkInfo network = mConnectivityManager.getActiveNetworkInfo();
if (network != null) {
boolean isConnectedOrConnecting = network.isConnectedOrConnecting();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With