1

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 .

skydroid
  • 733
  • 6
  • 16
Arsad Rahman
  • 125
  • 2
  • 13
  • possible duplicate of http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-times-out – Theyna Aug 31 '16 at 22:57

3 Answers3

3

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"/>
CodyEngel
  • 1,501
  • 14
  • 22
0
public static NETWORK_AVAILABILITY_STATUS getAvailableNetworkType(Context context)
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting())
        {
            int type = activeNetworkInfo.getType();
            if (type == ConnectivityManager.TYPE_MOBILE)
            {
                return NETWORK_AVAILABILITY_STATUS.DATA_PLAN;
            }
            else if (type == ConnectivityManager.TYPE_WIFI)
            {
                return NETWORK_AVAILABILITY_STATUS.WIFI;
            }
        }

        return NETWORK_AVAILABILITY_STATUS.NO_NETWORK;
    }

Note : You need to have internet permission i.e

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

Note :This method does NOT guarantee that network is reachable, the connection might still timeout or not respond at all.

dex
  • 5,182
  • 1
  • 23
  • 41
0

I use this way in my app:

public static boolean isConnect(Activity activity) {
    boolean flag = false;

    ConnectivityManager cwjManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cwjManager.getActiveNetworkInfo() != null)
        flag = cwjManager.getActiveNetworkInfo().isAvailable();

    return flag;
}

And of course, you also need android permission:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Coding minion
  • 527
  • 2
  • 4
  • 12