is Online via Wifi or Mobile - Android Wifi

Android examples for Wifi:Wifi Connection

Description

is Online via Wifi or Mobile

Demo Code

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;

public class Main {
  public static boolean isOnline(Context context) {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (isM()) {/*from ww w .java  2  s .c om*/
      Network networks = cm.getActiveNetwork();
      NetworkInfo netInfo = cm.getNetworkInfo(networks);
      haveConnectedWifi = netInfo.getType() == ConnectivityManager.TYPE_WIFI
          && netInfo.getState().equals(NetworkInfo.State.CONNECTED);
      haveConnectedMobile = netInfo.getType() == ConnectivityManager.TYPE_MOBILE
          && netInfo.getState().equals(NetworkInfo.State.CONNECTED);
      return haveConnectedWifi || haveConnectedMobile;
    } else {
      NetworkInfo[] netInfo = cm.getAllNetworkInfo();
      for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI")) {
          if (ni.isConnected())
            haveConnectedWifi = true;
        }
        if (ni.getTypeName().equalsIgnoreCase("MOBILE")) {
          if (ni.isConnected())
            haveConnectedMobile = true;
        }
      }
      return haveConnectedWifi || haveConnectedMobile;
    }
  }

  public static boolean isM() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
  }
}

Related Tutorials