Code example for ConnectivityManager: Querying Network Reachability

Methods: getActiveNetworkInfogetNetworkInfo

0
	 
	public static ConnectivityState getConnectivity(Context ctx) {
		ConnectivityState currentNetworkType;
		final ConnectivityManager conMgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
 
		if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) {
			NetworkInfo networkInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if (networkInfo != null && networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
				currentNetworkType = ConnectivityState.WIFI;
			} else { 
				networkInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
				if (networkInfo != null && networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
					currentNetworkType = ConnectivityState.CARRIER;
				} else { 
					// how can we be there ? no wifi and no mobile data but connected ? 
					currentNetworkType = ConnectivityState.UNKNOWN;
				} 
			} 
		} else { 
			currentNetworkType = ConnectivityState.NONE;
		}