android.net.NetworkCapabilities Java Examples

The following examples show how to use android.net.NetworkCapabilities. 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: LocalIPUtil.java    From DanDanPlayForAndroid with MIT License 7 votes vote down vote up
private String findLocalIp1(){
    ConnectivityManager connMgr = (ConnectivityManager) IApplication.get_context().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && connMgr != null) {
        LinkProperties linkProperties;
        String ipAddress = null;
        linkProperties = getLinkProperties(connMgr, NetworkCapabilities.TRANSPORT_VPN);
        if (linkProperties == null)
            linkProperties = getLinkProperties(connMgr, NetworkCapabilities.TRANSPORT_ETHERNET);
        if (linkProperties == null)
            linkProperties = getLinkProperties(connMgr, NetworkCapabilities.TRANSPORT_WIFI);
        if (linkProperties != null)
            ipAddress =  getIp(linkProperties);
        if (ipAddress != null)
            return ipAddress;
    }
    return null;
}
 
Example #2
Source File: FragmentOptionsConnection.java    From FairEmail with GNU General Public License v3.0 7 votes vote down vote up
@Override
public void onResume() {
    super.onResume();

    ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null)
        return;

    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    cm.registerNetworkCallback(builder.build(), networkCallback);
}
 
Example #3
Source File: RequirementsWatcher.java    From TelePlus-Android with GNU General Public License v2.0 7 votes vote down vote up
@TargetApi(23)
private void registerNetworkCallbackV23() {
  ConnectivityManager connectivityManager =
      (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkRequest request =
      new NetworkRequest.Builder()
          .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
          .build();
  networkCallback = new CapabilityValidatedCallback();
  connectivityManager.registerNetworkCallback(request, networkCallback);
}
 
Example #4
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Updates {@link #mNetworkCapabilities} based on current underlying networks and returns a
 * defensive copy.
 *
 * <p>Does not propagate updated capabilities to apps.
 *
 * @param defaultNetwork underlying network for VPNs following platform's default
 */
public synchronized NetworkCapabilities updateCapabilities(
        @Nullable Network defaultNetwork) {
    if (mConfig == null) {
        // VPN is not running.
        return null;
    }

    Network[] underlyingNetworks = mConfig.underlyingNetworks;
    if (underlyingNetworks == null && defaultNetwork != null) {
        // null underlying networks means to track the default.
        underlyingNetworks = new Network[] { defaultNetwork };
    }

    applyUnderlyingCapabilities(
            mContext.getSystemService(ConnectivityManager.class),
            underlyingNetworks,
            mNetworkCapabilities);

    return new NetworkCapabilities(mNetworkCapabilities);
}
 
Example #5
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 #6
Source File: WifiFacade.java    From particle-android with Apache License 2.0 6 votes vote down vote up
@Nullable
@RequiresApi(api = VERSION_CODES.LOLLIPOP)
public Network getNetworkObjectForCurrentWifiConnection() {
    // Android doesn't have any means of directly asking
    // "I want the Network obj for the Wi-Fi network with SSID <foo>".
    // Instead, you have to infer it based on the fact that you can only
    // have one connected Wi-Fi connection at a time.
    // (Update: one *regular* Wi-Fi connection, anyway.  See below.)

    return Funcy.findFirstMatch(
            Arrays.asList(connectivityManager.getAllNetworks()),
            network -> {
                NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
                if (capabilities == null) {
                    return false;
                }
                // Don't try using the P2P Wi-Fi interfaces on recent Samsung devices
                if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
                    return false;
                }
                return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
            }
    );
}
 
Example #7
Source File: CheckNet.java    From Ruisi with Apache License 2.0 6 votes vote down vote up
private void request(final CheckNetResponse checkNetResponse) {
    finishCount = 0;
    errCount = 0;


    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        Network network = connectivityManager.getActiveNetwork();
        NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
        if (capabilities == null) {
            checkNetResponse.sendFinishMessage(0, "无法连接到睿思,请打开网络连接");
        } //else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
        checkSchoolNet(context);
        checkOutNet(context);
    } else {
        final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
            checkSchoolNet(context);
            checkOutNet(context);
        } else {
            checkNetResponse.sendFinishMessage(0, "无法连接到睿思,请打开网络连接");
        }
    }
}
 
Example #8
Source File: ConnectivityController.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static boolean isSatisfied(JobStatus jobStatus, Network network,
        NetworkCapabilities capabilities, Constants constants) {
    // Zeroth, we gotta have a network to think about being satisfied
    if (network == null || capabilities == null) return false;

    // First, are we insane?
    if (isInsane(jobStatus, network, capabilities, constants)) return false;

    // Second, is the network congested?
    if (isCongestionDelayed(jobStatus, network, capabilities, constants)) return false;

    // Third, is the network a strict match?
    if (isStrictSatisfied(jobStatus, network, capabilities, constants)) return true;

    // Third, is the network a relaxed match?
    if (isRelaxedSatisfied(jobStatus, network, capabilities, constants)) return true;

    return false;
}
 
