Reputation: 80
When I use the below code to show my connection state, "if" condition always returns "true", unless I put "netinfo" equal "null".
Where is the problem?
public boolean isConnectedToInternet()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if ( netInfo.isConnectedOrConnecting())
{
Toast.makeText(this, "On",Toast.LENGTH_LONG).show();
Log.i("NewsList", "Internet Connection found.");
return true;
}
Toast.makeText(this, "Off",Toast.LENGTH_LONG).show();
return false;
}
Upvotes: 0
Views: 254
Reputation: 3249
Try following:
DetectConnection.class:
public class DetectConnection {
/*
* Checking internet connection
*/
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
}
Check internet from another activity:
if (DetectConnection.checkInternetConnection(this)) {
//do something
}
Upvotes: 1