Java Code Examples for android.net.NetworkCapabilities#hasCapability()

The following examples show how to use android.net.NetworkCapabilities#hasCapability() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Requirements.java    From TelePlus-Android with GNU General Public License v2.0 7 votes vote down vote up
private static boolean checkInternetConnectivity(ConnectivityManager connectivityManager) {
  if (Util.SDK_INT < 23) {
    // TODO Check internet connectivity using http://clients3.google.com/generate_204 on API
    // levels prior to 23.
    return true;
  }
  Network activeNetwork = connectivityManager.getActiveNetwork();
  if (activeNetwork == null) {
    logd("No active network.");
    return false;
  }
  NetworkCapabilities networkCapabilities =
      connectivityManager.getNetworkCapabilities(activeNetwork);
  boolean validated =
      networkCapabilities == null
          || !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
  logd("Network capability validated: " + validated);
  return !validated;
}
 
Example 2
Source File: AndroidNetworkLibrary.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns true if the system's captive portal probe was blocked for the current default data
 * network. The method will return false if the captive portal probe was not blocked, the login
 * process to the captive portal has been successfully completed, or if the captive portal
 * status can't be determined. Requires ACCESS_NETWORK_STATE permission. Only available on
 * Android Marshmallow and later versions. Returns false on earlier versions.
 */
@TargetApi(Build.VERSION_CODES.M)
@CalledByNative
private static boolean getIsCaptivePortal() {
    // NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL is only available on Marshmallow and
    // later versions.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;
    ConnectivityManager connectivityManager =
            (ConnectivityManager) ContextUtils.getApplicationContext().getSystemService(
                    Context.CONNECTIVITY_SERVICE);
    if (connectivityManager == null) return false;

    Network network = ApiHelperForM.getActiveNetwork(connectivityManager);
    if (network == null) return false;

    NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
    return capabilities != null
            && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL);
}
 
Example 3
Source File: Requirements.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isInternetConnectivityValidated(ConnectivityManager connectivityManager) {
  if (Util.SDK_INT < 23) {
    // TODO Check internet connectivity using http://clients3.google.com/generate_204 on API
    // levels prior to 23.
    return true;
  }
  Network activeNetwork = connectivityManager.getActiveNetwork();
  if (activeNetwork == null) {
    return false;
  }
  NetworkCapabilities networkCapabilities =
      connectivityManager.getNetworkCapabilities(activeNetwork);
  boolean validated =
      networkCapabilities == null
          || !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
  return !validated;
}
 
Example 4
Source File: Requirements.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isInternetConnectivityValidated(ConnectivityManager connectivityManager) {
  if (Util.SDK_INT < 23) {
    // TODO Check internet connectivity using http://clients3.google.com/generate_204 on API
    // levels prior to 23.
    return true;
  }
  Network activeNetwork = connectivityManager.getActiveNetwork();
  if (activeNetwork == null) {
    return false;
  }
  NetworkCapabilities networkCapabilities =
      connectivityManager.getNetworkCapabilities(activeNetwork);
  boolean validated =
      networkCapabilities == null
          || !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
  return !validated;
}
 
Example 5
Source File: AndroidNetworkLibrary.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the system's captive portal probe was blocked for the current default data
 * network. The method will return false if the captive portal probe was not blocked, the login
 * process to the captive portal has been successfully completed, or if the captive portal
 * status can't be determined. Requires ACCESS_NETWORK_STATE permission. Only available on
 * Android Marshmallow and later versions. Returns false on earlier versions.
 */
@TargetApi(Build.VERSION_CODES.M)
@CalledByNative
private static boolean getIsCaptivePortal() {
    // NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL is only available on Marshmallow and
    // later versions.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;
    ConnectivityManager connectivityManager =
            (ConnectivityManager) ContextUtils.getApplicationContext().getSystemService(
                    Context.CONNECTIVITY_SERVICE);
    if (connectivityManager == null) return false;

    Network network = connectivityManager.getActiveNetwork();
    if (network == null) return false;

    NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
    return capabilities != null
            && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL);
}
 
Example 6
Source File: Requirements.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
private static boolean checkInternetConnectivity(ConnectivityManager connectivityManager) {
  if (Util.SDK_INT < 23) {
    // TODO Check internet connectivity using http://clients3.google.com/generate_204 on API
    // levels prior to 23.
    return true;
  }
  Network activeNetwork = connectivityManager.getActiveNetwork();
  if (activeNetwork == null) {
    logd("No active network.");
    return false;
  }
  NetworkCapabilities networkCapabilities =
      connectivityManager.getNetworkCapabilities(activeNetwork);
  boolean validated =
      networkCapabilities == null
          || !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
  logd("Network capability validated: " + validated);
  return !validated;
}
 