Example #9
Source File: ConnectivityController.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private static boolean isRelaxedSatisfied(JobStatus jobStatus, Network network,
        NetworkCapabilities capabilities, Constants constants) {
    // Only consider doing this for prefetching jobs
    if (!jobStatus.getJob().isPrefetch()) {
        return false;
    }

    // See if we match after relaxing any unmetered request
    final NetworkCapabilities relaxed = new NetworkCapabilities(
            jobStatus.getJob().getRequiredNetwork().networkCapabilities)
                    .removeCapability(NET_CAPABILITY_NOT_METERED);
    if (relaxed.satisfiedByNetworkCapabilities(capabilities)) {
        // TODO: treat this as "maybe" response; need to check quotas
        return jobStatus.getFractionRunTime() > constants.CONN_PREFETCH_RELAX_FRAC;
    } else {
        return false;
    }
}
 
Example #10
Source File: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void handleRequestSuplConnection(InetAddress address) {
    if (DEBUG) {
        String message = String.format(
                "requestSuplConnection, state=%s, address=%s",
                agpsDataConnStateAsString(),
                address);
        Log.d(TAG, message);
    }

    if (mAGpsDataConnectionState != AGPS_DATA_CONNECTION_CLOSED) {
        return;
    }
    mAGpsDataConnectionIpAddr = address;
    mAGpsDataConnectionState = AGPS_DATA_CONNECTION_OPENING;

    NetworkRequest.Builder requestBuilder = new NetworkRequest.Builder();
    requestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
    requestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_SUPL);
    NetworkRequest request = requestBuilder.build();
    mConnMgr.requestNetwork(
            request,
            mSuplConnectivityCallback);
}
 
Example #11
Source File: DefaultNetworkEvent.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringJoiner j = new StringJoiner(", ", "DefaultNetworkEvent(", ")");
    j.add("netId=" + netId);
    for (int t : BitUtils.unpackBits(transports)) {
        j.add(NetworkCapabilities.transportNameOf(t));
    }
    j.add("ip=" + ipSupport());
    if (initialScore > 0) {
        j.add("initial_score=" + initialScore);
    }
    if (finalScore > 0) {
        j.add("final_score=" + finalScore);
    }
    j.add(String.format("duration=%.0fs", durationMs / 1000.0));
    j.add(String.format("validation=%04.1f%%", (validatedMs * 100.0) / durationMs));
    return j.toString();
}
 
Example #12
Source File: ConnectivityHelper.java    From libcommon with Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
	@TargetApi(Build.VERSION_CODES.LOLLIPOP)
	private static boolean isWifiNetworkReachable(
		@NonNull final NetworkCapabilities capabilities,
		@NonNull final NetworkInfo info) {

		final boolean isWiFi;
		if (BuildCheck.isAPI26()) {
			isWiFi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)		// API>=21
				|| capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET);	// API>=21
//				|| capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI_AWARE);	// API>=26 これはWi-Fi端末間での近接情報の発見機能
		} else {
			isWiFi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)		// API>=21
				|| capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET);	// API>=21
		}
		return isWiFi && isNetworkReachable(capabilities, info);
	}
 
Example #13
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 #14
Source File: NetworkChangeNotifierAutoDetect.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onCapabilitiesChanged(
        Network network, NetworkCapabilities networkCapabilities) {
    if (ignoreConnectedNetwork(network, networkCapabilities)) {
        return;
    }
    // A capabilities change may indicate the ConnectionType has changed,
    // so forward the new ConnectionType along to observer.
    final long netId = networkToNetId(network);
    final int connectionType = mConnectivityManagerDelegate.getConnectionType(network);
    runOnThread(new Runnable() {
        @Override
        public void run() {
            mObserver.onNetworkConnect(netId, connectionType);
        }
    });
}
 
Example #15
Source File: NetworkChangeNotifierAutoDetect.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
public void onCapabilitiesChanged(
        Network network, NetworkCapabilities networkCapabilities) {
    if (ignoreConnectedNetwork(network, networkCapabilities)) {
        return;
    }
    // A capabilities change may indicate the ConnectionType has changed,
    // so forward the new ConnectionType along to observer.
    final long netId = networkToNetId(network);
    final int connectionType = mConnectivityManagerDelegate.getConnectionType(network);
    runOnThread(new Runnable() {
        @Override
        public void run() {
            mObserver.onNetworkConnect(netId, connectionType);
        }
    });
}
 
