if you want to check internet connection in android there is a lot of ways to do that for example:
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
getAllNetworkInfo(); was deprecated in api level 23 so i need a solution to check internet connection both api level 23 and prior,i found another way to do that
private boolean isConnectedToInternet()
{
ConnectivityManager cm = (ConnectivityManager) SplashActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
Toast.makeText(SplashActivity.this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
return true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
Toast.makeText(SplashActivity.this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
return true;
}
}
return false;
}
my question is about getActiveNetworkInfo() and isConnected() the documentation provided by google for this method is here
Returns details about the currently active default data network. When connected, this network is the default route for outgoing connections. You should always check isConnected() before initiating network traffic. This may return null when there is no default network.
why we need to call isConnected() on getActiveNetworkInfo() for checking internet connection while we can check returned value from getActiveNetworkInfo() with null if not null we have internet connection else if returned null calling isConnected() on getActiveNetworkInfo() throws null pointer exception at runtime?