Java Code Examples for android.net.NetworkCapabilities

The following examples show how to use android.net.NetworkCapabilities. These examples are extracted from open source projects. 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
@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 2
Source Project: android_9.0.0_r45   Source File: ConnectivityController.java    License: 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 3
Source Project: android_9.0.0_r45   Source File: ConnectivityController.java    License: 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 4
Source Project: Ruisi   Source File: CheckNet.java    License: 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 5
Source Project: android_9.0.0_r45   Source File: GnssLocationProvider.java    License: 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 6
Source Project: android_9.0.0_r45   Source File: Vpn.java    License: 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 7
/**
 * 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 8
Source Project: android_9.0.0_r45   Source File: NetworkAgentInfo.java    License: 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 9
Source Project: Telegram-FOSS   Source File: Requirements.java    License: 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 10
Source Project: android_9.0.0_r45   Source File: DefaultNetworkEvent.java    License: 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 11
Source Project: particle-android   Source File: WifiFacade.java    License: 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 12
Source Project: libcommon   Source File: ConnectivityHelper.java    License: 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
@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 14
Source Project: DanDanPlayForAndroid   Source File: LocalIPUtil.java    License: MIT License 6 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 15
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];
        }
    }
}
 
Example 16
public void testSocketFactoryNull2() {
    setupMockNetworks(new MockNetworkConfig[] {
            new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_CELLULAR, FactoryRet.RETURNS_ANOTHER_FACTORY),
            new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_WIFI, FactoryRet.RETURNS_NULL),
            new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_WIFI, FactoryRet.RETURNS_CORRECT_FACTORY),
    });

    Socket ret = WiFiSocketFactory.createSocket(mMockContext);

    assertNotNull("createSocket() should always return a Socket instance", ret);
    assertEquals("Returned Socket should be created through SocketFactory", mWiFiBoundSocket, ret);
}
 
Example 17
Source Project: react-native-tcp-socket   Source File: TcpSocketModule.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a network given its interface name:
 * "wifi" -> WIFI
 * "cellular" -> Cellular
 * etc...
 */
private void selectNetwork(@Nullable final String iface, @Nullable final String ipAddress) throws InterruptedException, IOException {
    currentNetwork.setNetwork(null);
    if (iface == null) return;
    if (ipAddress != null) {
        final Network cachedNetwork = mNetworkMap.get(iface + ipAddress);
        if (cachedNetwork != null) {
            currentNetwork.setNetwork(cachedNetwork);
            return;
        }
    }
    switch (iface) {
        case "wifi":
            requestNetwork(NetworkCapabilities.TRANSPORT_WIFI);
            break;
        case "cellular":
            requestNetwork(NetworkCapabilities.TRANSPORT_CELLULAR);
            break;
        case "ethernet":
            requestNetwork(NetworkCapabilities.TRANSPORT_ETHERNET);
            break;
    }
    if (currentNetwork.getNetwork() == null) {
        throw new IOException("Interface " + iface + " unreachable");
    } else if (ipAddress != null && !ipAddress.equals("0.0.0.0"))
        mNetworkMap.put(iface + ipAddress, currentNetwork.getNetwork());
}
 
Example 18
Source Project: webrtc_android   Source File: NetworkMonitorAutoDetect.java    License: MIT License 5 votes vote down vote up
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
  // A capabilities change may indicate the ConnectionType has changed,
  // so forward the new NetworkInformation along to the observer.
  Logging.d(TAG, "capabilities changed: " + networkCapabilities.toString());
  onNetworkChanged(network);
}
 
Example 19
Source Project: Telegram   Source File: RequirementsWatcher.java    License: 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 20
Source Project: webrtc_android   Source File: NetworkMonitorAutoDetect.java    License: MIT License 5 votes vote down vote up
/** Only callable on Lollipop and newer releases. */
@SuppressLint("NewApi")
public void registerNetworkCallback(NetworkCallback networkCallback) {
  connectivityManager.registerNetworkCallback(
      new NetworkRequest.Builder()
          .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
          .build(),
      networkCallback);
}
 