Example #16
Source File: NetworkAgentInfo.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info,
        LinkProperties lp, NetworkCapabilities nc, int score, Context context, Handler handler,
        NetworkMisc misc, NetworkRequest defaultRequest, ConnectivityService connService) {
    this.messenger = messenger;
    asyncChannel = ac;
    network = net;
    networkInfo = info;
    linkProperties = lp;
    networkCapabilities = nc;
    currentScore = score;
    mConnService = connService;
    mContext = context;
    mHandler = handler;
    networkMonitor = mConnService.createNetworkMonitor(context, handler, this, defaultRequest);
    networkMisc = misc;
}
 
Example #17
Source File: RequirementsWatcher.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(23)
private void registerNetworkCallbackV23() {
  ConnectivityManager connectivityManager =
      (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkRequest request =
      new NetworkRequest.Builder()
          .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
          .build();
  networkCallback = new CapabilityValidatedCallback();
  connectivityManager.registerNetworkCallback(request, networkCallback);
}
 
Example #18
Source File: MainActivity.java    From Intra with Apache License 2.0 5 votes vote down vote up
private boolean isAnotherVpnActive() {
  if (VERSION.SDK_INT >= VERSION_CODES.M) {
    ConnectivityManager connectivityManager =
        (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    Network activeNetwork = connectivityManager.getActiveNetwork();
    if (activeNetwork == null) {
      return false;
    }
    NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
    if (capabilities == null) {
      // It's not clear when this can happen, but it has occurred for at least one user.
      return false;
    }
    return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN);
  }
  // For pre-M versions, return true if there's any network whose name looks like a VPN.
  try {
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements()) {
      NetworkInterface networkInterface = networkInterfaces.nextElement();
      String name = networkInterface.getName();
      if (networkInterface.isUp() && name != null &&
          (name.startsWith("tun") || name.startsWith("pptp") || name.startsWith("l2tp"))) {
        return true;
      }
    }
  } catch (SocketException e) {
    LogWrapper.logException(e);
  }
  return false;
}
 
Example #19
Source File: DeviceInfoHelper.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
public static String extractTransportTypes(NetworkCapabilities caps) {
    List<String> result = new ArrayList<>();
    for (Map.Entry<Integer, String> entry : TRANSPORTS.entrySet()) {
        if (caps.hasTransport(entry.getKey())) {
            result.add(entry.getValue());
        }
    }
    return TextUtils.join(",", result);
}
 
Example #20
Source File: ThetaM15.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
private static SocketFactory getWifiSocketFactory(final Context context) {
    SocketFactory socketFactory = SocketFactory.getDefault();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !isGalaxyDevice()) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network[] allNetwork = cm.getAllNetworks();
        for (Network network : allNetwork) {
            NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(network);
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                socketFactory = network.getSocketFactory();
            }
        }
    }
    return socketFactory;
}
 
Example #21
Source File: RequirementsWatcher.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(23)
private void registerNetworkCallbackV23() {
  ConnectivityManager connectivityManager =
      Assertions.checkNotNull(
          (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
  NetworkRequest request =
      new NetworkRequest.Builder()
          .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
          .build();
  networkCallback = new CapabilityValidatedCallback();
  connectivityManager.registerNetworkCallback(request, networkCallback);
}
 
Example #22
Source File: LollipopDeviceStateListener.java    From Cake-VPN with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
    super.onCapabilitiesChanged(network, networkCapabilities);
    if (!networkCapabilities.toString().equals(mLastNetworkCapabilities)) {
        mLastNetworkCapabilities = networkCapabilities.toString();
        VpnStatus.logDebug(String.format("Network capabilities of %s: %s", network, networkCapabilities));
    }
}
 
Example #23
Source File: LollipopDeviceStateListener.java    From android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
    super.onCapabilitiesChanged(network, networkCapabilities);
    if (!networkCapabilities.toString().equals(mLastNetworkCapabilities)) {
        mLastNetworkCapabilities = networkCapabilities.toString();
        VpnStatus.logDebug(String.format("Network capabilities of %s: %s", network, networkCapabilities));
    }
}
 
Example #24
Source File: WiFiSocketFactoryTest.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testPackageManagerNull() {
    setupMockNetworks(new MockNetworkConfig[] {
            new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_WIFI, FactoryRet.RETURNS_CORRECT_FACTORY),
    });

    // simulate the case where ConnectivityManager isn't available
    when(mMockContext.getPackageManager()).thenReturn(null);

    Socket ret = WiFiSocketFactory.createSocket(mMockContext);

    assertNotNull("createSocket() should always return a Socket instance", ret);
    assertNotSame("Returned Socket shouldn't be created through SocketFactory since PackageManager isn't available",
            mWiFiBoundSocket, ret);
}
 
