Tuesday, October 19, 2010

Check internet connection in Android

Sometimes, apps need internet access to get content from other remote resources. However, you also need to take care the case when there is no internet access. You can't assume users always has internet access. To check whether a mobile has internet or not, you can use the following code:

public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean connected = (conMgr.getActiveNetworkInfo() != null &&
conMgr.getActiveNetworkInfo().isAvailable() &&
conMgr.getActiveNetworkInfo().isConnected())
return connected;
}


Also, you need to add permission to the app so that it can access network status.



Note: In emulator, you can press F8 to toggle the internet access.

No comments:

Post a Comment