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

Note: only a member of this blog may post a comment.

Covid-19 impact on mobile applications - a quick case study

Amidst everything that's been going on over the last few months, checking on how my apps have been doing has been low down my priorities...