Example #25
Source File: DnsEvent.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    StringBuilder builder =
            new StringBuilder("DnsEvent(").append("netId=").append(netId).append(", ");
    for (int t : BitUtils.unpackBits(transports)) {
        builder.append(NetworkCapabilities.transportNameOf(t)).append(", ");
    }
    builder.append(String.format("%d events, ", eventCount));
    builder.append(String.format("%d success)", successCount));
    return builder.toString();
}
 
Example #26
Source File: TelephonyRegistry.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void broadcastDataConnectionStateChanged(int state,
        boolean isDataAllowed,
        String reason, String apn, String apnType, LinkProperties linkProperties,
        NetworkCapabilities networkCapabilities, boolean roaming, int subId) {
    // Note: not reporting to the battery stats service here, because the
    // status bar takes care of that after taking into account all of the
    // required info.
    Intent intent = new Intent(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
    intent.putExtra(PhoneConstants.STATE_KEY,
            PhoneConstantConversions.convertDataState(state).toString());
    if (!isDataAllowed) {
        intent.putExtra(PhoneConstants.NETWORK_UNAVAILABLE_KEY, true);
    }
    if (reason != null) {
        intent.putExtra(PhoneConstants.STATE_CHANGE_REASON_KEY, reason);
    }
    if (linkProperties != null) {
        intent.putExtra(PhoneConstants.DATA_LINK_PROPERTIES_KEY, linkProperties);
        String iface = linkProperties.getInterfaceName();
        if (iface != null) {
            intent.putExtra(PhoneConstants.DATA_IFACE_NAME_KEY, iface);
        }
    }
    if (networkCapabilities != null) {
        intent.putExtra(PhoneConstants.DATA_NETWORK_CAPABILITIES_KEY, networkCapabilities);
    }
    if (roaming) intent.putExtra(PhoneConstants.DATA_NETWORK_ROAMING_KEY, true);

    intent.putExtra(PhoneConstants.DATA_APN_KEY, apn);
    intent.putExtra(PhoneConstants.DATA_APN_TYPE_KEY, apnType);
    intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
    mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
}
 
Example #27
Source File: WiFiSocketFactoryTest.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testSocketFactoryNull() {
    setupMockNetworks(new MockNetworkConfig[] {
            new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_CELLULAR, FactoryRet.RETURNS_ANOTHER_FACTORY),
            new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_WIFI, FactoryRet.RETURNS_NULL),
    });

    Socket ret = WiFiSocketFactory.createSocket(mMockContext);

    assertNotNull("createSocket() should always return a Socket instance", ret);
    assertNotSame("Returned Socket shouldn't be created through SocketFactory since SocketFactory isn't available",
            mWiFiBoundSocket, ret);
}
 
Example #28
Source File: NetworkAgentInfo.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public NetworkState getNetworkState() {
    synchronized (this) {
        // Network objects are outwardly immutable so there is no point in duplicating.
        // Duplicating also precludes sharing socket factories and connection pools.
        final String subscriberId = (networkMisc != null) ? networkMisc.subscriberId : null;
        return new NetworkState(new NetworkInfo(networkInfo),
                new LinkProperties(linkProperties),
                new NetworkCapabilities(networkCapabilities), network, subscriberId, null);
    }
}
 
Example #29
Source File: WifiUtil.java    From android-wificonnect with MIT License 5 votes vote down vote up
@TargetApi(LOLLIPOP)
void bindToNetwork(final String networkSSID, final NetworkStateChangeListener listener) {
    if (SDK_INT < LOLLIPOP) {
        logger.i("SDK version is below Lollipop. No need to bind process to network. Skipping...");
        return;
    }
    logger.i("Currently active network is not " + networkSSID + ", would bind the app to use this when available");

    NetworkRequest request = new NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build();
    networkCallback = networkCallback(networkSSID, listener);
    manager.registerNetworkCallback(request, networkCallback);
}
 
Example #30
Source File: NetworkChangeNotifierAutoDetect.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void initializeVpnInPlace() {
    final Network[] networks = getAllNetworksFiltered(mConnectivityManagerDelegate, null);
    mVpnInPlace = null;
    // If the filtered list of networks contains just a VPN, then that VPN is in place.
    if (networks.length == 1) {
        final NetworkCapabilities capabilities =
                mConnectivityManagerDelegate.getNetworkCapabilities(networks[0]);
        if (capabilities != null && capabilities.hasTransport(TRANSPORT_VPN)) {
            mVpnInPlace = networks[0];
        }
    }
}