1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.net; 18 19 import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL; 20 import static android.net.NetworkCapabilities.NET_CAPABILITY_DUN; 21 import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND; 22 import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET; 23 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED; 24 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED; 25 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED; 26 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING; 27 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED; 28 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED; 29 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN; 30 import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY; 31 import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED; 32 import static android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED; 33 import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED; 34 import static android.net.NetworkCapabilities.TRANSPORT_TEST; 35 36 import android.annotation.NonNull; 37 import android.annotation.Nullable; 38 import android.annotation.RequiresPermission; 39 import android.annotation.SuppressLint; 40 import android.annotation.SystemApi; 41 import android.compat.annotation.UnsupportedAppUsage; 42 import android.net.NetworkCapabilities.NetCapability; 43 import android.net.NetworkCapabilities.Transport; 44 import android.os.Build; 45 import android.os.Parcel; 46 import android.os.Parcelable; 47 import android.os.Process; 48 import android.text.TextUtils; 49 import android.util.Range; 50 51 import java.util.Arrays; 52 import java.util.List; 53 import java.util.Objects; 54 import java.util.Set; 55 56 /** 57 * An object describing a network that the application is interested in. 58 * 59 * <p>@see <a href="https://developer.android.com/training/basics/network-ops/reading-network-state> 60 * this general guide</a> on how to use NetworkCapabilities and related classes. 61 * 62 * NetworkRequest defines a request for a network, made through 63 * {@link NetworkRequest.Builder} and used to request a network via 64 * {@link ConnectivityManager#requestNetwork} or to listen for changes 65 * via the {@link ConnectivityManager#registerNetworkCallback} family of 66 * functions. 67 * 68 * <p>{@link ConnectivityManager#requestNetwork} will try to find a connected 69 * network matching the NetworkRequest, and return it if there is one. 70 * As long as the request is outstanding, the system will try to find the best 71 * possible network that matches the request. The request will keep up the 72 * currently best connected network, and if a better one is found (e.g. cheaper 73 * or faster) the system will bring up that better network to better serve the 74 * request. A request filed with {@link ConnectivityManager#requestNetwork} will 75 * only match one network at a time (the one the system thinks is best), even if 76 * other networks can match the request that are being kept up by other requests. 77 * 78 * For example, an application needing a network with 79 * {@link NetworkCapabilities#NET_CAPABILITY_INTERNET} should use 80 * {@link ConnectivityManager#requestNetwork} to request the system keeps one up. 81 * A general cellular network can satisfy this request, but if the system finds 82 * a free Wi-Fi network which is expected to be faster, it will try and connect 83 * to that Wi-Fi network and switch the request over to it once it is connected. 84 * The cell network may stay connected if there are outstanding requests (from 85 * the same app or from other apps on the system) that match the cell network 86 * but not the Wi-Fi network, such as a request with {@link NetworkCapabilities#NET_CAPABILITY_MMS}. 87 * 88 * When a network is no longer needed to serve any request, the system can 89 * tear it down at any time and usually does so immediately, so make sure to 90 * keep up requests for the networks your app needs. 91 * 92 * <p>By contrast, requests filed with {@link ConnectivityManager#registerNetworkCallback} 93 * will receive callbacks for all matching networks, and will not cause the system to 94 * keep up the networks they match. Use this to listen to networks that the device is 95 * connected to, but that you don't want the system to keep up for your use case. 96 * 97 * <p>Applications build a NetworkRequest and pass it to one of the 98 * {@link ConnectivityManager} methods above together with a 99 * {@link ConnectivityManager.NetworkCallback} object. The callback 100 * will then start receiving method calls about networks that match 101 * the request. 102 * 103 * <p>Networks are brought up and/or matched according to the capabilities 104 * set in the builder. For example, a request with 105 * {@link NetworkCapabilities#NET_CAPABILITY_MMS} lets the system match 106 * and/or bring up a network that is capable to send MMS. A request with 107 * {@link NetworkCapabilities#NET_CAPABILITY_NOT_METERED} matches a network 108 * that doesn't charge the user for usage. See 109 * {@link NetworkCapabilities} for a list of capabilities and their 110 * description. 111 * 112 * <p>While all capabilities can be matched with the 113 * {@link ConnectivityManager#registerNetworkCallback} family of methods, 114 * not all capabilities can be used to request that the system brings 115 * up a network with {@link ConnectivityManager#requestNetwork}. For example, 116 * an application cannot use {@link ConnectivityManager#requestNetwork} to 117 * ask the system to bring up a network with 118 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}, because the 119 * system won't know if a network has a captive portal before it connects 120 * to that network. Similarly, some capabilities may require a specific 121 * permission or privilege to be requested. 122 * 123 * Look up the specific capability and the {@link ConnectivityManager#requestNetwork} 124 * method for limitations applicable to each capability. 125 * 126 * <p>Also, starting with {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, some capabilities 127 * require the application to self-certify by explicitly adding the 128 * {@link android.content.pm.PackageManager#PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES} 129 * property in the AndroidManifest.xml, which points to an XML resource file. In the 130 * XML resource file, the application declares what kind of network capabilities the application 131 * wants to have. 132 * 133 * Here is an example self-certification XML resource file : 134 * <pre> 135 * {@code 136 * <network-capabilities-declaration xmlns:android="http://schemas.android.com/apk/res/android"> 137 * <uses-network-capability android:name="NET_CAPABILITY_PRIORITIZE_LATENCY"/> 138 * <uses-network-capability android:name="NET_CAPABILITY_PRIORITIZE_BANDWIDTH"/> 139 * </network-capabilities-declaration> 140 * } 141 * </pre> 142 * Look up the specific capability to learn whether its usage requires this self-certification. 143 */ 144 public class NetworkRequest implements Parcelable { 145 /** 146 * The first requestId value that will be allocated. 147 * @hide only used by ConnectivityService. 148 */ 149 public static final int FIRST_REQUEST_ID = 1; 150 151 /** 152 * The requestId value that represents the absence of a request. 153 * @hide only used by ConnectivityService. 154 */ 155 public static final int REQUEST_ID_NONE = -1; 156 157 /** 158 * The {@link NetworkCapabilities} that define this request. 159 * @hide 160 */ 161 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 162 public final @NonNull NetworkCapabilities networkCapabilities; 163 164 /** 165 * Identifies the request. NetworkRequests should only be constructed by 166 * the Framework and given out to applications as tokens to be used to identify 167 * the request. 168 * @hide 169 */ 170 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 171 public final int requestId; 172 173 /** 174 * Set for legacy requests and the default. Set to TYPE_NONE for none. 175 * Causes CONNECTIVITY_ACTION broadcasts to be sent. 176 * @hide 177 */ 178 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 179 public final int legacyType; 180 181 /** 182 * A NetworkRequest as used by the system can be one of the following types: 183 * 184 * - LISTEN, for which the framework will issue callbacks about any 185 * and all networks that match the specified NetworkCapabilities, 186 * 187 * - REQUEST, capable of causing a specific network to be created 188 * first (e.g. a telephony DUN request), the framework will issue 189 * callbacks about the single, highest scoring current network 190 * (if any) that matches the specified NetworkCapabilities, or 191 * 192 * - TRACK_DEFAULT, which causes the framework to issue callbacks for 193 * the single, highest scoring current network (if any) that will 194 * be chosen for an app, but which cannot cause the framework to 195 * either create or retain the existence of any specific network. 196 * 197 * - TRACK_SYSTEM_DEFAULT, which causes the framework to send callbacks 198 * for the network (if any) that satisfies the default Internet 199 * request. 200 * 201 * - TRACK_BEST, which causes the framework to send callbacks about 202 * the single, highest scoring current network (if any) that matches 203 * the specified NetworkCapabilities. 204 * 205 * - BACKGROUND_REQUEST, like REQUEST but does not cause any networks 206 * to retain the NET_CAPABILITY_FOREGROUND capability. A network with 207 * no foreground requests is in the background. A network that has 208 * one or more background requests and loses its last foreground 209 * request to a higher-scoring network will not go into the 210 * background immediately, but will linger and go into the background 211 * after the linger timeout. 212 * 213 * - The value NONE is used only by applications. When an application 214 * creates a NetworkRequest, it does not have a type; the type is set 215 * by the system depending on the method used to file the request 216 * (requestNetwork, registerNetworkCallback, etc.). 217 * 218 * @hide 219 */ 220 public static enum Type { 221 NONE, 222 LISTEN, 223 TRACK_DEFAULT, 224 REQUEST, 225 BACKGROUND_REQUEST, 226 TRACK_SYSTEM_DEFAULT, 227 LISTEN_FOR_BEST, 228 }; 229 230 /** 231 * The type of the request. This is only used by the system and is always NONE elsewhere. 232 * 233 * @hide 234 */ 235 public final Type type; 236 237 /** 238 * @hide 239 */ NetworkRequest(NetworkCapabilities nc, int legacyType, int rId, Type type)240 public NetworkRequest(NetworkCapabilities nc, int legacyType, int rId, Type type) { 241 if (nc == null) { 242 throw new NullPointerException(); 243 } 244 requestId = rId; 245 networkCapabilities = nc; 246 this.legacyType = legacyType; 247 this.type = type; 248 } 249 250 /** 251 * @hide 252 */ NetworkRequest(NetworkRequest that)253 public NetworkRequest(NetworkRequest that) { 254 networkCapabilities = new NetworkCapabilities(that.networkCapabilities); 255 requestId = that.requestId; 256 this.legacyType = that.legacyType; 257 this.type = that.type; 258 } 259 260 /** 261 * Builder used to create {@link NetworkRequest} objects. Specify the Network features 262 * needed in terms of {@link NetworkCapabilities} features 263 */ 264 public static class Builder { 265 /** 266 * Capabilities that are currently compatible with VCN networks. 267 */ 268 private static final List<Integer> VCN_SUPPORTED_CAPABILITIES = Arrays.asList( 269 NET_CAPABILITY_CAPTIVE_PORTAL, 270 NET_CAPABILITY_DUN, 271 NET_CAPABILITY_FOREGROUND, 272 NET_CAPABILITY_INTERNET, 273 NET_CAPABILITY_NOT_CONGESTED, 274 NET_CAPABILITY_NOT_METERED, 275 NET_CAPABILITY_NOT_RESTRICTED, 276 NET_CAPABILITY_NOT_ROAMING, 277 NET_CAPABILITY_NOT_SUSPENDED, 278 NET_CAPABILITY_NOT_VPN, 279 NET_CAPABILITY_PARTIAL_CONNECTIVITY, 280 NET_CAPABILITY_TEMPORARILY_NOT_METERED, 281 NET_CAPABILITY_TRUSTED, 282 NET_CAPABILITY_VALIDATED); 283 284 private final NetworkCapabilities mNetworkCapabilities; 285 286 // A boolean that represents whether the NOT_VCN_MANAGED capability should be deduced when 287 // the NetworkRequest object is built. 288 private boolean mShouldDeduceNotVcnManaged = true; 289 290 /** 291 * Default constructor for Builder. 292 */ Builder()293 public Builder() { 294 // By default, restrict this request to networks available to this app. 295 // Apps can rescind this restriction, but ConnectivityService will enforce 296 // it for apps that do not have the NETWORK_SETTINGS permission. 297 mNetworkCapabilities = new NetworkCapabilities(); 298 mNetworkCapabilities.setSingleUid(Process.myUid()); 299 } 300 301 /** 302 * Creates a new Builder of NetworkRequest from an existing instance. 303 */ Builder(@onNull final NetworkRequest request)304 public Builder(@NonNull final NetworkRequest request) { 305 Objects.requireNonNull(request); 306 mNetworkCapabilities = request.networkCapabilities; 307 // If the caller constructed the builder from a request, it means the user 308 // might explicitly want the capabilities from the request. Thus, the NOT_VCN_MANAGED 309 // capabilities should not be touched later. 310 mShouldDeduceNotVcnManaged = false; 311 } 312 313 /** 314 * Build {@link NetworkRequest} give the current set of capabilities. 315 */ build()316 public NetworkRequest build() { 317 // Make a copy of mNetworkCapabilities so we don't inadvertently remove NOT_RESTRICTED 318 // when later an unrestricted capability could be added to mNetworkCapabilities, in 319 // which case NOT_RESTRICTED should be returned to mNetworkCapabilities, which 320 // maybeMarkCapabilitiesRestricted() doesn't add back. 321 final NetworkCapabilities nc = new NetworkCapabilities(mNetworkCapabilities); 322 nc.maybeMarkCapabilitiesRestricted(); 323 deduceNotVcnManagedCapability(nc); 324 return new NetworkRequest(nc, ConnectivityManager.TYPE_NONE, 325 ConnectivityManager.REQUEST_ID_UNSET, Type.NONE); 326 } 327 328 /** 329 * Add the given capability requirement to this builder. These represent 330 * the requested network's required capabilities. Note that when searching 331 * for a network to satisfy a request, all capabilities requested must be 332 * satisfied. 333 * 334 * @param capability The capability to add. 335 * @return The builder to facilitate chaining 336 * {@code builder.addCapability(...).addCapability();}. 337 */ addCapability(@etworkCapabilities.NetCapability int capability)338 public Builder addCapability(@NetworkCapabilities.NetCapability int capability) { 339 mNetworkCapabilities.addCapability(capability); 340 if (capability == NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED) { 341 mShouldDeduceNotVcnManaged = false; 342 } 343 return this; 344 } 345 346 /** 347 * Removes (if found) the given capability from this builder instance. 348 * 349 * @param capability The capability to remove. 350 * @return The builder to facilitate chaining. 351 */ removeCapability(@etworkCapabilities.NetCapability int capability)352 public Builder removeCapability(@NetworkCapabilities.NetCapability int capability) { 353 mNetworkCapabilities.removeCapability(capability); 354 if (capability == NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED) { 355 mShouldDeduceNotVcnManaged = false; 356 } 357 return this; 358 } 359 360 /** 361 * Set the {@code NetworkCapabilities} for this builder instance, 362 * overriding any capabilities that had been previously set. 363 * 364 * @param nc The superseding {@code NetworkCapabilities} instance. 365 * @return The builder to facilitate chaining. 366 * @hide 367 */ setCapabilities(NetworkCapabilities nc)368 public Builder setCapabilities(NetworkCapabilities nc) { 369 mNetworkCapabilities.set(nc); 370 return this; 371 } 372 373 /** 374 * Sets this request to match only networks that apply to the specified UIDs. 375 * 376 * By default, the set of UIDs is the UID of the calling app, and this request will match 377 * any network that applies to the app. Setting it to {@code null} will observe any 378 * network on the system, even if it does not apply to this app. In this case, any 379 * {@link NetworkSpecifier} set on this request will be redacted or removed to prevent the 380 * application deducing restricted information such as location. 381 * 382 * @param uids The UIDs as a set of {@code Range<Integer>}, or null for everything. 383 * @return The builder to facilitate chaining. 384 * @hide 385 */ 386 @NonNull 387 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 388 @SuppressLint("MissingGetterMatchingBuilder") setUids(@ullable Set<Range<Integer>> uids)389 public Builder setUids(@Nullable Set<Range<Integer>> uids) { 390 mNetworkCapabilities.setUids(uids); 391 return this; 392 } 393 394 /** 395 * Add a capability that must not exist in the requested network. 396 * <p> 397 * If the capability was previously added to the list of required capabilities (for 398 * example, it was there by default or added using {@link #addCapability(int)} method), then 399 * it will be removed from the list of required capabilities as well. 400 * 401 * @see #addCapability(int) 402 * 403 * @param capability The capability to add to forbidden capability list. 404 * @return The builder to facilitate chaining. 405 * 406 * @hide 407 */ 408 @NonNull 409 @SuppressLint("MissingGetterMatchingBuilder") 410 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) addForbiddenCapability(@etworkCapabilities.NetCapability int capability)411 public Builder addForbiddenCapability(@NetworkCapabilities.NetCapability int capability) { 412 mNetworkCapabilities.addForbiddenCapability(capability); 413 return this; 414 } 415 416 /** 417 * Removes (if found) the given forbidden capability from this builder instance. 418 * 419 * @param capability The forbidden capability to remove. 420 * @return The builder to facilitate chaining. 421 * 422 * @hide 423 */ 424 @NonNull 425 @SuppressLint("BuilderSetStyle") 426 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) removeForbiddenCapability( @etworkCapabilities.NetCapability int capability)427 public Builder removeForbiddenCapability( 428 @NetworkCapabilities.NetCapability int capability) { 429 mNetworkCapabilities.removeForbiddenCapability(capability); 430 return this; 431 } 432 433 /** 434 * Completely clears all the {@code NetworkCapabilities} from this builder instance, 435 * removing even the capabilities that are set by default when the object is constructed. 436 * 437 * @return The builder to facilitate chaining. 438 */ 439 @NonNull clearCapabilities()440 public Builder clearCapabilities() { 441 mNetworkCapabilities.clearAll(); 442 // If the caller explicitly clear all capabilities, the NOT_VCN_MANAGED capabilities 443 // should not be add back later. 444 mShouldDeduceNotVcnManaged = false; 445 return this; 446 } 447 448 /** 449 * Adds the given transport requirement to this builder. These represent 450 * the set of allowed transports for the request. Only networks using one 451 * of these transports will satisfy the request. If no particular transports 452 * are required, none should be specified here. 453 * 454 * @param transportType The transport type to add. 455 * @return The builder to facilitate chaining. 456 */ addTransportType(@etworkCapabilities.Transport int transportType)457 public Builder addTransportType(@NetworkCapabilities.Transport int transportType) { 458 mNetworkCapabilities.addTransportType(transportType); 459 return this; 460 } 461 462 /** 463 * Removes (if found) the given transport from this builder instance. 464 * 465 * @param transportType The transport type to remove. 466 * @return The builder to facilitate chaining. 467 */ removeTransportType(@etworkCapabilities.Transport int transportType)468 public Builder removeTransportType(@NetworkCapabilities.Transport int transportType) { 469 mNetworkCapabilities.removeTransportType(transportType); 470 return this; 471 } 472 473 /** 474 * @hide 475 */ setLinkUpstreamBandwidthKbps(int upKbps)476 public Builder setLinkUpstreamBandwidthKbps(int upKbps) { 477 mNetworkCapabilities.setLinkUpstreamBandwidthKbps(upKbps); 478 return this; 479 } 480 /** 481 * @hide 482 */ setLinkDownstreamBandwidthKbps(int downKbps)483 public Builder setLinkDownstreamBandwidthKbps(int downKbps) { 484 mNetworkCapabilities.setLinkDownstreamBandwidthKbps(downKbps); 485 return this; 486 } 487 488 /** 489 * Sets the optional bearer specific network specifier. 490 * This has no meaning if a single transport is also not specified, so calling 491 * this without a single transport set will generate an exception, as will 492 * subsequently adding or removing transports after this is set. 493 * </p> 494 * If the {@code networkSpecifier} is provided, it shall be interpreted as follows: 495 * <ul> 496 * <li>If the specifier can be parsed as an integer, it will be treated as a 497 * {@link android.net TelephonyNetworkSpecifier}, and the provided integer will be 498 * interpreted as a SubscriptionId. 499 * <li>If the value is an ethernet interface name, it will be treated as such. 500 * <li>For all other cases, the behavior is undefined. 501 * </ul> 502 * 503 * @param networkSpecifier A {@code String} of either a SubscriptionId in cellular 504 * network request or an ethernet interface name in ethernet 505 * network request. 506 * 507 * @deprecated Use {@link #setNetworkSpecifier(NetworkSpecifier)} instead. 508 */ 509 @Deprecated setNetworkSpecifier(String networkSpecifier)510 public Builder setNetworkSpecifier(String networkSpecifier) { 511 try { 512 int subId = Integer.parseInt(networkSpecifier); 513 return setNetworkSpecifier(new TelephonyNetworkSpecifier.Builder() 514 .setSubscriptionId(subId).build()); 515 } catch (NumberFormatException nfe) { 516 // An EthernetNetworkSpecifier or TestNetworkSpecifier does not accept null or empty 517 // ("") strings. When network specifiers were strings a null string and an empty 518 // string were considered equivalent. Hence no meaning is attached to a null or 519 // empty ("") string. 520 if (TextUtils.isEmpty(networkSpecifier)) { 521 return setNetworkSpecifier((NetworkSpecifier) null); 522 } else if (mNetworkCapabilities.hasTransport(TRANSPORT_TEST)) { 523 return setNetworkSpecifier(new TestNetworkSpecifier(networkSpecifier)); 524 } else { 525 return setNetworkSpecifier(new EthernetNetworkSpecifier(networkSpecifier)); 526 } 527 } 528 } 529 530 /** 531 * Sets the optional bearer specific network specifier. 532 * This has no meaning if a single transport is also not specified, so calling 533 * this without a single transport set will generate an exception, as will 534 * subsequently adding or removing transports after this is set. 535 * </p> 536 * 537 * @param networkSpecifier A concrete, parcelable framework class that extends 538 * NetworkSpecifier. 539 */ setNetworkSpecifier(NetworkSpecifier networkSpecifier)540 public Builder setNetworkSpecifier(NetworkSpecifier networkSpecifier) { 541 if (networkSpecifier instanceof MatchAllNetworkSpecifier) { 542 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted"); 543 } 544 mNetworkCapabilities.setNetworkSpecifier(networkSpecifier); 545 // Do not touch NOT_VCN_MANAGED if the caller needs to access to a very specific 546 // Network. 547 mShouldDeduceNotVcnManaged = false; 548 return this; 549 } 550 551 /** 552 * Sets the signal strength. This is a signed integer, with higher values indicating a 553 * stronger signal. The exact units are bearer-dependent. For example, Wi-Fi uses the same 554 * RSSI units reported by WifiManager. 555 * <p> 556 * Note that when used to register a network callback, this specifies the minimum acceptable 557 * signal strength. When received as the state of an existing network it specifies the 558 * current value. A value of {@code SIGNAL_STRENGTH_UNSPECIFIED} means no value when 559 * received and has no effect when requesting a callback. 560 * 561 * <p>This method requires the caller to hold the 562 * {@link android.Manifest.permission#NETWORK_SIGNAL_STRENGTH_WAKEUP} permission 563 * 564 * @param signalStrength the bearer-specific signal strength. 565 * @hide 566 */ 567 @SystemApi 568 @RequiresPermission(android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP) setSignalStrength(int signalStrength)569 public @NonNull Builder setSignalStrength(int signalStrength) { 570 mNetworkCapabilities.setSignalStrength(signalStrength); 571 return this; 572 } 573 574 /** 575 * Deduce the NET_CAPABILITY_NOT_VCN_MANAGED capability from other capabilities 576 * and user intention, which includes: 577 * 1. For the requests that don't have anything besides 578 * {@link #VCN_SUPPORTED_CAPABILITIES}, add the NET_CAPABILITY_NOT_VCN_MANAGED to 579 * allow the callers automatically utilize VCN networks if available. 580 * 2. For the requests that explicitly add or remove NET_CAPABILITY_NOT_VCN_MANAGED, 581 * or has clear intention of tracking specific network, 582 * do not alter them to allow user fire request that suits their need. 583 * 584 * @hide 585 */ deduceNotVcnManagedCapability(final NetworkCapabilities nc)586 private void deduceNotVcnManagedCapability(final NetworkCapabilities nc) { 587 if (!mShouldDeduceNotVcnManaged) return; 588 for (final int cap : nc.getCapabilities()) { 589 if (!VCN_SUPPORTED_CAPABILITIES.contains(cap)) return; 590 } 591 nc.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED); 592 } 593 594 /** 595 * Sets the optional subscription ID set. 596 * <p> 597 * This specify the subscription IDs requirement. 598 * A network will satisfy this request only if it matches one of the subIds in this set. 599 * An empty set matches all networks, including those without a subId. 600 * 601 * <p>Registering a NetworkRequest with a non-empty set of subIds requires the 602 * NETWORK_FACTORY permission. 603 * 604 * @param subIds A {@code Set} that represents subscription IDs. 605 * @hide 606 */ 607 @NonNull 608 @SystemApi setSubscriptionIds(@onNull Set<Integer> subIds)609 public Builder setSubscriptionIds(@NonNull Set<Integer> subIds) { 610 mNetworkCapabilities.setSubscriptionIds(subIds); 611 return this; 612 } 613 614 /** 615 * Specifies whether the built request should also match networks that do not apply to the 616 * calling UID. 617 * 618 * By default, the built request will only match networks that apply to the calling UID. 619 * If this method is called with {@code true}, the built request will match any network on 620 * the system that matches the other parameters of the request. In this case, any 621 * information in the built request that is subject to redaction for security or privacy 622 * purposes, such as a {@link NetworkSpecifier}, will be redacted or removed to prevent the 623 * application deducing sensitive information. 624 * 625 * @param include Whether to match networks that do not apply to the calling UID. 626 * @return The builder to facilitate chaining. 627 */ 628 @NonNull setIncludeOtherUidNetworks(boolean include)629 public Builder setIncludeOtherUidNetworks(boolean include) { 630 if (include) { 631 mNetworkCapabilities.setUids(null); 632 } else { 633 mNetworkCapabilities.setSingleUid(Process.myUid()); 634 } 635 return this; 636 } 637 } 638 639 // implement the Parcelable interface describeContents()640 public int describeContents() { 641 return 0; 642 } writeToParcel(Parcel dest, int flags)643 public void writeToParcel(Parcel dest, int flags) { 644 networkCapabilities.writeToParcel(dest, flags); 645 dest.writeInt(legacyType); 646 dest.writeInt(requestId); 647 dest.writeString(type.name()); 648 } 649 650 public static final @android.annotation.NonNull Creator<NetworkRequest> CREATOR = 651 new Creator<NetworkRequest>() { 652 public NetworkRequest createFromParcel(Parcel in) { 653 NetworkCapabilities nc = NetworkCapabilities.CREATOR.createFromParcel(in); 654 int legacyType = in.readInt(); 655 int requestId = in.readInt(); 656 Type type = Type.valueOf(in.readString()); // IllegalArgumentException if invalid. 657 NetworkRequest result = new NetworkRequest(nc, legacyType, requestId, type); 658 return result; 659 } 660 public NetworkRequest[] newArray(int size) { 661 return new NetworkRequest[size]; 662 } 663 }; 664 665 /** 666 * Returns true iff. this NetworkRequest is of type LISTEN. 667 * 668 * @hide 669 */ isListen()670 public boolean isListen() { 671 return type == Type.LISTEN; 672 } 673 674 /** 675 * Returns true iff. this NetworkRequest is of type LISTEN_FOR_BEST. 676 * 677 * @hide 678 */ isListenForBest()679 public boolean isListenForBest() { 680 return type == Type.LISTEN_FOR_BEST; 681 } 682 683 /** 684 * Returns true iff. the contained NetworkRequest is one that: 685 * 686 * - should be associated with at most one satisfying network 687 * at a time; 688 * 689 * - should cause a network to be kept up, but not necessarily in 690 * the foreground, if it is the best network which can satisfy the 691 * NetworkRequest. 692 * 693 * For full detail of how isRequest() is used for pairing Networks with 694 * NetworkRequests read rematchNetworkAndRequests(). 695 * 696 * @hide 697 */ isRequest()698 public boolean isRequest() { 699 return type == Type.REQUEST || type == Type.BACKGROUND_REQUEST; 700 } 701 702 /** 703 * Returns true iff. this NetworkRequest is of type BACKGROUND_REQUEST. 704 * 705 * @hide 706 */ isBackgroundRequest()707 public boolean isBackgroundRequest() { 708 return type == Type.BACKGROUND_REQUEST; 709 } 710 711 /** 712 * @see Builder#addCapability(int) 713 */ hasCapability(@etCapability int capability)714 public boolean hasCapability(@NetCapability int capability) { 715 return networkCapabilities.hasCapability(capability); 716 } 717 718 /** 719 * @see Builder#addForbiddenCapability(int) 720 * 721 * @hide 722 */ 723 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) hasForbiddenCapability(@etCapability int capability)724 public boolean hasForbiddenCapability(@NetCapability int capability) { 725 return networkCapabilities.hasForbiddenCapability(capability); 726 } 727 728 /** 729 * Returns true if and only if the capabilities requested in this NetworkRequest are satisfied 730 * by the provided {@link NetworkCapabilities}. 731 * 732 * @param nc Capabilities that should satisfy this NetworkRequest. null capabilities do not 733 * satisfy any request. 734 */ canBeSatisfiedBy(@ullable NetworkCapabilities nc)735 public boolean canBeSatisfiedBy(@Nullable NetworkCapabilities nc) { 736 return networkCapabilities.satisfiedByNetworkCapabilities(nc); 737 } 738 739 /** 740 * @see Builder#addTransportType(int) 741 */ hasTransport(@ransport int transportType)742 public boolean hasTransport(@Transport int transportType) { 743 return networkCapabilities.hasTransport(transportType); 744 } 745 746 /** 747 * @see Builder#setNetworkSpecifier(NetworkSpecifier) 748 */ 749 @Nullable getNetworkSpecifier()750 public NetworkSpecifier getNetworkSpecifier() { 751 return networkCapabilities.getNetworkSpecifier(); 752 } 753 754 /** 755 * @return the uid of the app making the request. 756 * 757 * Note: This could return {@link Process#INVALID_UID} if the {@link NetworkRequest} object was 758 * not obtained from {@link ConnectivityManager}. 759 * @hide 760 */ 761 @SystemApi getRequestorUid()762 public int getRequestorUid() { 763 return networkCapabilities.getRequestorUid(); 764 } 765 766 /** 767 * @return the package name of the app making the request. 768 * 769 * Note: This could return {@code null} if the {@link NetworkRequest} object was not obtained 770 * from {@link ConnectivityManager}. 771 * @hide 772 */ 773 @SystemApi 774 @Nullable getRequestorPackageName()775 public String getRequestorPackageName() { 776 return networkCapabilities.getRequestorPackageName(); 777 } 778 toString()779 public String toString() { 780 return "NetworkRequest [ " + type + " id=" + requestId + 781 (legacyType != ConnectivityManager.TYPE_NONE ? ", legacyType=" + legacyType : "") + 782 ", " + networkCapabilities.toString() + " ]"; 783 } 784 equals(@ullable Object obj)785 public boolean equals(@Nullable Object obj) { 786 if (obj instanceof NetworkRequest == false) return false; 787 NetworkRequest that = (NetworkRequest)obj; 788 return (that.legacyType == this.legacyType && 789 that.requestId == this.requestId && 790 that.type == this.type && 791 Objects.equals(that.networkCapabilities, this.networkCapabilities)); 792 } 793 hashCode()794 public int hashCode() { 795 return Objects.hash(requestId, legacyType, networkCapabilities, type); 796 } 797 798 /** 799 * Gets all the capabilities set on this {@code NetworkRequest} instance. 800 * 801 * @return an array of capability values for this instance. 802 */ 803 @NonNull getCapabilities()804 public @NetCapability int[] getCapabilities() { 805 // No need to make a defensive copy here as NC#getCapabilities() already returns 806 // a new array. 807 return networkCapabilities.getCapabilities(); 808 } 809 810 /** 811 * Get the enteprise identifiers. 812 * 813 * Get all the enterprise identifiers set on this {@code NetworkCapability} 814 * @return array of all the enterprise identifiers. 815 * @hide 816 */ 817 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) getEnterpriseIds()818 public @NonNull @NetworkCapabilities.EnterpriseId int[] getEnterpriseIds() { 819 // No need to make a defensive copy here as NC#getCapabilities() already returns 820 // a new array. 821 return networkCapabilities.getEnterpriseIds(); 822 } 823 824 /** 825 * Tests for the presence of an enterprise identifier on this instance. 826 * 827 * @param enterpriseId the enterprise capability identifier to be tested for. 828 * @return {@code true} if set on this instance. 829 * @hide 830 */ 831 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) hasEnterpriseId( @etworkCapabilities.EnterpriseId int enterpriseId)832 public boolean hasEnterpriseId( 833 @NetworkCapabilities.EnterpriseId int enterpriseId) { 834 return networkCapabilities.hasEnterpriseId(enterpriseId); 835 } 836 837 /** 838 * Gets all the forbidden capabilities set on this {@code NetworkRequest} instance. 839 * 840 * @return an array of forbidden capability values for this instance. 841 * 842 * @hide 843 */ 844 @NonNull 845 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) getForbiddenCapabilities()846 public @NetCapability int[] getForbiddenCapabilities() { 847 // No need to make a defensive copy here as NC#getForbiddenCapabilities() already returns 848 // a new array. 849 return networkCapabilities.getForbiddenCapabilities(); 850 } 851 852 /** 853 * Gets all the transports set on this {@code NetworkRequest} instance. 854 * 855 * @return an array of transport type values for this instance. 856 */ 857 @NonNull getTransportTypes()858 public @Transport int[] getTransportTypes() { 859 // No need to make a defensive copy here as NC#getTransportTypes() already returns 860 // a new array. 861 return networkCapabilities.getTransportTypes(); 862 } 863 } 864