NetworkRequest.java revision 19c0ccaa8c59975aebfa4582b6038f261b6bb3d4
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 17package android.net; 18 19import android.annotation.NonNull; 20import android.net.NetworkCapabilities.NetCapability; 21import android.net.NetworkCapabilities.Transport; 22import android.os.Parcel; 23import android.os.Parcelable; 24import android.os.Process; 25import android.text.TextUtils; 26import android.util.proto.ProtoOutputStream; 27 28import java.util.Objects; 29import java.util.Set; 30 31/** 32 * Defines a request for a network, made through {@link NetworkRequest.Builder} and used 33 * to request a network via {@link ConnectivityManager#requestNetwork} or listen for changes 34 * via {@link ConnectivityManager#registerNetworkCallback}. 35 */ 36public class NetworkRequest implements Parcelable { 37 /** 38 * The {@link NetworkCapabilities} that define this request. 39 * @hide 40 */ 41 public final @NonNull NetworkCapabilities networkCapabilities; 42 43 /** 44 * Identifies the request. NetworkRequests should only be constructed by 45 * the Framework and given out to applications as tokens to be used to identify 46 * the request. 47 * @hide 48 */ 49 public final int requestId; 50 51 /** 52 * Set for legacy requests and the default. Set to TYPE_NONE for none. 53 * Causes CONNECTIVITY_ACTION broadcasts to be sent. 54 * @hide 55 */ 56 public final int legacyType; 57 58 /** 59 * A NetworkRequest as used by the system can be one of the following types: 60 * 61 * - LISTEN, for which the framework will issue callbacks about any 62 * and all networks that match the specified NetworkCapabilities, 63 * 64 * - REQUEST, capable of causing a specific network to be created 65 * first (e.g. a telephony DUN request), the framework will issue 66 * callbacks about the single, highest scoring current network 67 * (if any) that matches the specified NetworkCapabilities, or 68 * 69 * - TRACK_DEFAULT, a hybrid of the two designed such that the 70 * framework will issue callbacks for the single, highest scoring 71 * current network (if any) that matches the capabilities of the 72 * default Internet request (mDefaultRequest), but which cannot cause 73 * the framework to either create or retain the existence of any 74 * specific network. Note that from the point of view of the request 75 * matching code, TRACK_DEFAULT is identical to REQUEST: its special 76 * behaviour is not due to different semantics, but to the fact that 77 * the system will only ever create a TRACK_DEFAULT with capabilities 78 * that are identical to the default request's capabilities, thus 79 * causing it to share fate in every way with the default request. 80 * 81 * - BACKGROUND_REQUEST, like REQUEST but does not cause any networks 82 * to retain the NET_CAPABILITY_FOREGROUND capability. A network with 83 * no foreground requests is in the background. A network that has 84 * one or more background requests and loses its last foreground 85 * request to a higher-scoring network will not go into the 86 * background immediately, but will linger and go into the background 87 * after the linger timeout. 88 * 89 * - The value NONE is used only by applications. When an application 90 * creates a NetworkRequest, it does not have a type; the type is set 91 * by the system depending on the method used to file the request 92 * (requestNetwork, registerNetworkCallback, etc.). 93 * 94 * @hide 95 */ 96 public static enum Type { 97 NONE, 98 LISTEN, 99 TRACK_DEFAULT, 100 REQUEST, 101 BACKGROUND_REQUEST, 102 }; 103 104 /** 105 * The type of the request. This is only used by the system and is always NONE elsewhere. 106 * 107 * @hide 108 */ 109 public final Type type; 110 111 /** 112 * @hide 113 */ 114 public NetworkRequest(NetworkCapabilities nc, int legacyType, int rId, Type type) { 115 if (nc == null) { 116 throw new NullPointerException(); 117 } 118 requestId = rId; 119 networkCapabilities = nc; 120 this.legacyType = legacyType; 121 this.type = type; 122 } 123 124 /** 125 * @hide 126 */ 127 public NetworkRequest(NetworkRequest that) { 128 networkCapabilities = new NetworkCapabilities(that.networkCapabilities); 129 requestId = that.requestId; 130 this.legacyType = that.legacyType; 131 this.type = that.type; 132 } 133 134 /** 135 * Builder used to create {@link NetworkRequest} objects. Specify the Network features 136 * needed in terms of {@link NetworkCapabilities} features 137 */ 138 public static class Builder { 139 private final NetworkCapabilities mNetworkCapabilities; 140 141 /** 142 * Default constructor for Builder. 143 */ 144 public Builder() { 145 // By default, restrict this request to networks available to this app. 146 // Apps can rescind this restriction, but ConnectivityService will enforce 147 // it for apps that do not have the NETWORK_SETTINGS permission. 148 mNetworkCapabilities = new NetworkCapabilities(); 149 mNetworkCapabilities.setSingleUid(Process.myUid()); 150 } 151 152 /** 153 * Build {@link NetworkRequest} give the current set of capabilities. 154 */ 155 public NetworkRequest build() { 156 // Make a copy of mNetworkCapabilities so we don't inadvertently remove NOT_RESTRICTED 157 // when later an unrestricted capability could be added to mNetworkCapabilities, in 158 // which case NOT_RESTRICTED should be returned to mNetworkCapabilities, which 159 // maybeMarkCapabilitiesRestricted() doesn't add back. 160 final NetworkCapabilities nc = new NetworkCapabilities(mNetworkCapabilities); 161 nc.maybeMarkCapabilitiesRestricted(); 162 return new NetworkRequest(nc, ConnectivityManager.TYPE_NONE, 163 ConnectivityManager.REQUEST_ID_UNSET, Type.NONE); 164 } 165 166 /** 167 * Add the given capability requirement to this builder. These represent 168 * the requested network's required capabilities. Note that when searching 169 * for a network to satisfy a request, all capabilities requested must be 170 * satisfied. 171 * 172 * @param capability The capability to add. 173 * @return The builder to facilitate chaining 174 * {@code builder.addCapability(...).addCapability();}. 175 */ 176 public Builder addCapability(@NetworkCapabilities.NetCapability int capability) { 177 mNetworkCapabilities.addCapability(capability); 178 return this; 179 } 180 181 /** 182 * Removes (if found) the given capability from this builder instance. 183 * 184 * @param capability The capability to remove. 185 * @return The builder to facilitate chaining. 186 */ 187 public Builder removeCapability(@NetworkCapabilities.NetCapability int capability) { 188 mNetworkCapabilities.removeCapability(capability); 189 return this; 190 } 191 192 /** 193 * Set the {@code NetworkCapabilities} for this builder instance, 194 * overriding any capabilities that had been previously set. 195 * 196 * @param nc The superseding {@code NetworkCapabilities} instance. 197 * @return The builder to facilitate chaining. 198 * @hide 199 */ 200 public Builder setCapabilities(NetworkCapabilities nc) { 201 mNetworkCapabilities.clearAll(); 202 mNetworkCapabilities.combineCapabilities(nc); 203 return this; 204 } 205 206 /** 207 * Set the watched UIDs for this request. This will be reset and wiped out unless 208 * the calling app holds the CHANGE_NETWORK_STATE permission. 209 * 210 * @param uids The watched UIDs as a set of UidRanges, or null for everything. 211 * @return The builder to facilitate chaining. 212 * @hide 213 */ 214 public Builder setUids(Set<UidRange> uids) { 215 mNetworkCapabilities.setUids(uids); 216 return this; 217 } 218 219 /** 220 * Add a capability that must not exist in the requested network. 221 * <p> 222 * If the capability was previously added to the list of required capabilities (for 223 * example, it was there by default or added using {@link #addCapability(int)} method), then 224 * it will be removed from the list of required capabilities as well. 225 * 226 * @see #addCapability(int) 227 * 228 * @param capability The capability to add to unwanted capability list. 229 * @return The builder to facilitate chaining. 230 * 231 * @hide 232 */ 233 public Builder addUnwantedCapability(@NetworkCapabilities.NetCapability int capability) { 234 mNetworkCapabilities.addUnwantedCapability(capability); 235 return this; 236 } 237 238 /** 239 * Completely clears all the {@code NetworkCapabilities} from this builder instance, 240 * removing even the capabilities that are set by default when the object is constructed. 241 * 242 * @return The builder to facilitate chaining. 243 * @hide 244 */ 245 public Builder clearCapabilities() { 246 mNetworkCapabilities.clearAll(); 247 return this; 248 } 249 250 /** 251 * Adds the given transport requirement to this builder. These represent 252 * the set of allowed transports for the request. Only networks using one 253 * of these transports will satisfy the request. If no particular transports 254 * are required, none should be specified here. 255 * 256 * @param transportType The transport type to add. 257 * @return The builder to facilitate chaining. 258 */ 259 public Builder addTransportType(@NetworkCapabilities.Transport int transportType) { 260 mNetworkCapabilities.addTransportType(transportType); 261 return this; 262 } 263 264 /** 265 * Removes (if found) the given transport from this builder instance. 266 * 267 * @param transportType The transport type to remove. 268 * @return The builder to facilitate chaining. 269 */ 270 public Builder removeTransportType(@NetworkCapabilities.Transport int transportType) { 271 mNetworkCapabilities.removeTransportType(transportType); 272 return this; 273 } 274 275 /** 276 * @hide 277 */ 278 public Builder setLinkUpstreamBandwidthKbps(int upKbps) { 279 mNetworkCapabilities.setLinkUpstreamBandwidthKbps(upKbps); 280 return this; 281 } 282 /** 283 * @hide 284 */ 285 public Builder setLinkDownstreamBandwidthKbps(int downKbps) { 286 mNetworkCapabilities.setLinkDownstreamBandwidthKbps(downKbps); 287 return this; 288 } 289 290 /** 291 * Sets the optional bearer specific network specifier. 292 * This has no meaning if a single transport is also not specified, so calling 293 * this without a single transport set will generate an exception, as will 294 * subsequently adding or removing transports after this is set. 295 * </p> 296 * The interpretation of this {@code String} is bearer specific and bearers that use 297 * it should document their particulars. For example, Bluetooth may use some sort of 298 * device id while WiFi could used ssid and/or bssid. Cellular may use carrier spn. 299 * 300 * @param networkSpecifier An {@code String} of opaque format used to specify the bearer 301 * specific network specifier where the bearer has a choice of 302 * networks. 303 */ 304 public Builder setNetworkSpecifier(String networkSpecifier) { 305 /* 306 * A StringNetworkSpecifier does not accept null or empty ("") strings. When network 307 * specifiers were strings a null string and an empty string were considered equivalent. 308 * Hence no meaning is attached to a null or empty ("") string. 309 */ 310 return setNetworkSpecifier(TextUtils.isEmpty(networkSpecifier) ? null 311 : new StringNetworkSpecifier(networkSpecifier)); 312 } 313 314 /** 315 * Sets the optional bearer specific network specifier. 316 * This has no meaning if a single transport is also not specified, so calling 317 * this without a single transport set will generate an exception, as will 318 * subsequently adding or removing transports after this is set. 319 * </p> 320 * 321 * @param networkSpecifier A concrete, parcelable framework class that extends 322 * NetworkSpecifier. 323 */ 324 public Builder setNetworkSpecifier(NetworkSpecifier networkSpecifier) { 325 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(networkSpecifier); 326 mNetworkCapabilities.setNetworkSpecifier(networkSpecifier); 327 return this; 328 } 329 330 /** 331 * Sets the signal strength. This is a signed integer, with higher values indicating a 332 * stronger signal. The exact units are bearer-dependent. For example, Wi-Fi uses the same 333 * RSSI units reported by WifiManager. 334 * <p> 335 * Note that when used to register a network callback, this specifies the minimum acceptable 336 * signal strength. When received as the state of an existing network it specifies the 337 * current value. A value of {@code SIGNAL_STRENGTH_UNSPECIFIED} means no value when 338 * received and has no effect when requesting a callback. 339 * 340 * @param signalStrength the bearer-specific signal strength. 341 * @hide 342 */ 343 public Builder setSignalStrength(int signalStrength) { 344 mNetworkCapabilities.setSignalStrength(signalStrength); 345 return this; 346 } 347 } 348 349 // implement the Parcelable interface 350 public int describeContents() { 351 return 0; 352 } 353 public void writeToParcel(Parcel dest, int flags) { 354 networkCapabilities.writeToParcel(dest, flags); 355 dest.writeInt(legacyType); 356 dest.writeInt(requestId); 357 dest.writeString(type.name()); 358 } 359 public static final Creator<NetworkRequest> CREATOR = 360 new Creator<NetworkRequest>() { 361 public NetworkRequest createFromParcel(Parcel in) { 362 NetworkCapabilities nc = NetworkCapabilities.CREATOR.createFromParcel(in); 363 int legacyType = in.readInt(); 364 int requestId = in.readInt(); 365 Type type = Type.valueOf(in.readString()); // IllegalArgumentException if invalid. 366 NetworkRequest result = new NetworkRequest(nc, legacyType, requestId, type); 367 return result; 368 } 369 public NetworkRequest[] newArray(int size) { 370 return new NetworkRequest[size]; 371 } 372 }; 373 374 /** 375 * Returns true iff. this NetworkRequest is of type LISTEN. 376 * 377 * @hide 378 */ 379 public boolean isListen() { 380 return type == Type.LISTEN; 381 } 382 383 /** 384 * Returns true iff. the contained NetworkRequest is one that: 385 * 386 * - should be associated with at most one satisfying network 387 * at a time; 388 * 389 * - should cause a network to be kept up, but not necessarily in 390 * the foreground, if it is the best network which can satisfy the 391 * NetworkRequest. 392 * 393 * For full detail of how isRequest() is used for pairing Networks with 394 * NetworkRequests read rematchNetworkAndRequests(). 395 * 396 * @hide 397 */ 398 public boolean isRequest() { 399 return isForegroundRequest() || isBackgroundRequest(); 400 } 401 402 /** 403 * Returns true iff. the contained NetworkRequest is one that: 404 * 405 * - should be associated with at most one satisfying network 406 * at a time; 407 * 408 * - should cause a network to be kept up and in the foreground if 409 * it is the best network which can satisfy the NetworkRequest. 410 * 411 * For full detail of how isRequest() is used for pairing Networks with 412 * NetworkRequests read rematchNetworkAndRequests(). 413 * 414 * @hide 415 */ 416 public boolean isForegroundRequest() { 417 return type == Type.TRACK_DEFAULT || type == Type.REQUEST; 418 } 419 420 /** 421 * Returns true iff. this NetworkRequest is of type BACKGROUND_REQUEST. 422 * 423 * @hide 424 */ 425 public boolean isBackgroundRequest() { 426 return type == Type.BACKGROUND_REQUEST; 427 } 428 429 /** 430 * @see Builder#addCapability(int) 431 */ 432 public boolean hasCapability(@NetCapability int capability) { 433 return networkCapabilities.hasCapability(capability); 434 } 435 436 /** 437 * @see Builder#addUnwantedCapability(int) 438 * 439 * @hide 440 */ 441 public boolean hasUnwantedCapability(@NetCapability int capability) { 442 return networkCapabilities.hasUnwantedCapability(capability); 443 } 444 445 /** 446 * @see Builder#addTransportType(int) 447 */ 448 public boolean hasTransport(@Transport int transportType) { 449 return networkCapabilities.hasTransport(transportType); 450 } 451 452 public String toString() { 453 return "NetworkRequest [ " + type + " id=" + requestId + 454 (legacyType != ConnectivityManager.TYPE_NONE ? ", legacyType=" + legacyType : "") + 455 ", " + networkCapabilities.toString() + " ]"; 456 } 457 458 private int typeToProtoEnum(Type t) { 459 switch (t) { 460 case NONE: 461 return NetworkRequestProto.TYPE_NONE; 462 case LISTEN: 463 return NetworkRequestProto.TYPE_LISTEN; 464 case TRACK_DEFAULT: 465 return NetworkRequestProto.TYPE_TRACK_DEFAULT; 466 case REQUEST: 467 return NetworkRequestProto.TYPE_REQUEST; 468 case BACKGROUND_REQUEST: 469 return NetworkRequestProto.TYPE_BACKGROUND_REQUEST; 470 default: 471 return NetworkRequestProto.TYPE_UNKNOWN; 472 } 473 } 474 475 /** @hide */ 476 public void writeToProto(ProtoOutputStream proto, long fieldId) { 477 final long token = proto.start(fieldId); 478 479 proto.write(NetworkRequestProto.TYPE, typeToProtoEnum(type)); 480 proto.write(NetworkRequestProto.REQUEST_ID, requestId); 481 proto.write(NetworkRequestProto.LEGACY_TYPE, legacyType); 482 networkCapabilities.writeToProto(proto, NetworkRequestProto.NETWORK_CAPABILITIES); 483 484 proto.end(token); 485 } 486 487 public boolean equals(Object obj) { 488 if (obj instanceof NetworkRequest == false) return false; 489 NetworkRequest that = (NetworkRequest)obj; 490 return (that.legacyType == this.legacyType && 491 that.requestId == this.requestId && 492 that.type == this.type && 493 Objects.equals(that.networkCapabilities, this.networkCapabilities)); 494 } 495 496 public int hashCode() { 497 return Objects.hash(requestId, legacyType, networkCapabilities, type); 498 } 499} 500