private static List<NetworkInfo> getConnectedNetworks(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) { return null; } final List<NetworkInfo> list = new ArrayList<NetworkInfo>(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { NetworkInfo[] networkInfoList = cm.getAllNetworkInfo(); if (networkInfoList != null) { final int length = networkInfoList.length; for (int i = 0; i < length; i++) { if (networkInfoList[i].getState() == NetworkInfo.State.CONNECTED) { list.add(networkInfoList[i]); } } } } else { final Network[] networks = cm.getAllNetworks(); if (networks != null && networks.length > 0) { NetworkInfo info; for (Network network : networks) { info = cm.getNetworkInfo(network); if (info != null && info.getState() == NetworkInfo.State.CONNECTED) { list.add(info); } } } } return list; }
@TargetApi(23) private static List<InetAddress> getDnsServers(Context context) { List<InetAddress> servers = new ArrayList<>(); ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //Network[] networks = connectivityManager == null ? null : connectivityManager.getAllNetworks(); Network[] networks = connectivityManager == null ? null : new Network[]{connectivityManager.getActiveNetwork()}; if (networks == null) { return servers; } for(int i = 0; i < networks.length; ++i) { LinkProperties linkProperties = connectivityManager.getLinkProperties(networks[i]); if (linkProperties != null) { servers.addAll(linkProperties.getDnsServers()); } } for(InetAddress server : servers) { Log.d("dns","DNS server: " + Strings.nullToEmpty(server.getHostName()) + " (" + server.getHostAddress() + ")"); } return servers; }
/** * @param context the current application context * @return whether the device was connected to the internet */ public static boolean hasInternetConnection(Context context) { /* Taken from Johan's answer at: https://stackoverflow.com/a/35009615 */ ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); Network network; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { network = connectivityManager.getActiveNetwork(); } else return true; NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network); return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED); }
@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 = getCurrentConnectionType(mConnectivityManagerDelegate.getNetworkState(network)); ThreadUtils.postOnUiThread(new Runnable() { @Override public void run() { mObserver.onNetworkConnect(netId, connectionType); } }); }
@UiThreadTest @MediumTest @Feature({"Android-AppBase"}) public void testConnectivityManagerDelegateDoesNotCrash() { ConnectivityManagerDelegate delegate = new ConnectivityManagerDelegate(getInstrumentation().getTargetContext()); delegate.getNetworkState(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // getNetworkState(Network) doesn't crash upon invalid Network argument. Network invalidNetwork = netIdToNetwork(NetId.INVALID); NetworkState invalidNetworkState = delegate.getNetworkState(invalidNetwork); assertFalse(invalidNetworkState.isConnected()); assertEquals(-1, invalidNetworkState.getNetworkType()); assertEquals(-1, invalidNetworkState.getNetworkSubType()); Network[] networks = delegate.getAllNetworksUnfiltered(); if (networks.length >= 1) { delegate.getNetworkState(networks[0]); } delegate.getDefaultNetId(); NetworkCallback networkCallback = new NetworkCallback(); NetworkRequest networkRequest = new NetworkRequest.Builder().build(); delegate.registerNetworkCallback(networkRequest, networkCallback); delegate.unregisterNetworkCallback(networkCallback); } }
private Network findVpnNetwork() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); Network[] networks = cm.getAllNetworks(); for (Network network : networks) { LinkProperties linkProperties = cm.getLinkProperties(network); List<LinkAddress> addresses = linkProperties.getLinkAddresses(); for (LinkAddress addr : addresses) { if (addr.getAddress().equals(VPN_ADDRESS)) { return network; } } } return null; }
/** * Tests that ConnectivityManagerDelegate doesn't crash. This test cannot rely on having any * active network connections so it cannot usefully check results, but it can at least check * that the functions don't crash. */ @Test @UiThreadTest @SmallTest public void testConnectivityManagerDelegateDoesNotCrash() { ConnectivityManagerDelegate delegate = new ConnectivityManagerDelegate(InstrumentationRegistry.getTargetContext()); delegate.getNetworkState(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Network[] networks = delegate.getAllNetworks(); if (networks.length >= 1) { delegate.getNetworkState(networks[0]); delegate.hasInternetCapability(networks[0]); } delegate.getDefaultNetId(); } }
@RequiresApi(LOLLIPOP) @Nullable static NetworkInfo getNetworkInfo(@NonNull Network network, @NonNull ConnectivityManager connectivityManager) { NetworkInfo networkInfo = null; try { networkInfo = connectivityManager.getNetworkInfo(network); } catch (Exception exc) { logger.log(WARNING, "Could not retrieve network info from provided network: " + exc.getMessage()); } return networkInfo; }
public static void registerLollipopNetworkReceiver(Context context) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); cm.registerNetworkCallback( new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .build(), new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { boolean connected = false; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { connected = cm.bindProcessToNetwork(network); } else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ //noinspection deprecation connected = ConnectivityManager.setProcessDefaultNetwork(network); } if(connected) { Customerly.get().__SOCKET__check(); } } }); } }
@Contract("null -> false") @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.LOLLIPOP) static boolean checkConnection(@Nullable Context c) { if(c == null) return false; ConnectivityManager manager = (ConnectivityManager) c .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Network[] nets = manager.getAllNetworks(); for (Network net : nets) { info = manager.getNetworkInfo(net); if (info != null && info.getState() == NetworkInfo.State.CONNECTED) return true; } return false; } else { info = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (info != null && info.getState() == NetworkInfo.State.CONNECTED) return true; info = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (info != null && info.getState() == NetworkInfo.State.CONNECTED) return true; info = manager.getNetworkInfo(ConnectivityManager.TYPE_WIMAX); return info != null && info.getState() == NetworkInfo.State.CONNECTED; } }
@TargetApi(LOLLIPOP) NetworkCallback networkCallback(final String networkSSID, final NetworkStateChangeListener listener) { return new NetworkCallback() { @Override public void onAvailable(Network network) { NetworkInfo networkInfo = manager.getNetworkInfo(network); logger.i("Network is Available. Network Info: " + networkInfo); if (WifiHelper.areEqual(networkInfo.getExtraInfo(), networkSSID)) { manager.unregisterNetworkCallback(this); networkCallback = null; bindToRequiredNetwork(network); logger.i(format("Bound application to use %s network", networkSSID)); listener.onNetworkBound(); } } }; }
@SuppressWarnings("deprecation") private static void logNetworks(ConnectivityManager connectivityManager) { NetworkInfo[] networkInfos; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { networkInfos = connectivityManager.getAllNetworkInfo(); } else { Network[] networks = connectivityManager.getAllNetworks(); networkInfos = new NetworkInfo[networks.length]; for (int i = 0; i < networks.length; i++) { networkInfos[i] = connectivityManager.getNetworkInfo(networks[i]); } } for (NetworkInfo networkInfo : networkInfos) log(networkInfo); }
private static Set<InetAddress> getDnsServers(Context context) throws VpnNetworkException { Set<InetAddress> out = new HashSet<>(); ConnectivityManager cm = (ConnectivityManager) context.getSystemService(VpnService.CONNECTIVITY_SERVICE); // Seriously, Android? Seriously? NetworkInfo activeInfo = cm.getActiveNetworkInfo(); if (activeInfo == null) throw new VpnNetworkException("No DNS Server"); for (Network nw : cm.getAllNetworks()) { NetworkInfo ni = cm.getNetworkInfo(nw); if (ni == null || !ni.isConnected() || ni.getType() != activeInfo.getType() || ni.getSubtype() != activeInfo.getSubtype()) continue; for (InetAddress address : cm.getLinkProperties(nw).getDnsServers()) out.add(address); } return out; }
@TargetApi(21) private static List<InetAddress> getDnsServers(Context context) { List<InetAddress> servers = new ArrayList<>(); ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); Network[] networks = connectivityManager == null ? null : connectivityManager.getAllNetworks(); if (networks == null) { return getDnsServersPreLollipop(); } for(int i = 0; i < networks.length; ++i) { LinkProperties linkProperties = connectivityManager.getLinkProperties(networks[i]); if (linkProperties != null) { servers.addAll(linkProperties.getDnsServers()); } } if (servers.size() > 0) { Log.d(Config.LOGTAG,"used lollipop variant to discover dns servers in "+networks.length+" networks"); } return servers.size() > 0 ? servers : getDnsServersPreLollipop(); }
public static boolean isMobileOnline(final Context context) { boolean state = false; ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { Network[] networks = connectivityManager.getAllNetworks(); for (Network network : networks) { NetworkInfo info = connectivityManager.getNetworkInfo(network); if (info.getType() == ConnectivityManager.TYPE_MOBILE) { state = info.isConnectedOrConnecting(); } } } else { /* Mobile data connection */ NetworkInfo mobileNetwork = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mobileNetwork != null) { state = mobileNetwork.isConnectedOrConnecting(); } } return state; }
public boolean isNetworkAvailable(@NonNull Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Network[] networks = connectivityManager.getAllNetworks(); for (Network network : networks) { if (connectivityManager .getNetworkInfo(network) .getState() .equals(NetworkInfo.State.CONNECTED)) { return true; } } } else if (connectivityManager != null) { NetworkInfo[] info = connectivityManager.getAllNetworkInfo(); if (info != null) { for (NetworkInfo anInfo : info) { if (anInfo.getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; }
public static boolean forceWifiUse(Context context) { if (context == null) return false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); //TODO rewrite this in order to support multiples API //TODO (use bindProcessToNetwork, setProcessDefaultNetwork, and requestRouteToHost) Network[] networks = manager.getAllNetworks(); int i = 0; for (i = 0; i < networks.length; i++) { NetworkInfo info = manager.getNetworkInfo(networks[i]); if (info != null) if (info.isConnected()) if (info.getType() == manager.TYPE_WIFI) break; } if (i == networks.length) { return false; } else { return manager.bindProcessToNetwork(networks[i]); } } return false; }
/** * 网络是否可用 * * @param context 上下文 * @return true 可用 false 不可用 */ public static boolean isNetworkAvailable(Context context) { if (context != null) { ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); Network[] networks; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { networks = mgr.getAllNetworks(); for (Network network : networks) { NetworkInfo networkInfo = mgr.getNetworkInfo(network); if (networkInfo.getState() == NetworkInfo.State.CONNECTED) { return true; } } } else { NetworkInfo[] info = mgr.getAllNetworkInfo(); if (info != null) { for (NetworkInfo anInfo : info) { if (anInfo.getState() == NetworkInfo.State.CONNECTED) { return true; } } } } } return false; }
/** * 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); }
@TargetApi(Build.VERSION_CODES.M) @CalledByNative private static byte[][] getDnsServers() { ConnectivityManager connectivityManager = (ConnectivityManager) ContextUtils.getApplicationContext().getSystemService( Context.CONNECTIVITY_SERVICE); if (connectivityManager == null) { return new byte[0][0]; } Network network = connectivityManager.getActiveNetwork(); if (network == null) { return new byte[0][0]; } LinkProperties linkProperties = connectivityManager.getLinkProperties(network); if (linkProperties == null) { return new byte[0][0]; } List<InetAddress> dnsServersList = linkProperties.getDnsServers(); byte[][] dnsServers = new byte[dnsServersList.size()][]; for (int i = 0; i < dnsServersList.size(); i++) { dnsServers[i] = dnsServersList.get(i).getAddress(); } return dnsServers; }
/** * Returns connection type for |network|. * Only callable on Lollipop and newer releases. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) @ConnectionType int getConnectionType(Network network) { NetworkInfo networkInfo = getNetworkInfo(network); if (networkInfo != null && networkInfo.getType() == TYPE_VPN) { // When a VPN is in place the underlying network type can be queried via // getActiveNeworkInfo() thanks to // https://android.googlesource.com/platform/frameworks/base/+/d6a7980d networkInfo = mConnectivityManager.getActiveNetworkInfo(); } if (networkInfo != null && networkInfo.isConnected()) { return convertToConnectionType(networkInfo.getType(), networkInfo.getSubtype()); } return ConnectionType.CONNECTION_NONE; }
@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); } }); }
@TargetApi(Build.VERSION_CODES.M) private String getActiveInterface() { final Network network = cm.getActiveNetwork(); if (network == null) { return null; } final LinkProperties linkInfo = cm.getLinkProperties(network); if (linkInfo == null) { return null; } final List<LinkAddress> linkAddress = linkInfo.getLinkAddresses(); if (linkAddress.isEmpty()) { return null; } final InetAddress address = linkAddress.get(0).getAddress(); return address.getHostAddress(); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) private static String getNetId(Context c){ String netId = ""; ConnectivityManager manager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); try{ Network[] networks = manager.getAllNetworks(); for(Network i: networks){ netId = i.getClass().getDeclaredField("netId").get(i).toString(); } }catch (Exception e){ e.printStackTrace(); } return netId; }
@SuppressWarnings("deprecation") public static boolean isWlanConnected(Context c) { ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { for(Network n : cm.getAllNetworks()) { NetworkInfo info = cm.getNetworkInfo(n); if(info != null && info.getType() == ConnectivityManager.TYPE_WIFI && info.isConnected()) { return true; } } return false; } else { return cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected(); } }
@TargetApi(21) private static List<InetAddress> getDnsServers(Context context) { List<InetAddress> servers = new ArrayList<>(); ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); Network[] networks = connectivityManager == null ? null : connectivityManager.getAllNetworks(); if (networks == null) { return getDnsServersPreLollipop(); } for(int i = 0; i < networks.length; ++i) { LinkProperties linkProperties = connectivityManager.getLinkProperties(networks[i]); if (linkProperties != null) { if (hasDefaultRoute(linkProperties)) { servers.addAll(0, linkProperties.getDnsServers()); } else { servers.addAll(linkProperties.getDnsServers()); } } } if (servers.size() > 0) { Log.d(Config.LOGTAG, "used lollipop variant to discover dns servers in " + networks.length + " networks"); } return servers.size() > 0 ? servers : getDnsServersPreLollipop(); }
/** * Determine if device connected to network * @param context context * @return true if connected, false otherwise */ @SuppressWarnings("deprecation") public static boolean isConnected(@NonNull final Context context) { final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { final NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); final NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); return wifi != null && wifi.isConnected() || mobile != null && mobile.isConnected(); } else { boolean connected = false; for (Network network : connMgr.getAllNetworks()) { NetworkInfo info = connMgr.getNetworkInfo(network); connected |= info != null && info.isConnected(); } return connected; } }
@Override public void process(final StateMachineConnection sm) { // Workaround when there is a data connection more than the wifi one // http://stackoverflow.com/questions/33237074/request-over-wifi-on-android-m if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { ConnectivityManager connectivityManager = (ConnectivityManager) sm.mApplication.getSystemService(Context.CONNECTIVITY_SERVICE); for (Network net : connectivityManager.getAllNetworks()) { NetworkInfo netInfo = connectivityManager.getNetworkInfo(net); if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI && netInfo.getExtraInfo() != null && netInfo.getExtraInfo() .equals(sm.mStateRegistry.wifiInfo.getSSID())) { connectivityManager.bindProcessToNetwork(net); break; } } } sm.mStateRegistry.apiAttempts = 1; sm.setCurrentState(State.CHECK_API); }
/** * Returns TRUE if WiFi is ON and connected. * <br><br> * This method requires the caller to hold the permission android.Manifest.permission.ACCESS_NETWORK_STATE * * @param context * @return */ @SuppressLint("NewApi") public static boolean net_isWifiOn(Context context) { boolean res = false; ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if(connManager!=null) { if(ToolBox.device_hasAPILevel(ApiLevel.LEVEL_21)){ Network[] networks = connManager.getAllNetworks(); for(Network n:networks) { NetworkInfo nInfo = connManager.getNetworkInfo(n); if( nInfo != null && nInfo.getType() == ConnectivityManager.TYPE_WIFI && nInfo.isConnected()){ res = true; break; } } }else{ NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mWifi!=null && mWifi.isConnected()) { res = true; } } } return res; }
private void defaultToWifi() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { connectivityManager.setNetworkPreference(ConnectivityManager.TYPE_WIFI); return; } Network network = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ network = getNetwork(); } if(network != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { connectivityManager.bindProcessToNetwork(getNetwork()); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { ConnectivityManager.setProcessDefaultNetwork(network); } catch (IllegalStateException ignored) { } } } }
@SuppressWarnings("deprecation") private void recheckNetwork() { Network network; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ network = getNetwork(); } else { return; } if(network != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { connectivityManager.reportNetworkConnectivity(network,true); return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { connectivityManager.reportBadNetwork(network); } } }
@SuppressWarnings("deprecation") private static boolean connectedToWifi(Context context) { boolean wifiConnected = false; ConnectivityManager connManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { NetworkInfo mWifi = connManager.getNetworkInfo( ConnectivityManager.TYPE_WIFI); wifiConnected = mWifi != null && mWifi.isConnected(); } else { Network[] networks = connManager.getAllNetworks(); NetworkInfo networkInfo; for (Network mNetwork : networks) { networkInfo = connManager.getNetworkInfo(mNetwork); wifiConnected = (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()); } } return wifiConnected; }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) private LinkProperties getLP(ConnectivityManager connMgr, int cap) { Network nets[] = connMgr.getAllNetworks(); for (Network n: nets) { LinkProperties lp = connMgr.getLinkProperties(n); NetworkCapabilities np = connMgr.getNetworkCapabilities(n); String iname = lp.getInterfaceName(); if (iname != null && np != null) { //Log.d(TAG, ">>> " + iname + ": " + np.hasTransport(cap)); if (np.hasTransport(cap)) return lp; } } return null; }
/** * Returns connection type and status information about |network|. * Only callable on Lollipop and newer releases. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) NetworkState getNetworkState(Network network) { final NetworkInfo networkInfo = getNetworkInfo(network); if (networkInfo != null && networkInfo.getType() == TYPE_VPN) { // When a VPN is in place the underlying network type can be queried via // getActiveNeworkInfo() thanks to // https://android.googlesource.com/platform/frameworks/base/+/d6a7980d return getNetworkState(); } return getNetworkState(networkInfo); }
/** * Returns {@code true} if {@code network} applies to (and hence is accessible) to the * current user. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) @VisibleForTesting protected boolean vpnAccessible(Network network) { // Determine if the VPN applies to the current user by seeing if a socket can be bound // to the VPN. try { network.getSocketFactory().createSocket().close(); } catch (IOException e) { // Failed to bind so this VPN isn't for the current user to use. return false; } return true; }
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]; } } }
/** * Should changes to connected network {@code network} be ignored? * @param network Network to possibly consider ignoring changes to. * @param capabilities {@code NetworkCapabilities} for {@code network} if known, otherwise * {@code null}. * @return {@code true} when either: {@code network} is an inaccessible VPN, or has already * disconnected. */ private boolean ignoreConnectedInaccessibleVpn( Network network, NetworkCapabilities capabilities) { // Fetch capabilities if not provided. if (capabilities == null) { capabilities = mConnectivityManagerDelegate.getNetworkCapabilities(network); } // Ignore inaccessible VPNs as they don't apply to Chrome. return capabilities == null || capabilities.hasTransport(TRANSPORT_VPN) && !mConnectivityManagerDelegate.vpnAccessible(network); }
@Override public void onAvailable(Network network) { final NetworkCapabilities capabilities = mConnectivityManagerDelegate.getNetworkCapabilities(network); if (ignoreConnectedNetwork(network, capabilities)) { return; } final boolean makeVpnDefault = capabilities.hasTransport(TRANSPORT_VPN); if (makeVpnDefault) { mVpnInPlace = network; } final long netId = networkToNetId(network); final int connectionType = getCurrentConnectionType(mConnectivityManagerDelegate.getNetworkState(network)); ThreadUtils.postOnUiThread(new Runnable() { @Override public void run() { mObserver.onNetworkConnect(netId, connectionType); if (makeVpnDefault) { // Make VPN the default network. mObserver.onConnectionTypeChanged(connectionType); // Purge all other networks as they're inaccessible to Chrome now. mObserver.purgeActiveNetworkList(new long[] {netId}); } } }); }