How to check if internet connection is enabled in Android ?
Today, a simple article exposing a snippet code lets you to know if user’s internet connection is enabled in Android. It can be very important to know if user is connected before to send internet requests that are useless.
First, you must add following permissions to your Android Manifest :
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I presume that you want to make an internet request if you wanna try if internet connection is enabled. Thus, I add also INTERNET permission to the Manifest.
Helper method is like that :
public static boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); }
To get active network and check if it’s connected or is connecting, you must get Connectivity Manager that is a system service. Then, you have just to call isConnectedOrConnecting method from instance you got.
Leave a Reply
You must be logged in to post a comment.