Example 7
Source File: Requirements.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
private static boolean isInternetConnectivityValidated(ConnectivityManager connectivityManager) {
  if (Util.SDK_INT < 23) {
    // TODO Check internet connectivity using http://clients3.google.com/generate_204 on API
    // levels prior to 23.
    return true;
  }
  Network activeNetwork = connectivityManager.getActiveNetwork();
  if (activeNetwork == null) {
    return false;
  }
  NetworkCapabilities networkCapabilities =
      connectivityManager.getNetworkCapabilities(activeNetwork);
  boolean validated =
      networkCapabilities == null
          || !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
  return !validated;
}
 
Example 8
Source File: MultipathPolicyTracker.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private NetworkIdentity getTemplateMatchingNetworkIdentity(NetworkCapabilities nc) {
    return new NetworkIdentity(
            ConnectivityManager.TYPE_MOBILE,
            0 /* subType, unused for template matching */,
            subscriberId,
            null /* networkId, unused for matching mobile networks */,
            !nc.hasCapability(NET_CAPABILITY_NOT_ROAMING),
            !nc.hasCapability(NET_CAPABILITY_NOT_METERED),
            false /* defaultNetwork, templates should have DEFAULT_NETWORK_ALL */);
}
 
Example 9
Source File: NetworkCallbackImpl.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
    LogUtils.e("onCapabilitiesChanged: "+ networkCapabilities);
    if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
        if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
            mListener.onWifiConnected();
        } else {
            mListener.onMobileConnected();
        }
    }
}
 
Example 10
Source File: NetworkChangeNotifierAutoDetect.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns all connected networks that are useful and accessible to Chrome.
 * Only callable on Lollipop and newer releases.
 * @param ignoreNetwork ignore this network as if it is not connected.
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Network[] getAllNetworksFiltered(
        ConnectivityManagerDelegate connectivityManagerDelegate, Network ignoreNetwork) {
    Network[] networks = connectivityManagerDelegate.getAllNetworksUnfiltered();
    // Whittle down |networks| into just the list of networks useful to us.
    int filteredIndex = 0;
    for (Network network : networks) {
        if (network.equals(ignoreNetwork)) {
            continue;
        }
        final NetworkCapabilities capabilities =
                connectivityManagerDelegate.getNetworkCapabilities(network);
        if (capabilities == null || !capabilities.hasCapability(NET_CAPABILITY_INTERNET)) {
            continue;
        }
        if (capabilities.hasTransport(TRANSPORT_VPN)) {
            // If we can access the VPN then...
            if (connectivityManagerDelegate.vpnAccessible(network)) {
                // ...we cannot access any other network, so return just the VPN.
                return new Network[] {network};
            } else {
                // ...otherwise ignore it as we cannot use it.
                continue;
            }
        }
        networks[filteredIndex++] = network;
    }
    return Arrays.copyOf(networks, filteredIndex);
}
 
Example 11
Source File: ConnectivityHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static boolean isNetworkReachable(
	@NonNull final NetworkCapabilities capabilities,
	@NonNull final NetworkInfo info) {

	if (DEBUG) Log.v(TAG, "isNetworkReachable:capabilities=" + capabilities);
	if (DEBUG) Log.v(TAG, "isNetworkReachable:info=" + info);
	final NetworkInfo.DetailedState state = info.getDetailedState();
	final boolean isConnectedOrConnecting
		= (state == NetworkInfo.DetailedState.CONNECTED)
			|| (state == NetworkInfo.DetailedState.CONNECTING);
	final boolean hasCapability;
	if (BuildCheck.isAPI28()) {
		hasCapability = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)	// API>=21
			&& capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)			// API>=23
			&& (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)	// API>=28
				|| capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOREGROUND));	// API>=28
	} else if (BuildCheck.isAPI23()) {
		hasCapability = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)	// API>=21
			&& capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);		// API>=23
	} else {
		hasCapability = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);// API>=21
	}
	if (DEBUG) Log.v(TAG, "isNetworkReachable:isConnectedOrConnecting="
		+ isConnectedOrConnecting + ",hasCapability=" + hasCapability
		+ ",NOT_SUSPENDED=" + capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)
		+ ",FOREGROUND=" + capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOREGROUND));
	return isConnectedOrConnecting && hasCapability;
}
 
Example 12
Source File: DeviceInfoHelper.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
public static String extractCapNames(NetworkCapabilities caps) {
    List<String> result = new ArrayList<>();
    for (Map.Entry<Integer, String> entry : CAPS.entrySet()) {
        if (caps.hasCapability(entry.getKey())) {
            result.add(entry.getValue());
        }
    }
    return TextUtils.join(",", result);
}
 
