Monday, 12 January 2015

Android - Check for internet connectivity.

It's common to check for connectivity to the Internet within your Android app before you try and perform an operation. For example, if you were about to call an external REST call, you may want to check internet connectivity before performing the operation.

To perform the check I use the following utility method:

private boolean isNetworkAvailable() {
           ConnectivityManager connectivityManager
                 = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
           NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
           return activeNetworkInfo != null;

}

Remember you need the following in your AndroidManifest.xml in order for your app to connect to the Internet:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

No comments:

Post a Comment

Android Studio - How to change app icon (ic_launcher)

Changing your applications icon (ic_launcher) is a common occurrence when developing your android application. Here's quick steps on how...