Arsad Rahman Arsad Rahman - 1 year ago 103
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 .

Answer Source

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"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download