Example 13
Source File: Device.java    From android-job with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static boolean isRoaming(ConnectivityManager connectivityManager, NetworkInfo networkInfo) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
        return networkInfo.isRoaming();
    }

    try {
        NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
        return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
    } catch (Exception e) {
        return networkInfo.isRoaming();
    }
}
 
Example 14
Source File: ConnectivityController.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private static boolean isCongestionDelayed(JobStatus jobStatus, Network network,
        NetworkCapabilities capabilities, Constants constants) {
    // If network is congested, and job is less than 50% through the
    // developer-requested window, then we're okay delaying the job.
    if (!capabilities.hasCapability(NET_CAPABILITY_NOT_CONGESTED)) {
        return jobStatus.getFractionRunTime() < constants.CONN_CONGESTION_DELAY_FRAC;
    } else {
        return false;
    }
}
 
Example 15
Source File: NetworkChangeNotifierAutoDetect.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all connected networks that are useful and accessible to Chrome.
 * Only callable on Lollipop and newer releases.
 * @param ignoreNetwork ignore this network as if it is not connected.
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Network[] getAllNetworksFiltered(
        ConnectivityManagerDelegate connectivityManagerDelegate, Network ignoreNetwork) {
    Network[] networks = connectivityManagerDelegate.getAllNetworksUnfiltered();
    // Whittle down |networks| into just the list of networks useful to us.
    int filteredIndex = 0;
    for (Network network : networks) {
        if (network.equals(ignoreNetwork)) {
            continue;
        }
        final NetworkCapabilities capabilities =
                connectivityManagerDelegate.getNetworkCapabilities(network);
        if (capabilities == null || !capabilities.hasCapability(NET_CAPABILITY_INTERNET)) {
            continue;
        }
        if (capabilities.hasTransport(TRANSPORT_VPN)) {
            // If we can access the VPN then...
            if (connectivityManagerDelegate.vpnAccessible(network)) {
                // ...we cannot access any other network, so return just the VPN.
                return new Network[] {network};
            } else {
                // ...otherwise ignore it as we cannot use it.
                continue;
            }
        }
        networks[filteredIndex++] = network;
    }
    return Arrays.copyOf(networks, filteredIndex);
}
 
Example 16
Source File: NetworkMonitorAutoDetect.java    From webrtc_android with MIT License 5 votes vote down vote up
/**
 * Returns true if {@code network} can provide Internet access. Can be used to
 * ignore specialized networks (e.g. IMS, FOTA).
 */
@SuppressLint("NewApi")
boolean hasInternetCapability(Network network) {
  if (connectivityManager == null) {
    return false;
  }
  final NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
  return capabilities != null
      && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
}
 
Example 17
Source File: UpstreamNetworkMonitor.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private static boolean isCellular(NetworkCapabilities nc) {
    return (nc != null) && nc.hasTransport(TRANSPORT_CELLULAR) &&
           nc.hasCapability(NET_CAPABILITY_NOT_VPN);
}
 
Example 18
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
public static void applyUnderlyingCapabilities(
        ConnectivityManager cm,
        Network[] underlyingNetworks,
        NetworkCapabilities caps) {
    int[] transportTypes = new int[] { NetworkCapabilities.TRANSPORT_VPN };
    int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
    int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
    boolean metered = false;
    boolean roaming = false;
    boolean congested = false;

    boolean hadUnderlyingNetworks = false;
    if (null != underlyingNetworks) {
        for (Network underlying : underlyingNetworks) {
            // TODO(b/124469351): Get capabilities directly from ConnectivityService instead.
            final NetworkCapabilities underlyingCaps = cm.getNetworkCapabilities(underlying);
            if (underlyingCaps == null) continue;
            hadUnderlyingNetworks = true;
            for (int underlyingType : underlyingCaps.getTransportTypes()) {
                transportTypes = ArrayUtils.appendInt(transportTypes, underlyingType);
            }

            // When we have multiple networks, we have to assume the
            // worst-case link speed and restrictions.
            downKbps = NetworkCapabilities.minBandwidth(downKbps,
                    underlyingCaps.getLinkDownstreamBandwidthKbps());
            upKbps = NetworkCapabilities.minBandwidth(upKbps,
                    underlyingCaps.getLinkUpstreamBandwidthKbps());
            metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
            roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
            congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
        }
    }
    if (!hadUnderlyingNetworks) {
        // No idea what the underlying networks are; assume sane defaults
        metered = true;
        roaming = false;
        congested = false;
    }

    caps.setTransportTypes(transportTypes);
    caps.setLinkDownstreamBandwidthKbps(downKbps);
    caps.setLinkUpstreamBandwidthKbps(upKbps);
    caps.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
    caps.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
    caps.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
}