Arsad Rahman Arsad Rahman - 7 months ago 70
Android Question

Best way to detect internet connection in android

When I upload my data to server via web service I have to check internet connection before upload the data this may costing me time (im using asyntask to check intertnet connection with progress dialog) on the operation even the user may feel some much loading can anyone tell me which is the best way to detect internet connection .


Here is a method you can use to validate whether a data connection is available or not:

public static boolean isDataConnectionAvailable(Context context) {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();

If this returns true then there is a data connection available.

Also make sure you add this to your manifest:

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