Example 21
Source Project: webrtc_android   Source File: NetworkMonitorAutoDetect.java    License: MIT License 5 votes vote down vote up
/** Only callable on Lollipop and newer releases. */
@SuppressLint("NewApi")
public void requestMobileNetwork(NetworkCallback networkCallback) {
  NetworkRequest.Builder builder = new NetworkRequest.Builder();
  builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
      .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
  connectivityManager.requestNetwork(builder.build(), networkCallback);
}
 
Example 22
/**
 * 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);
}
 
Example 23
Source Project: JobSchedulerCompat   Source File: JobInfo.java    License: MIT License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.P)
private void syncRequiredNetworkAndType(NetworkRequest networkRequest, Integer networkType) {
    if (networkType == null) {
        if (networkRequest == null) {
            this.networkType = NETWORK_TYPE_NONE;
        } else if (networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
            this.networkType = NETWORK_TYPE_UNMETERED;
        } else if (networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING)) {
            this.networkType = NETWORK_TYPE_NOT_ROAMING;
        } else if (networkRequest.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
            this.networkType = NETWORK_TYPE_CELLULAR;
        } else {
            this.networkType = NETWORK_TYPE_ANY;
        }
    } else {
        final NetworkRequest.Builder builder = new NetworkRequest.Builder();
        builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
        builder.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
        builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
        if (networkType == NETWORK_TYPE_UNMETERED) {
            builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
        } else if (networkType == NETWORK_TYPE_NOT_ROAMING) {
            builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
        } else if (networkType == NETWORK_TYPE_CELLULAR) {
            builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
        }
        this.networkRequest = builder.build();
    }
}
 
Example 24
Source Project: android_9.0.0_r45   Source File: ConnectivityController.java    License: 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 25
@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 26
public void testWithWiFiNetwork() {
    setupMockNetworks(new MockNetworkConfig[] {
            new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_CELLULAR, FactoryRet.RETURNS_ANOTHER_FACTORY),
            new MockNetworkConfig(false, NetworkCapabilities.TRANSPORT_WIFI, FactoryRet.RETURNS_CORRECT_FACTORY),
    });

    Socket ret = WiFiSocketFactory.createSocket(mMockContext);

    assertNotNull("createSocket() should always return a Socket instance", ret);
    assertEquals("Returned Socket should be created through SocketFactory", mWiFiBoundSocket, ret);
}
 
Example 27
Source Project: android-job   Source File: Device.java    License: 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 28
Source Project: android_9.0.0_r45   Source File: ConnectivityController.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) {
    if (DEBUG) {
        Slog.v(TAG, "onCapabilitiesChanged: " + network);
    }
    updateTrackedJobs(-1, network);
}
 
Example 29
Source Project: android_9.0.0_r45   Source File: LingerMonitor.java    License: Apache License 2.0 5 votes vote down vote up
private static HashMap<String, Integer> makeTransportToNameMap() {
    SparseArray<String> numberToName = MessageUtils.findMessageNames(
        new Class[] { NetworkCapabilities.class }, new String[]{ "TRANSPORT_" });
    HashMap<String, Integer> nameToNumber = new HashMap<>();
    for (int i = 0; i < numberToName.size(); i++) {
        // MessageUtils will fail to initialize if there are duplicate constant values, so there
        // are no duplicates here.
        nameToNumber.put(numberToName.valueAt(i), numberToName.keyAt(i));
    }
    return nameToNumber;
}
 
Example 30
Source Project: android_9.0.0_r45   Source File: Vpn.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected Vpn(Looper looper, Context context, INetworkManagementService netService,
        int userHandle, SystemServices systemServices) {
    mContext = context;
    mNetd = netService;
    mUserHandle = userHandle;
    mLooper = looper;
    mSystemServices = systemServices;

    mPackage = VpnConfig.LEGACY_VPN;
    mOwnerUID = getAppUid(mPackage, mUserHandle);

    try {
        netService.registerObserver(mObserver);
    } catch (RemoteException e) {
        Log.wtf(TAG, "Problem registering observer", e);
    }

    mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0 /* subtype */, NETWORKTYPE,
            "" /* subtypeName */);
    mNetworkCapabilities = new NetworkCapabilities();
    mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
    mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
    updateCapabilities(null /* defaultNetwork */);

    loadAlwaysOnPackage();
}