1 /* 2 * Copyright (C) 2008 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 package android.net; 17 18 import static android.annotation.SystemApi.Client.MODULE_LIBRARIES; 19 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1; 20 import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST; 21 import static android.net.NetworkRequest.Type.LISTEN; 22 import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST; 23 import static android.net.NetworkRequest.Type.REQUEST; 24 import static android.net.NetworkRequest.Type.TRACK_DEFAULT; 25 import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT; 26 import static android.net.QosCallback.QosCallbackRegistrationException; 27 28 import android.annotation.CallbackExecutor; 29 import android.annotation.IntDef; 30 import android.annotation.NonNull; 31 import android.annotation.Nullable; 32 import android.annotation.RequiresPermission; 33 import android.annotation.SdkConstant; 34 import android.annotation.SdkConstant.SdkConstantType; 35 import android.annotation.SuppressLint; 36 import android.annotation.SystemApi; 37 import android.annotation.SystemService; 38 import android.app.PendingIntent; 39 import android.app.admin.DevicePolicyManager; 40 import android.compat.annotation.UnsupportedAppUsage; 41 import android.content.ComponentName; 42 import android.content.Context; 43 import android.content.Intent; 44 import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod; 45 import android.net.IpSecManager.UdpEncapsulationSocket; 46 import android.net.SocketKeepalive.Callback; 47 import android.net.TetheringManager.StartTetheringCallback; 48 import android.net.TetheringManager.TetheringEventCallback; 49 import android.net.TetheringManager.TetheringRequest; 50 import android.os.Binder; 51 import android.os.Build; 52 import android.os.Build.VERSION_CODES; 53 import android.os.Bundle; 54 import android.os.Handler; 55 import android.os.IBinder; 56 import android.os.Looper; 57 import android.os.Message; 58 import android.os.Messenger; 59 import android.os.ParcelFileDescriptor; 60 import android.os.PersistableBundle; 61 import android.os.Process; 62 import android.os.RemoteException; 63 import android.os.ResultReceiver; 64 import android.os.ServiceSpecificException; 65 import android.os.UserHandle; 66 import android.provider.Settings; 67 import android.telephony.SubscriptionManager; 68 import android.telephony.TelephonyManager; 69 import android.util.ArrayMap; 70 import android.util.Log; 71 import android.util.Range; 72 import android.util.SparseIntArray; 73 74 import com.android.internal.annotations.GuardedBy; 75 76 import libcore.net.event.NetworkEventDispatcher; 77 78 import java.io.IOException; 79 import java.io.UncheckedIOException; 80 import java.lang.annotation.Retention; 81 import java.lang.annotation.RetentionPolicy; 82 import java.net.DatagramSocket; 83 import java.net.InetAddress; 84 import java.net.InetSocketAddress; 85 import java.net.Socket; 86 import java.util.ArrayList; 87 import java.util.Collection; 88 import java.util.HashMap; 89 import java.util.List; 90 import java.util.Map; 91 import java.util.Objects; 92 import java.util.concurrent.Executor; 93 import java.util.concurrent.ExecutorService; 94 import java.util.concurrent.Executors; 95 import java.util.concurrent.RejectedExecutionException; 96 97 /** 98 * Class that answers queries about the state of network connectivity. It also 99 * notifies applications when network connectivity changes. 100 * <p> 101 * The primary responsibilities of this class are to: 102 * <ol> 103 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li> 104 * <li>Send broadcast intents when network connectivity changes</li> 105 * <li>Attempt to "fail over" to another network when connectivity to a network 106 * is lost</li> 107 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained 108 * state of the available networks</li> 109 * <li>Provide an API that allows applications to request and select networks for their data 110 * traffic</li> 111 * </ol> 112 */ 113 @SystemService(Context.CONNECTIVITY_SERVICE) 114 public class ConnectivityManager { 115 private static final String TAG = "ConnectivityManager"; 116 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); 117 118 /** 119 * A change in network connectivity has occurred. A default connection has either 120 * been established or lost. The NetworkInfo for the affected network is 121 * sent as an extra; it should be consulted to see what kind of 122 * connectivity event occurred. 123 * <p/> 124 * Apps targeting Android 7.0 (API level 24) and higher do not receive this 125 * broadcast if they declare the broadcast receiver in their manifest. Apps 126 * will still receive broadcasts if they register their 127 * {@link android.content.BroadcastReceiver} with 128 * {@link android.content.Context#registerReceiver Context.registerReceiver()} 129 * and that context is still valid. 130 * <p/> 131 * If this is a connection that was the result of failing over from a 132 * disconnected network, then the FAILOVER_CONNECTION boolean extra is 133 * set to true. 134 * <p/> 135 * For a loss of connectivity, if the connectivity manager is attempting 136 * to connect (or has already connected) to another network, the 137 * NetworkInfo for the new network is also passed as an extra. This lets 138 * any receivers of the broadcast know that they should not necessarily 139 * tell the user that no data traffic will be possible. Instead, the 140 * receiver should expect another broadcast soon, indicating either that 141 * the failover attempt succeeded (and so there is still overall data 142 * connectivity), or that the failover attempt failed, meaning that all 143 * connectivity has been lost. 144 * <p/> 145 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY 146 * is set to {@code true} if there are no connected networks at all. 147 * <p /> 148 * Note that this broadcast is deprecated and generally tries to implement backwards 149 * compatibility with older versions of Android. As such, it may not reflect new 150 * capabilities of the system, like multiple networks being connected at the same 151 * time, the details of newer technology, or changes in tethering state. 152 * 153 * @deprecated apps should use the more versatile {@link #requestNetwork}, 154 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback} 155 * functions instead for faster and more detailed updates about the network 156 * changes they care about. 157 */ 158 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 159 @Deprecated 160 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; 161 162 /** 163 * The device has connected to a network that has presented a captive 164 * portal, which is blocking Internet connectivity. The user was presented 165 * with a notification that network sign in is required, 166 * and the user invoked the notification's action indicating they 167 * desire to sign in to the network. Apps handling this activity should 168 * facilitate signing in to the network. This action includes a 169 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents 170 * the network presenting the captive portal; all communication with the 171 * captive portal must be done using this {@code Network} object. 172 * <p/> 173 * This activity includes a {@link CaptivePortal} extra named 174 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different 175 * outcomes of the captive portal sign in to the system: 176 * <ul> 177 * <li> When the app handling this action believes the user has signed in to 178 * the network and the captive portal has been dismissed, the app should 179 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can 180 * reevaluate the network. If reevaluation finds the network no longer 181 * subject to a captive portal, the network may become the default active 182 * data network.</li> 183 * <li> When the app handling this action believes the user explicitly wants 184 * to ignore the captive portal and the network, the app should call 185 * {@link CaptivePortal#ignoreNetwork}. </li> 186 * </ul> 187 */ 188 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 189 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL"; 190 191 /** 192 * The lookup key for a {@link NetworkInfo} object. Retrieve with 193 * {@link android.content.Intent#getParcelableExtra(String)}. 194 * 195 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties 196 * can't accurately represent modern network characteristics. 197 * Please obtain information about networks from the {@link NetworkCapabilities} 198 * or {@link LinkProperties} objects instead. 199 */ 200 @Deprecated 201 public static final String EXTRA_NETWORK_INFO = "networkInfo"; 202 203 /** 204 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast. 205 * 206 * @see android.content.Intent#getIntExtra(String, int) 207 * @deprecated The network type is not rich enough to represent the characteristics 208 * of modern networks. Please use {@link NetworkCapabilities} instead, 209 * in particular the transports. 210 */ 211 @Deprecated 212 public static final String EXTRA_NETWORK_TYPE = "networkType"; 213 214 /** 215 * The lookup key for a boolean that indicates whether a connect event 216 * is for a network to which the connectivity manager was failing over 217 * following a disconnect on another network. 218 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}. 219 * 220 * @deprecated See {@link NetworkInfo}. 221 */ 222 @Deprecated 223 public static final String EXTRA_IS_FAILOVER = "isFailover"; 224 /** 225 * The lookup key for a {@link NetworkInfo} object. This is supplied when 226 * there is another network that it may be possible to connect to. Retrieve with 227 * {@link android.content.Intent#getParcelableExtra(String)}. 228 * 229 * @deprecated See {@link NetworkInfo}. 230 */ 231 @Deprecated 232 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork"; 233 /** 234 * The lookup key for a boolean that indicates whether there is a 235 * complete lack of connectivity, i.e., no network is available. 236 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}. 237 */ 238 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity"; 239 /** 240 * The lookup key for a string that indicates why an attempt to connect 241 * to a network failed. The string has no particular structure. It is 242 * intended to be used in notifications presented to users. Retrieve 243 * it with {@link android.content.Intent#getStringExtra(String)}. 244 */ 245 public static final String EXTRA_REASON = "reason"; 246 /** 247 * The lookup key for a string that provides optionally supplied 248 * extra information about the network state. The information 249 * may be passed up from the lower networking layers, and its 250 * meaning may be specific to a particular network type. Retrieve 251 * it with {@link android.content.Intent#getStringExtra(String)}. 252 * 253 * @deprecated See {@link NetworkInfo#getExtraInfo()}. 254 */ 255 @Deprecated 256 public static final String EXTRA_EXTRA_INFO = "extraInfo"; 257 /** 258 * The lookup key for an int that provides information about 259 * our connection to the internet at large. 0 indicates no connection, 260 * 100 indicates a great connection. Retrieve it with 261 * {@link android.content.Intent#getIntExtra(String, int)}. 262 * {@hide} 263 */ 264 public static final String EXTRA_INET_CONDITION = "inetCondition"; 265 /** 266 * The lookup key for a {@link CaptivePortal} object included with the 267 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal} 268 * object can be used to either indicate to the system that the captive 269 * portal has been dismissed or that the user does not want to pursue 270 * signing in to captive portal. Retrieve it with 271 * {@link android.content.Intent#getParcelableExtra(String)}. 272 */ 273 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL"; 274 275 /** 276 * Key for passing a URL to the captive portal login activity. 277 */ 278 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL"; 279 280 /** 281 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive 282 * portal login activity. 283 * {@hide} 284 */ 285 @SystemApi 286 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC = 287 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC"; 288 289 /** 290 * Key for passing a user agent string to the captive portal login activity. 291 * {@hide} 292 */ 293 @SystemApi 294 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT = 295 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT"; 296 297 /** 298 * Broadcast action to indicate the change of data activity status 299 * (idle or active) on a network in a recent period. 300 * The network becomes active when data transmission is started, or 301 * idle if there is no data transmission for a period of time. 302 * {@hide} 303 */ 304 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 305 public static final String ACTION_DATA_ACTIVITY_CHANGE = 306 "android.net.conn.DATA_ACTIVITY_CHANGE"; 307 /** 308 * The lookup key for an enum that indicates the network device type on which this data activity 309 * change happens. 310 * {@hide} 311 */ 312 public static final String EXTRA_DEVICE_TYPE = "deviceType"; 313 /** 314 * The lookup key for a boolean that indicates the device is active or not. {@code true} means 315 * it is actively sending or receiving data and {@code false} means it is idle. 316 * {@hide} 317 */ 318 public static final String EXTRA_IS_ACTIVE = "isActive"; 319 /** 320 * The lookup key for a long that contains the timestamp (nanos) of the radio state change. 321 * {@hide} 322 */ 323 public static final String EXTRA_REALTIME_NS = "tsNanos"; 324 325 /** 326 * Broadcast Action: The setting for background data usage has changed 327 * values. Use {@link #getBackgroundDataSetting()} to get the current value. 328 * <p> 329 * If an application uses the network in the background, it should listen 330 * for this broadcast and stop using the background data if the value is 331 * {@code false}. 332 * <p> 333 * 334 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability 335 * of background data depends on several combined factors, and 336 * this broadcast is no longer sent. Instead, when background 337 * data is unavailable, {@link #getActiveNetworkInfo()} will now 338 * appear disconnected. During first boot after a platform 339 * upgrade, this broadcast will be sent once if 340 * {@link #getBackgroundDataSetting()} was {@code false} before 341 * the upgrade. 342 */ 343 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 344 @Deprecated 345 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED = 346 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED"; 347 348 /** 349 * Broadcast Action: The network connection may not be good 350 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and 351 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify 352 * the network and it's condition. 353 * @hide 354 */ 355 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 356 @UnsupportedAppUsage 357 public static final String INET_CONDITION_ACTION = 358 "android.net.conn.INET_CONDITION_ACTION"; 359 360 /** 361 * Broadcast Action: A tetherable connection has come or gone. 362 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER}, 363 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY}, 364 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and 365 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate 366 * the current state of tethering. Each include a list of 367 * interface names in that state (may be empty). 368 * @hide 369 */ 370 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 371 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 372 public static final String ACTION_TETHER_STATE_CHANGED = 373 TetheringManager.ACTION_TETHER_STATE_CHANGED; 374 375 /** 376 * @hide 377 * gives a String[] listing all the interfaces configured for 378 * tethering and currently available for tethering. 379 */ 380 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 381 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER; 382 383 /** 384 * @hide 385 * gives a String[] listing all the interfaces currently in local-only 386 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding) 387 */ 388 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY; 389 390 /** 391 * @hide 392 * gives a String[] listing all the interfaces currently tethered 393 * (ie, has DHCPv4 support and packets potentially forwarded/NATed) 394 */ 395 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 396 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER; 397 398 /** 399 * @hide 400 * gives a String[] listing all the interfaces we tried to tether and 401 * failed. Use {@link #getLastTetherError} to find the error code 402 * for any interfaces listed here. 403 */ 404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 405 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER; 406 407 /** 408 * Broadcast Action: The captive portal tracker has finished its test. 409 * Sent only while running Setup Wizard, in lieu of showing a user 410 * notification. 411 * @hide 412 */ 413 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 414 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED = 415 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED"; 416 /** 417 * The lookup key for a boolean that indicates whether a captive portal was detected. 418 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}. 419 * @hide 420 */ 421 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal"; 422 423 /** 424 * Action used to display a dialog that asks the user whether to connect to a network that is 425 * not validated. This intent is used to start the dialog in settings via startActivity. 426 * 427 * This action includes a {@link Network} typed extra which is called 428 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated. 429 * 430 * @hide 431 */ 432 @SystemApi(client = MODULE_LIBRARIES) 433 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED"; 434 435 /** 436 * Action used to display a dialog that asks the user whether to avoid a network that is no 437 * longer validated. This intent is used to start the dialog in settings via startActivity. 438 * 439 * This action includes a {@link Network} typed extra which is called 440 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer 441 * validated. 442 * 443 * @hide 444 */ 445 @SystemApi(client = MODULE_LIBRARIES) 446 public static final String ACTION_PROMPT_LOST_VALIDATION = 447 "android.net.action.PROMPT_LOST_VALIDATION"; 448 449 /** 450 * Action used to display a dialog that asks the user whether to stay connected to a network 451 * that has not validated. This intent is used to start the dialog in settings via 452 * startActivity. 453 * 454 * This action includes a {@link Network} typed extra which is called 455 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial 456 * connectivity. 457 * 458 * @hide 459 */ 460 @SystemApi(client = MODULE_LIBRARIES) 461 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY = 462 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY"; 463 464 /** 465 * Clear DNS Cache Action: This is broadcast when networks have changed and old 466 * DNS entries should be cleared. 467 * @hide 468 */ 469 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 470 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 471 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE"; 472 473 /** 474 * Invalid tethering type. 475 * @see #startTethering(int, boolean, OnStartTetheringCallback) 476 * @hide 477 */ 478 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID; 479 480 /** 481 * Wifi tethering type. 482 * @see #startTethering(int, boolean, OnStartTetheringCallback) 483 * @hide 484 */ 485 @SystemApi 486 public static final int TETHERING_WIFI = 0; 487 488 /** 489 * USB tethering type. 490 * @see #startTethering(int, boolean, OnStartTetheringCallback) 491 * @hide 492 */ 493 @SystemApi 494 public static final int TETHERING_USB = 1; 495 496 /** 497 * Bluetooth tethering type. 498 * @see #startTethering(int, boolean, OnStartTetheringCallback) 499 * @hide 500 */ 501 @SystemApi 502 public static final int TETHERING_BLUETOOTH = 2; 503 504 /** 505 * Wifi P2p tethering type. 506 * Wifi P2p tethering is set through events automatically, and don't 507 * need to start from #startTethering(int, boolean, OnStartTetheringCallback). 508 * @hide 509 */ 510 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P; 511 512 /** 513 * Extra used for communicating with the TetherService. Includes the type of tethering to 514 * enable if any. 515 * @hide 516 */ 517 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE; 518 519 /** 520 * Extra used for communicating with the TetherService. Includes the type of tethering for 521 * which to cancel provisioning. 522 * @hide 523 */ 524 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE; 525 526 /** 527 * Extra used for communicating with the TetherService. True to schedule a recheck of tether 528 * provisioning. 529 * @hide 530 */ 531 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM; 532 533 /** 534 * Tells the TetherService to run a provision check now. 535 * @hide 536 */ 537 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION; 538 539 /** 540 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver} 541 * which will receive provisioning results. Can be left empty. 542 * @hide 543 */ 544 public static final String EXTRA_PROVISION_CALLBACK = 545 TetheringConstants.EXTRA_PROVISION_CALLBACK; 546 547 /** 548 * The absence of a connection type. 549 * @hide 550 */ 551 @SystemApi 552 public static final int TYPE_NONE = -1; 553 554 /** 555 * A Mobile data connection. Devices may support more than one. 556 * 557 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or 558 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an 559 * appropriate network. See {@link NetworkCapabilities} for supported transports. 560 */ 561 @Deprecated 562 public static final int TYPE_MOBILE = 0; 563 564 /** 565 * A WIFI data connection. Devices may support more than one. 566 * 567 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or 568 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an 569 * appropriate network. See {@link NetworkCapabilities} for supported transports. 570 */ 571 @Deprecated 572 public static final int TYPE_WIFI = 1; 573 574 /** 575 * An MMS-specific Mobile data connection. This network type may use the 576 * same network interface as {@link #TYPE_MOBILE} or it may use a different 577 * one. This is used by applications needing to talk to the carrier's 578 * Multimedia Messaging Service servers. 579 * 580 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or 581 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that 582 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability. 583 */ 584 @Deprecated 585 public static final int TYPE_MOBILE_MMS = 2; 586 587 /** 588 * A SUPL-specific Mobile data connection. This network type may use the 589 * same network interface as {@link #TYPE_MOBILE} or it may use a different 590 * one. This is used by applications needing to talk to the carrier's 591 * Secure User Plane Location servers for help locating the device. 592 * 593 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or 594 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that 595 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability. 596 */ 597 @Deprecated 598 public static final int TYPE_MOBILE_SUPL = 3; 599 600 /** 601 * A DUN-specific Mobile data connection. This network type may use the 602 * same network interface as {@link #TYPE_MOBILE} or it may use a different 603 * one. This is sometimes by the system when setting up an upstream connection 604 * for tethering so that the carrier is aware of DUN traffic. 605 * 606 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or 607 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that 608 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability. 609 */ 610 @Deprecated 611 public static final int TYPE_MOBILE_DUN = 4; 612 613 /** 614 * A High Priority Mobile data connection. This network type uses the 615 * same network interface as {@link #TYPE_MOBILE} but the routing setup 616 * is different. 617 * 618 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or 619 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an 620 * appropriate network. See {@link NetworkCapabilities} for supported transports. 621 */ 622 @Deprecated 623 public static final int TYPE_MOBILE_HIPRI = 5; 624 625 /** 626 * A WiMAX data connection. 627 * 628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or 629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an 630 * appropriate network. See {@link NetworkCapabilities} for supported transports. 631 */ 632 @Deprecated 633 public static final int TYPE_WIMAX = 6; 634 635 /** 636 * A Bluetooth data connection. 637 * 638 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or 639 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an 640 * appropriate network. See {@link NetworkCapabilities} for supported transports. 641 */ 642 @Deprecated 643 public static final int TYPE_BLUETOOTH = 7; 644 645 /** 646 * Fake data connection. This should not be used on shipping devices. 647 * @deprecated This is not used any more. 648 */ 649 @Deprecated 650 public static final int TYPE_DUMMY = 8; 651 652 /** 653 * An Ethernet data connection. 654 * 655 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or 656 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an 657 * appropriate network. See {@link NetworkCapabilities} for supported transports. 658 */ 659 @Deprecated 660 public static final int TYPE_ETHERNET = 9; 661 662 /** 663 * Over the air Administration. 664 * @deprecated Use {@link NetworkCapabilities} instead. 665 * {@hide} 666 */ 667 @Deprecated 668 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562) 669 public static final int TYPE_MOBILE_FOTA = 10; 670 671 /** 672 * IP Multimedia Subsystem. 673 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead. 674 * {@hide} 675 */ 676 @Deprecated 677 @UnsupportedAppUsage 678 public static final int TYPE_MOBILE_IMS = 11; 679 680 /** 681 * Carrier Branded Services. 682 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead. 683 * {@hide} 684 */ 685 @Deprecated 686 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562) 687 public static final int TYPE_MOBILE_CBS = 12; 688 689 /** 690 * A Wi-Fi p2p connection. Only requesting processes will have access to 691 * the peers connected. 692 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead. 693 * {@hide} 694 */ 695 @Deprecated 696 @SystemApi 697 public static final int TYPE_WIFI_P2P = 13; 698 699 /** 700 * The network to use for initially attaching to the network 701 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead. 702 * {@hide} 703 */ 704 @Deprecated 705 @UnsupportedAppUsage 706 public static final int TYPE_MOBILE_IA = 14; 707 708 /** 709 * Emergency PDN connection for emergency services. This 710 * may include IMS and MMS in emergency situations. 711 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead. 712 * {@hide} 713 */ 714 @Deprecated 715 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562) 716 public static final int TYPE_MOBILE_EMERGENCY = 15; 717 718 /** 719 * The network that uses proxy to achieve connectivity. 720 * @deprecated Use {@link NetworkCapabilities} instead. 721 * {@hide} 722 */ 723 @Deprecated 724 @SystemApi 725 public static final int TYPE_PROXY = 16; 726 727 /** 728 * A virtual network using one or more native bearers. 729 * It may or may not be providing security services. 730 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead. 731 */ 732 @Deprecated 733 public static final int TYPE_VPN = 17; 734 735 /** 736 * A network that is exclusively meant to be used for testing 737 * 738 * @deprecated Use {@link NetworkCapabilities} instead. 739 * @hide 740 */ 741 @Deprecated 742 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused. 743 744 /** 745 * @deprecated Use {@link NetworkCapabilities} instead. 746 * @hide 747 */ 748 @Deprecated 749 @Retention(RetentionPolicy.SOURCE) 750 @IntDef(prefix = { "TYPE_" }, value = { 751 TYPE_NONE, 752 TYPE_MOBILE, 753 TYPE_WIFI, 754 TYPE_MOBILE_MMS, 755 TYPE_MOBILE_SUPL, 756 TYPE_MOBILE_DUN, 757 TYPE_MOBILE_HIPRI, 758 TYPE_WIMAX, 759 TYPE_BLUETOOTH, 760 TYPE_DUMMY, 761 TYPE_ETHERNET, 762 TYPE_MOBILE_FOTA, 763 TYPE_MOBILE_IMS, 764 TYPE_MOBILE_CBS, 765 TYPE_WIFI_P2P, 766 TYPE_MOBILE_IA, 767 TYPE_MOBILE_EMERGENCY, 768 TYPE_PROXY, 769 TYPE_VPN, 770 TYPE_TEST 771 }) 772 public @interface LegacyNetworkType {} 773 774 // Deprecated constants for return values of startUsingNetworkFeature. They used to live 775 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible. 776 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0; 777 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1; 778 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3; 779 780 /** {@hide} */ 781 public static final int MAX_RADIO_TYPE = TYPE_TEST; 782 783 /** {@hide} */ 784 public static final int MAX_NETWORK_TYPE = TYPE_TEST; 785 786 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE; 787 788 /** 789 * If you want to set the default network preference,you can directly 790 * change the networkAttributes array in framework's config.xml. 791 * 792 * @deprecated Since we support so many more networks now, the single 793 * network default network preference can't really express 794 * the hierarchy. Instead, the default is defined by the 795 * networkAttributes in config.xml. You can determine 796 * the current value by calling {@link #getNetworkPreference()} 797 * from an App. 798 */ 799 @Deprecated 800 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI; 801 802 /** 803 * @hide 804 */ 805 public static final int REQUEST_ID_UNSET = 0; 806 807 /** 808 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered. 809 * This allows to distinguish when unregistering NetworkCallbacks those that were never 810 * registered from those that were already unregistered. 811 * @hide 812 */ 813 private static final NetworkRequest ALREADY_UNREGISTERED = 814 new NetworkRequest.Builder().clearCapabilities().build(); 815 816 /** 817 * A NetID indicating no Network is selected. 818 * Keep in sync with bionic/libc/dns/include/resolv_netid.h 819 * @hide 820 */ 821 public static final int NETID_UNSET = 0; 822 823 /** 824 * Flag to indicate that an app is not subject to any restrictions that could result in its 825 * network access blocked. 826 * 827 * @hide 828 */ 829 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 830 public static final int BLOCKED_REASON_NONE = 0; 831 832 /** 833 * Flag to indicate that an app is subject to Battery saver restrictions that would 834 * result in its network access being blocked. 835 * 836 * @hide 837 */ 838 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 839 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0; 840 841 /** 842 * Flag to indicate that an app is subject to Doze restrictions that would 843 * result in its network access being blocked. 844 * 845 * @hide 846 */ 847 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 848 public static final int BLOCKED_REASON_DOZE = 1 << 1; 849 850 /** 851 * Flag to indicate that an app is subject to App Standby restrictions that would 852 * result in its network access being blocked. 853 * 854 * @hide 855 */ 856 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 857 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2; 858 859 /** 860 * Flag to indicate that an app is subject to Restricted mode restrictions that would 861 * result in its network access being blocked. 862 * 863 * @hide 864 */ 865 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 866 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3; 867 868 /** 869 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN 870 * is not currently connected. 871 * 872 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean) 873 * 874 * @hide 875 */ 876 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 877 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4; 878 879 /** 880 * Flag to indicate that an app is subject to Low Power Standby restrictions that would 881 * result in its network access being blocked. 882 * 883 * @hide 884 */ 885 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 886 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5; 887 888 /** 889 * Flag to indicate that an app is subject to Data saver restrictions that would 890 * result in its metered network access being blocked. 891 * 892 * @hide 893 */ 894 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 895 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16; 896 897 /** 898 * Flag to indicate that an app is subject to user restrictions that would 899 * result in its metered network access being blocked. 900 * 901 * @hide 902 */ 903 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 904 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17; 905 906 /** 907 * Flag to indicate that an app is subject to Device admin restrictions that would 908 * result in its metered network access being blocked. 909 * 910 * @hide 911 */ 912 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 913 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18; 914 915 /** 916 * @hide 917 */ 918 @Retention(RetentionPolicy.SOURCE) 919 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = { 920 BLOCKED_REASON_NONE, 921 BLOCKED_REASON_BATTERY_SAVER, 922 BLOCKED_REASON_DOZE, 923 BLOCKED_REASON_APP_STANDBY, 924 BLOCKED_REASON_RESTRICTED_MODE, 925 BLOCKED_REASON_LOCKDOWN_VPN, 926 BLOCKED_REASON_LOW_POWER_STANDBY, 927 BLOCKED_METERED_REASON_DATA_SAVER, 928 BLOCKED_METERED_REASON_USER_RESTRICTED, 929 BLOCKED_METERED_REASON_ADMIN_DISABLED, 930 }) 931 public @interface BlockedReason {} 932 933 /** 934 * Set of blocked reasons that are only applicable on metered networks. 935 * 936 * @hide 937 */ 938 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 939 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000; 940 941 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562) 942 private final IConnectivityManager mService; 943 944 // LINT.IfChange(firewall_chain) 945 /** 946 * Firewall chain for device idle (doze mode). 947 * Allowlist of apps that have network access in device idle. 948 * @hide 949 */ 950 @SystemApi(client = MODULE_LIBRARIES) 951 public static final int FIREWALL_CHAIN_DOZABLE = 1; 952 953 /** 954 * Firewall chain used for app standby. 955 * Denylist of apps that do not have network access. 956 * @hide 957 */ 958 @SystemApi(client = MODULE_LIBRARIES) 959 public static final int FIREWALL_CHAIN_STANDBY = 2; 960 961 /** 962 * Firewall chain used for battery saver. 963 * Allowlist of apps that have network access when battery saver is on. 964 * @hide 965 */ 966 @SystemApi(client = MODULE_LIBRARIES) 967 public static final int FIREWALL_CHAIN_POWERSAVE = 3; 968 969 /** 970 * Firewall chain used for restricted networking mode. 971 * Allowlist of apps that have access in restricted networking mode. 972 * @hide 973 */ 974 @SystemApi(client = MODULE_LIBRARIES) 975 public static final int FIREWALL_CHAIN_RESTRICTED = 4; 976 977 /** 978 * Firewall chain used for low power standby. 979 * Allowlist of apps that have access in low power standby. 980 * @hide 981 */ 982 @SystemApi(client = MODULE_LIBRARIES) 983 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5; 984 985 /** 986 * Firewall chain used for OEM-specific application restrictions. 987 * 988 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an 989 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped. 990 * 991 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is 992 * independent of the others. The chains can be enabled and disabled independently, and apps can 993 * be added and removed from each chain independently. 994 * 995 * @see #FIREWALL_CHAIN_OEM_DENY_2 996 * @see #FIREWALL_CHAIN_OEM_DENY_3 997 * @hide 998 */ 999 @SystemApi(client = MODULE_LIBRARIES) 1000 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7; 1001 1002 /** 1003 * Firewall chain used for OEM-specific application restrictions. 1004 * 1005 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an 1006 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped. 1007 * 1008 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is 1009 * independent of the others. The chains can be enabled and disabled independently, and apps can 1010 * be added and removed from each chain independently. 1011 * 1012 * @see #FIREWALL_CHAIN_OEM_DENY_1 1013 * @see #FIREWALL_CHAIN_OEM_DENY_3 1014 * @hide 1015 */ 1016 @SystemApi(client = MODULE_LIBRARIES) 1017 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8; 1018 1019 /** 1020 * Firewall chain used for OEM-specific application restrictions. 1021 * 1022 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an 1023 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped. 1024 * 1025 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is 1026 * independent of the others. The chains can be enabled and disabled independently, and apps can 1027 * be added and removed from each chain independently. 1028 * 1029 * @see #FIREWALL_CHAIN_OEM_DENY_1 1030 * @see #FIREWALL_CHAIN_OEM_DENY_2 1031 * @hide 1032 */ 1033 @SystemApi(client = MODULE_LIBRARIES) 1034 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9; 1035 1036 /** @hide */ 1037 @Retention(RetentionPolicy.SOURCE) 1038 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = { 1039 FIREWALL_CHAIN_DOZABLE, 1040 FIREWALL_CHAIN_STANDBY, 1041 FIREWALL_CHAIN_POWERSAVE, 1042 FIREWALL_CHAIN_RESTRICTED, 1043 FIREWALL_CHAIN_LOW_POWER_STANDBY, 1044 FIREWALL_CHAIN_OEM_DENY_1, 1045 FIREWALL_CHAIN_OEM_DENY_2, 1046 FIREWALL_CHAIN_OEM_DENY_3 1047 }) 1048 public @interface FirewallChain {} 1049 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h) 1050 1051 /** 1052 * A firewall rule which allows or drops packets depending on existing policy. 1053 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle 1054 * specific uid's packets in specific firewall chain. 1055 * @hide 1056 */ 1057 @SystemApi(client = MODULE_LIBRARIES) 1058 public static final int FIREWALL_RULE_DEFAULT = 0; 1059 1060 /** 1061 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to 1062 * allow specific uid's packets in specific firewall chain. 1063 * @hide 1064 */ 1065 @SystemApi(client = MODULE_LIBRARIES) 1066 public static final int FIREWALL_RULE_ALLOW = 1; 1067 1068 /** 1069 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to 1070 * drop specific uid's packets in specific firewall chain. 1071 * @hide 1072 */ 1073 @SystemApi(client = MODULE_LIBRARIES) 1074 public static final int FIREWALL_RULE_DENY = 2; 1075 1076 /** @hide */ 1077 @Retention(RetentionPolicy.SOURCE) 1078 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = { 1079 FIREWALL_RULE_DEFAULT, 1080 FIREWALL_RULE_ALLOW, 1081 FIREWALL_RULE_DENY 1082 }) 1083 public @interface FirewallRule {} 1084 1085 /** 1086 * A kludge to facilitate static access where a Context pointer isn't available, like in the 1087 * case of the static set/getProcessDefaultNetwork methods and from the Network class. 1088 * TODO: Remove this after deprecating the static methods in favor of non-static methods or 1089 * methods that take a Context argument. 1090 */ 1091 private static ConnectivityManager sInstance; 1092 1093 private final Context mContext; 1094 1095 @GuardedBy("mTetheringEventCallbacks") 1096 private TetheringManager mTetheringManager; 1097 getTetheringManager()1098 private TetheringManager getTetheringManager() { 1099 synchronized (mTetheringEventCallbacks) { 1100 if (mTetheringManager == null) { 1101 mTetheringManager = mContext.getSystemService(TetheringManager.class); 1102 } 1103 return mTetheringManager; 1104 } 1105 } 1106 1107 /** 1108 * Tests if a given integer represents a valid network type. 1109 * @param networkType the type to be tested 1110 * @return {@code true} if the type is valid, else {@code false} 1111 * @deprecated All APIs accepting a network type are deprecated. There should be no need to 1112 * validate a network type. 1113 */ 1114 @Deprecated isNetworkTypeValid(int networkType)1115 public static boolean isNetworkTypeValid(int networkType) { 1116 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE; 1117 } 1118 1119 /** 1120 * Returns a non-localized string representing a given network type. 1121 * ONLY used for debugging output. 1122 * @param type the type needing naming 1123 * @return a String for the given type, or a string version of the type ("87") 1124 * if no name is known. 1125 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead. 1126 * {@hide} 1127 */ 1128 @Deprecated 1129 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) getNetworkTypeName(int type)1130 public static String getNetworkTypeName(int type) { 1131 switch (type) { 1132 case TYPE_NONE: 1133 return "NONE"; 1134 case TYPE_MOBILE: 1135 return "MOBILE"; 1136 case TYPE_WIFI: 1137 return "WIFI"; 1138 case TYPE_MOBILE_MMS: 1139 return "MOBILE_MMS"; 1140 case TYPE_MOBILE_SUPL: 1141 return "MOBILE_SUPL"; 1142 case TYPE_MOBILE_DUN: 1143 return "MOBILE_DUN"; 1144 case TYPE_MOBILE_HIPRI: 1145 return "MOBILE_HIPRI"; 1146 case TYPE_WIMAX: 1147 return "WIMAX"; 1148 case TYPE_BLUETOOTH: 1149 return "BLUETOOTH"; 1150 case TYPE_DUMMY: 1151 return "DUMMY"; 1152 case TYPE_ETHERNET: 1153 return "ETHERNET"; 1154 case TYPE_MOBILE_FOTA: 1155 return "MOBILE_FOTA"; 1156 case TYPE_MOBILE_IMS: 1157 return "MOBILE_IMS"; 1158 case TYPE_MOBILE_CBS: 1159 return "MOBILE_CBS"; 1160 case TYPE_WIFI_P2P: 1161 return "WIFI_P2P"; 1162 case TYPE_MOBILE_IA: 1163 return "MOBILE_IA"; 1164 case TYPE_MOBILE_EMERGENCY: 1165 return "MOBILE_EMERGENCY"; 1166 case TYPE_PROXY: 1167 return "PROXY"; 1168 case TYPE_VPN: 1169 return "VPN"; 1170 case TYPE_TEST: 1171 return "TEST"; 1172 default: 1173 return Integer.toString(type); 1174 } 1175 } 1176 1177 /** 1178 * @hide 1179 */ 1180 @SystemApi(client = MODULE_LIBRARIES) systemReady()1181 public void systemReady() { 1182 try { 1183 mService.systemReady(); 1184 } catch (RemoteException e) { 1185 throw e.rethrowFromSystemServer(); 1186 } 1187 } 1188 1189 /** 1190 * Checks if a given type uses the cellular data connection. 1191 * This should be replaced in the future by a network property. 1192 * @param networkType the type to check 1193 * @return a boolean - {@code true} if uses cellular network, else {@code false} 1194 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead. 1195 * {@hide} 1196 */ 1197 @Deprecated 1198 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562) isNetworkTypeMobile(int networkType)1199 public static boolean isNetworkTypeMobile(int networkType) { 1200 switch (networkType) { 1201 case TYPE_MOBILE: 1202 case TYPE_MOBILE_MMS: 1203 case TYPE_MOBILE_SUPL: 1204 case TYPE_MOBILE_DUN: 1205 case TYPE_MOBILE_HIPRI: 1206 case TYPE_MOBILE_FOTA: 1207 case TYPE_MOBILE_IMS: 1208 case TYPE_MOBILE_CBS: 1209 case TYPE_MOBILE_IA: 1210 case TYPE_MOBILE_EMERGENCY: 1211 return true; 1212 default: 1213 return false; 1214 } 1215 } 1216 1217 /** 1218 * Checks if the given network type is backed by a Wi-Fi radio. 1219 * 1220 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead. 1221 * @hide 1222 */ 1223 @Deprecated isNetworkTypeWifi(int networkType)1224 public static boolean isNetworkTypeWifi(int networkType) { 1225 switch (networkType) { 1226 case TYPE_WIFI: 1227 case TYPE_WIFI_P2P: 1228 return true; 1229 default: 1230 return false; 1231 } 1232 } 1233 1234 /** 1235 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}. 1236 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)} 1237 * Specify that the traffic for this user should by follow the default rules: 1238 * applications in the profile designated by the UserHandle behave like any 1239 * other application and use the system default network as their default 1240 * network. Compare other PROFILE_NETWORK_PREFERENCE_* settings. 1241 * @hide 1242 */ 1243 @SystemApi(client = MODULE_LIBRARIES) 1244 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0; 1245 1246 /** 1247 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}. 1248 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)} 1249 * Specify that the traffic for this user should by default go on a network with 1250 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network 1251 * if no such network is available. 1252 * @hide 1253 */ 1254 @SystemApi(client = MODULE_LIBRARIES) 1255 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1; 1256 1257 /** 1258 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}. 1259 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)} 1260 * Specify that the traffic for this user should by default go on a network with 1261 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available 1262 * should not have a default network at all (that is, network accesses that 1263 * do not specify a network explicitly terminate with an error), even if there 1264 * is a system default network available to apps outside this preference. 1265 * The apps can still use a non-enterprise network if they request it explicitly 1266 * provided that specific network doesn't require any specific permission they 1267 * do not hold. 1268 * @hide 1269 */ 1270 @SystemApi(client = MODULE_LIBRARIES) 1271 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2; 1272 1273 /** 1274 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}. 1275 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)} 1276 * Specify that the traffic for this user should by default go on a network with 1277 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}. 1278 * If there is no such network, the apps will have no default 1279 * network at all, even if there are available non-enterprise networks on the 1280 * device (that is, network accesses that do not specify a network explicitly 1281 * terminate with an error). Additionally, the designated apps should be 1282 * blocked from using any non-enterprise network even if they specify it 1283 * explicitly, unless they hold specific privilege overriding this (see 1284 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS}). 1285 * @hide 1286 */ 1287 @SystemApi(client = MODULE_LIBRARIES) 1288 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING = 3; 1289 1290 /** @hide */ 1291 @Retention(RetentionPolicy.SOURCE) 1292 @IntDef(value = { 1293 PROFILE_NETWORK_PREFERENCE_DEFAULT, 1294 PROFILE_NETWORK_PREFERENCE_ENTERPRISE, 1295 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK 1296 }) 1297 public @interface ProfileNetworkPreferencePolicy { 1298 } 1299 1300 /** 1301 * Specifies the preferred network type. When the device has more 1302 * than one type available the preferred network type will be used. 1303 * 1304 * @param preference the network type to prefer over all others. It is 1305 * unspecified what happens to the old preferred network in the 1306 * overall ordering. 1307 * @deprecated Functionality has been removed as it no longer makes sense, 1308 * with many more than two networks - we'd need an array to express 1309 * preference. Instead we use dynamic network properties of 1310 * the networks to describe their precedence. 1311 */ 1312 @Deprecated setNetworkPreference(int preference)1313 public void setNetworkPreference(int preference) { 1314 } 1315 1316 /** 1317 * Retrieves the current preferred network type. 1318 * 1319 * @return an integer representing the preferred network type 1320 * 1321 * @deprecated Functionality has been removed as it no longer makes sense, 1322 * with many more than two networks - we'd need an array to express 1323 * preference. Instead we use dynamic network properties of 1324 * the networks to describe their precedence. 1325 */ 1326 @Deprecated 1327 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) getNetworkPreference()1328 public int getNetworkPreference() { 1329 return TYPE_NONE; 1330 } 1331 1332 /** 1333 * Returns details about the currently active default data network. When 1334 * connected, this network is the default route for outgoing connections. 1335 * You should always check {@link NetworkInfo#isConnected()} before initiating 1336 * network traffic. This may return {@code null} when there is no default 1337 * network. 1338 * Note that if the default network is a VPN, this method will return the 1339 * NetworkInfo for one of its underlying networks instead, or null if the 1340 * VPN agent did not specify any. Apps interested in learning about VPNs 1341 * should use {@link #getNetworkInfo(android.net.Network)} instead. 1342 * 1343 * @return a {@link NetworkInfo} object for the current default network 1344 * or {@code null} if no default network is currently active 1345 * @deprecated See {@link NetworkInfo}. 1346 */ 1347 @Deprecated 1348 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1349 @Nullable getActiveNetworkInfo()1350 public NetworkInfo getActiveNetworkInfo() { 1351 try { 1352 return mService.getActiveNetworkInfo(); 1353 } catch (RemoteException e) { 1354 throw e.rethrowFromSystemServer(); 1355 } 1356 } 1357 1358 /** 1359 * Returns a {@link Network} object corresponding to the currently active 1360 * default data network. In the event that the current active default data 1361 * network disconnects, the returned {@code Network} object will no longer 1362 * be usable. This will return {@code null} when there is no default 1363 * network, or when the default network is blocked. 1364 * 1365 * @return a {@link Network} object for the current default network or 1366 * {@code null} if no default network is currently active or if 1367 * the default network is blocked for the caller 1368 */ 1369 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1370 @Nullable getActiveNetwork()1371 public Network getActiveNetwork() { 1372 try { 1373 return mService.getActiveNetwork(); 1374 } catch (RemoteException e) { 1375 throw e.rethrowFromSystemServer(); 1376 } 1377 } 1378 1379 /** 1380 * Returns a {@link Network} object corresponding to the currently active 1381 * default data network for a specific UID. In the event that the default data 1382 * network disconnects, the returned {@code Network} object will no longer 1383 * be usable. This will return {@code null} when there is no default 1384 * network for the UID. 1385 * 1386 * @return a {@link Network} object for the current default network for the 1387 * given UID or {@code null} if no default network is currently active 1388 * 1389 * @hide 1390 */ 1391 @RequiresPermission(android.Manifest.permission.NETWORK_STACK) 1392 @Nullable getActiveNetworkForUid(int uid)1393 public Network getActiveNetworkForUid(int uid) { 1394 return getActiveNetworkForUid(uid, false); 1395 } 1396 1397 /** {@hide} */ getActiveNetworkForUid(int uid, boolean ignoreBlocked)1398 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) { 1399 try { 1400 return mService.getActiveNetworkForUid(uid, ignoreBlocked); 1401 } catch (RemoteException e) { 1402 throw e.rethrowFromSystemServer(); 1403 } 1404 } 1405 getUidRangeArray(@onNull Collection<Range<Integer>> ranges)1406 private static UidRange[] getUidRangeArray(@NonNull Collection<Range<Integer>> ranges) { 1407 Objects.requireNonNull(ranges); 1408 final UidRange[] rangesArray = new UidRange[ranges.size()]; 1409 int index = 0; 1410 for (Range<Integer> range : ranges) { 1411 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper()); 1412 } 1413 1414 return rangesArray; 1415 } 1416 1417 /** 1418 * Adds or removes a requirement for given UID ranges to use the VPN. 1419 * 1420 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not 1421 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs 1422 * otherwise have permission to bypass the VPN (e.g., because they have the 1423 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when 1424 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If 1425 * set to {@code false}, a previously-added restriction is removed. 1426 * <p> 1427 * Each of the UID ranges specified by this method is added and removed as is, and no processing 1428 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to 1429 * remove a previously-added range, the exact range must be removed as is. 1430 * <p> 1431 * The changes are applied asynchronously and may not have been applied by the time the method 1432 * returns. Apps will be notified about any changes that apply to them via 1433 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take 1434 * effect. 1435 * <p> 1436 * This method will block the specified UIDs from accessing non-VPN networks, but does not 1437 * affect what the UIDs get as their default network. 1438 * Compare {@link #setVpnDefaultForUids(String, Collection)}, which declares that the UIDs 1439 * should only have a VPN as their default network, but does not block them from accessing other 1440 * networks if they request them explicitly with the {@link Network} API. 1441 * <p> 1442 * This method should be called only by the VPN code. 1443 * 1444 * @param ranges the UID ranges to restrict 1445 * @param requireVpn whether the specified UID ranges must use a VPN 1446 * 1447 * @hide 1448 */ 1449 @RequiresPermission(anyOf = { 1450 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 1451 android.Manifest.permission.NETWORK_STACK, 1452 android.Manifest.permission.NETWORK_SETTINGS}) 1453 @SystemApi(client = MODULE_LIBRARIES) setRequireVpnForUids(boolean requireVpn, @NonNull Collection<Range<Integer>> ranges)1454 public void setRequireVpnForUids(boolean requireVpn, 1455 @NonNull Collection<Range<Integer>> ranges) { 1456 Objects.requireNonNull(ranges); 1457 // The Range class is not parcelable. Convert to UidRange, which is what is used internally. 1458 // This method is not necessarily expected to be used outside the system server, so 1459 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network 1460 // stack process, or by tests. 1461 final UidRange[] rangesArray = getUidRangeArray(ranges); 1462 try { 1463 mService.setRequireVpnForUids(requireVpn, rangesArray); 1464 } catch (RemoteException e) { 1465 throw e.rethrowFromSystemServer(); 1466 } 1467 } 1468 1469 /** 1470 * Inform the system that this VPN session should manage the passed UIDs. 1471 * 1472 * A VPN with the specified session ID may call this method to inform the system that the UIDs 1473 * in the specified range are subject to a VPN. 1474 * When this is called, the system will only choose a VPN for the default network of the UIDs in 1475 * the specified ranges. 1476 * 1477 * This method declares that the UIDs in the range will only have a VPN for their default 1478 * network, but does not block the UIDs from accessing other networks (permissions allowing) by 1479 * explicitly requesting it with the {@link Network} API. 1480 * Compare {@link #setRequireVpnForUids(boolean, Collection)}, which does not affect what 1481 * network the UIDs get as default, but will block them from accessing non-VPN networks. 1482 * 1483 * @param session The VPN session which manages the passed UIDs. 1484 * @param ranges The uid ranges which will treat VPN as their only default network. 1485 * 1486 * @hide 1487 */ 1488 @RequiresPermission(anyOf = { 1489 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 1490 android.Manifest.permission.NETWORK_STACK, 1491 android.Manifest.permission.NETWORK_SETTINGS}) 1492 @SystemApi(client = MODULE_LIBRARIES) setVpnDefaultForUids(@onNull String session, @NonNull Collection<Range<Integer>> ranges)1493 public void setVpnDefaultForUids(@NonNull String session, 1494 @NonNull Collection<Range<Integer>> ranges) { 1495 Objects.requireNonNull(ranges); 1496 final UidRange[] rangesArray = getUidRangeArray(ranges); 1497 try { 1498 mService.setVpnNetworkPreference(session, rangesArray); 1499 } catch (RemoteException e) { 1500 throw e.rethrowFromSystemServer(); 1501 } 1502 } 1503 1504 /** 1505 * Temporarily set automaticOnOff keeplaive TCP polling alarm timer to 1 second. 1506 * 1507 * TODO: Remove this when the TCP polling design is replaced with callback. 1508 * @param timeMs The time of expiry, with System.currentTimeMillis() base. The value should be 1509 * set no more than 5 minutes in the future. 1510 * @hide 1511 */ setTestLowTcpPollingTimerForKeepalive(long timeMs)1512 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) { 1513 try { 1514 mService.setTestLowTcpPollingTimerForKeepalive(timeMs); 1515 } catch (RemoteException e) { 1516 throw e.rethrowFromSystemServer(); 1517 } 1518 } 1519 1520 /** 1521 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by 1522 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12 1523 * but is still supported for backwards compatibility. 1524 * <p> 1525 * This type of VPN is assumed always to use the system default network, and must always declare 1526 * exactly one underlying network, which is the network that was the default when the VPN 1527 * connected. 1528 * <p> 1529 * Calling this method with {@code true} enables legacy behaviour, specifically: 1530 * <ul> 1531 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated 1532 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the 1533 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN 1534 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network 1535 * underlying the VPN.</li> 1536 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state 1537 * similarly replaced by the VPN network state.</li> 1538 * <li>Information on current network interfaces passed to NetworkStatsService will not 1539 * include any VPN interfaces.</li> 1540 * </ul> 1541 * 1542 * @param enabled whether legacy lockdown VPN is enabled or disabled 1543 * 1544 * @hide 1545 */ 1546 @RequiresPermission(anyOf = { 1547 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 1548 android.Manifest.permission.NETWORK_STACK, 1549 android.Manifest.permission.NETWORK_SETTINGS}) 1550 @SystemApi(client = MODULE_LIBRARIES) setLegacyLockdownVpnEnabled(boolean enabled)1551 public void setLegacyLockdownVpnEnabled(boolean enabled) { 1552 try { 1553 mService.setLegacyLockdownVpnEnabled(enabled); 1554 } catch (RemoteException e) { 1555 throw e.rethrowFromSystemServer(); 1556 } 1557 } 1558 1559 /** 1560 * Returns details about the currently active default data network for a given uid. 1561 * This is for privileged use only to avoid spying on other apps. 1562 * 1563 * @return a {@link NetworkInfo} object for the current default network 1564 * for the given uid or {@code null} if no default network is 1565 * available for the specified uid. 1566 * 1567 * {@hide} 1568 */ 1569 @RequiresPermission(android.Manifest.permission.NETWORK_STACK) 1570 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) getActiveNetworkInfoForUid(int uid)1571 public NetworkInfo getActiveNetworkInfoForUid(int uid) { 1572 return getActiveNetworkInfoForUid(uid, false); 1573 } 1574 1575 /** {@hide} */ getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked)1576 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) { 1577 try { 1578 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked); 1579 } catch (RemoteException e) { 1580 throw e.rethrowFromSystemServer(); 1581 } 1582 } 1583 1584 /** 1585 * Returns connection status information about a particular network type. 1586 * 1587 * @param networkType integer specifying which networkType in 1588 * which you're interested. 1589 * @return a {@link NetworkInfo} object for the requested 1590 * network type or {@code null} if the type is not 1591 * supported by the device. If {@code networkType} is 1592 * TYPE_VPN and a VPN is active for the calling app, 1593 * then this method will try to return one of the 1594 * underlying networks for the VPN or null if the 1595 * VPN agent didn't specify any. 1596 * 1597 * @deprecated This method does not support multiple connected networks 1598 * of the same type. Use {@link #getAllNetworks} and 1599 * {@link #getNetworkInfo(android.net.Network)} instead. 1600 */ 1601 @Deprecated 1602 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1603 @Nullable getNetworkInfo(int networkType)1604 public NetworkInfo getNetworkInfo(int networkType) { 1605 try { 1606 return mService.getNetworkInfo(networkType); 1607 } catch (RemoteException e) { 1608 throw e.rethrowFromSystemServer(); 1609 } 1610 } 1611 1612 /** 1613 * Returns connection status information about a particular Network. 1614 * 1615 * @param network {@link Network} specifying which network 1616 * in which you're interested. 1617 * @return a {@link NetworkInfo} object for the requested 1618 * network or {@code null} if the {@code Network} 1619 * is not valid. 1620 * @deprecated See {@link NetworkInfo}. 1621 */ 1622 @Deprecated 1623 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1624 @Nullable getNetworkInfo(@ullable Network network)1625 public NetworkInfo getNetworkInfo(@Nullable Network network) { 1626 return getNetworkInfoForUid(network, Process.myUid(), false); 1627 } 1628 1629 /** {@hide} */ getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked)1630 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) { 1631 try { 1632 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked); 1633 } catch (RemoteException e) { 1634 throw e.rethrowFromSystemServer(); 1635 } 1636 } 1637 1638 /** 1639 * Returns connection status information about all network types supported by the device. 1640 * 1641 * @return an array of {@link NetworkInfo} objects. Check each 1642 * {@link NetworkInfo#getType} for which type each applies. 1643 * 1644 * @deprecated This method does not support multiple connected networks 1645 * of the same type. Use {@link #getAllNetworks} and 1646 * {@link #getNetworkInfo(android.net.Network)} instead. 1647 */ 1648 @Deprecated 1649 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1650 @NonNull getAllNetworkInfo()1651 public NetworkInfo[] getAllNetworkInfo() { 1652 try { 1653 return mService.getAllNetworkInfo(); 1654 } catch (RemoteException e) { 1655 throw e.rethrowFromSystemServer(); 1656 } 1657 } 1658 1659 /** 1660 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently 1661 * connected. 1662 * @hide 1663 */ 1664 @SystemApi(client = MODULE_LIBRARIES) 1665 @RequiresPermission(anyOf = { 1666 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 1667 android.Manifest.permission.NETWORK_STACK, 1668 android.Manifest.permission.NETWORK_SETTINGS}) 1669 @NonNull getAllNetworkStateSnapshots()1670 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() { 1671 try { 1672 return mService.getAllNetworkStateSnapshots(); 1673 } catch (RemoteException e) { 1674 throw e.rethrowFromSystemServer(); 1675 } 1676 } 1677 1678 /** 1679 * Returns the {@link Network} object currently serving a given type, or 1680 * null if the given type is not connected. 1681 * 1682 * @hide 1683 * @deprecated This method does not support multiple connected networks 1684 * of the same type. Use {@link #getAllNetworks} and 1685 * {@link #getNetworkInfo(android.net.Network)} instead. 1686 */ 1687 @Deprecated 1688 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1689 @UnsupportedAppUsage getNetworkForType(int networkType)1690 public Network getNetworkForType(int networkType) { 1691 try { 1692 return mService.getNetworkForType(networkType); 1693 } catch (RemoteException e) { 1694 throw e.rethrowFromSystemServer(); 1695 } 1696 } 1697 1698 /** 1699 * Returns an array of all {@link Network} currently tracked by the framework. 1700 * 1701 * @deprecated This method does not provide any notification of network state changes, forcing 1702 * apps to call it repeatedly. This is inefficient and prone to race conditions. 1703 * Apps should use methods such as 1704 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead. 1705 * Apps that desire to obtain information about networks that do not apply to them 1706 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}. 1707 * 1708 * @return an array of {@link Network} objects. 1709 */ 1710 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1711 @NonNull 1712 @Deprecated getAllNetworks()1713 public Network[] getAllNetworks() { 1714 try { 1715 return mService.getAllNetworks(); 1716 } catch (RemoteException e) { 1717 throw e.rethrowFromSystemServer(); 1718 } 1719 } 1720 1721 /** 1722 * Returns an array of {@link NetworkCapabilities} objects, representing 1723 * the Networks that applications run by the given user will use by default. 1724 * @hide 1725 */ 1726 @UnsupportedAppUsage getDefaultNetworkCapabilitiesForUser(int userId)1727 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) { 1728 try { 1729 return mService.getDefaultNetworkCapabilitiesForUser( 1730 userId, mContext.getOpPackageName(), getAttributionTag()); 1731 } catch (RemoteException e) { 1732 throw e.rethrowFromSystemServer(); 1733 } 1734 } 1735 1736 /** 1737 * Returns the IP information for the current default network. 1738 * 1739 * @return a {@link LinkProperties} object describing the IP info 1740 * for the current default network, or {@code null} if there 1741 * is no current default network. 1742 * 1743 * {@hide} 1744 * @deprecated please use {@link #getLinkProperties(Network)} on the return 1745 * value of {@link #getActiveNetwork()} instead. In particular, 1746 * this method will return non-null LinkProperties even if the 1747 * app is blocked by policy from using this network. 1748 */ 1749 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1750 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091) getActiveLinkProperties()1751 public LinkProperties getActiveLinkProperties() { 1752 try { 1753 return mService.getActiveLinkProperties(); 1754 } catch (RemoteException e) { 1755 throw e.rethrowFromSystemServer(); 1756 } 1757 } 1758 1759 /** 1760 * Returns the IP information for a given network type. 1761 * 1762 * @param networkType the network type of interest. 1763 * @return a {@link LinkProperties} object describing the IP info 1764 * for the given networkType, or {@code null} if there is 1765 * no current default network. 1766 * 1767 * {@hide} 1768 * @deprecated This method does not support multiple connected networks 1769 * of the same type. Use {@link #getAllNetworks}, 1770 * {@link #getNetworkInfo(android.net.Network)}, and 1771 * {@link #getLinkProperties(android.net.Network)} instead. 1772 */ 1773 @Deprecated 1774 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1775 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562) getLinkProperties(int networkType)1776 public LinkProperties getLinkProperties(int networkType) { 1777 try { 1778 return mService.getLinkPropertiesForType(networkType); 1779 } catch (RemoteException e) { 1780 throw e.rethrowFromSystemServer(); 1781 } 1782 } 1783 1784 /** 1785 * Get the {@link LinkProperties} for the given {@link Network}. This 1786 * will return {@code null} if the network is unknown. 1787 * 1788 * @param network The {@link Network} object identifying the network in question. 1789 * @return The {@link LinkProperties} for the network, or {@code null}. 1790 */ 1791 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1792 @Nullable getLinkProperties(@ullable Network network)1793 public LinkProperties getLinkProperties(@Nullable Network network) { 1794 try { 1795 return mService.getLinkProperties(network); 1796 } catch (RemoteException e) { 1797 throw e.rethrowFromSystemServer(); 1798 } 1799 } 1800 1801 /** 1802 * Redact {@link LinkProperties} for a given package 1803 * 1804 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the 1805 * given package, considering its permissions. 1806 * 1807 * @param lp A {@link LinkProperties} which will be redacted. 1808 * @param uid The target uid. 1809 * @param packageName The name of the package, for appops logging. 1810 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid, 1811 * or null if the uid lacks the ACCESS_NETWORK_STATE permission. 1812 * @hide 1813 */ 1814 @RequiresPermission(anyOf = { 1815 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 1816 android.Manifest.permission.NETWORK_STACK, 1817 android.Manifest.permission.NETWORK_SETTINGS}) 1818 @SystemApi(client = MODULE_LIBRARIES) 1819 @Nullable getRedactedLinkPropertiesForPackage(@onNull LinkProperties lp, int uid, @NonNull String packageName)1820 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid, 1821 @NonNull String packageName) { 1822 try { 1823 return mService.getRedactedLinkPropertiesForPackage( 1824 lp, uid, packageName, getAttributionTag()); 1825 } catch (RemoteException e) { 1826 throw e.rethrowFromSystemServer(); 1827 } 1828 } 1829 1830 /** 1831 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null. 1832 * 1833 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}. 1834 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location 1835 * sensitive information. To retrieve this location sensitive information (subject to 1836 * the caller's location permissions), use a {@link NetworkCallback} with the 1837 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead. 1838 * 1839 * This method returns {@code null} if the network is unknown or if the |network| argument 1840 * is null. 1841 * 1842 * @param network The {@link Network} object identifying the network in question. 1843 * @return The {@link NetworkCapabilities} for the network, or {@code null}. 1844 */ 1845 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 1846 @Nullable getNetworkCapabilities(@ullable Network network)1847 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) { 1848 try { 1849 return mService.getNetworkCapabilities( 1850 network, mContext.getOpPackageName(), getAttributionTag()); 1851 } catch (RemoteException e) { 1852 throw e.rethrowFromSystemServer(); 1853 } 1854 } 1855 1856 /** 1857 * Redact {@link NetworkCapabilities} for a given package. 1858 * 1859 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send 1860 * to the given package, considering its permissions. If the passed capabilities contain 1861 * location-sensitive information, they will be redacted to the correct degree for the location 1862 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving 1863 * that level of location. If the UID holds no location permission, the returned object will 1864 * contain no location-sensitive information and the UID is not blamed. 1865 * 1866 * @param nc A {@link NetworkCapabilities} instance which will be redacted. 1867 * @param uid The target uid. 1868 * @param packageName The name of the package, for appops logging. 1869 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid, 1870 * or null if the uid lacks the ACCESS_NETWORK_STATE permission. 1871 * @hide 1872 */ 1873 @RequiresPermission(anyOf = { 1874 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 1875 android.Manifest.permission.NETWORK_STACK, 1876 android.Manifest.permission.NETWORK_SETTINGS}) 1877 @SystemApi(client = MODULE_LIBRARIES) 1878 @Nullable getRedactedNetworkCapabilitiesForPackage( @onNull NetworkCapabilities nc, int uid, @NonNull String packageName)1879 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage( 1880 @NonNull NetworkCapabilities nc, 1881 int uid, @NonNull String packageName) { 1882 try { 1883 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName, 1884 getAttributionTag()); 1885 } catch (RemoteException e) { 1886 throw e.rethrowFromSystemServer(); 1887 } 1888 } 1889 1890 /** 1891 * Gets a URL that can be used for resolving whether a captive portal is present. 1892 * 1. This URL should respond with a 204 response to a GET request to indicate no captive 1893 * portal is present. 1894 * 2. This URL must be HTTP as redirect responses are used to find captive portal 1895 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects. 1896 * 1897 * The system network validation may be using different strategies to detect captive portals, 1898 * so this method does not necessarily return a URL used by the system. It only returns a URL 1899 * that may be relevant for other components trying to detect captive portals. 1900 * 1901 * @hide 1902 * @deprecated This API returns a URL which is not guaranteed to be one of the URLs used by the 1903 * system. 1904 */ 1905 @Deprecated 1906 @SystemApi 1907 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) getCaptivePortalServerUrl()1908 public String getCaptivePortalServerUrl() { 1909 try { 1910 return mService.getCaptivePortalServerUrl(); 1911 } catch (RemoteException e) { 1912 throw e.rethrowFromSystemServer(); 1913 } 1914 } 1915 1916 /** 1917 * Tells the underlying networking system that the caller wants to 1918 * begin using the named feature. The interpretation of {@code feature} 1919 * is completely up to each networking implementation. 1920 * 1921 * <p>This method requires the caller to hold either the 1922 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission 1923 * or the ability to modify system settings as determined by 1924 * {@link android.provider.Settings.System#canWrite}.</p> 1925 * 1926 * @param networkType specifies which network the request pertains to 1927 * @param feature the name of the feature to be used 1928 * @return an integer value representing the outcome of the request. 1929 * The interpretation of this value is specific to each networking 1930 * implementation+feature combination, except that the value {@code -1} 1931 * always indicates failure. 1932 * 1933 * @deprecated Deprecated in favor of the cleaner 1934 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API. 1935 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will 1936 * throw {@code UnsupportedOperationException} if called. 1937 * @removed 1938 */ 1939 @Deprecated startUsingNetworkFeature(int networkType, String feature)1940 public int startUsingNetworkFeature(int networkType, String feature) { 1941 checkLegacyRoutingApiAccess(); 1942 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature); 1943 if (netCap == null) { 1944 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " + 1945 feature); 1946 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED; 1947 } 1948 1949 NetworkRequest request = null; 1950 synchronized (sLegacyRequests) { 1951 LegacyRequest l = sLegacyRequests.get(netCap); 1952 if (l != null) { 1953 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest); 1954 renewRequestLocked(l); 1955 if (l.currentNetwork != null) { 1956 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE; 1957 } else { 1958 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED; 1959 } 1960 } 1961 1962 request = requestNetworkForFeatureLocked(netCap); 1963 } 1964 if (request != null) { 1965 Log.d(TAG, "starting startUsingNetworkFeature for request " + request); 1966 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED; 1967 } else { 1968 Log.d(TAG, " request Failed"); 1969 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED; 1970 } 1971 } 1972 1973 /** 1974 * Tells the underlying networking system that the caller is finished 1975 * using the named feature. The interpretation of {@code feature} 1976 * is completely up to each networking implementation. 1977 * 1978 * <p>This method requires the caller to hold either the 1979 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission 1980 * or the ability to modify system settings as determined by 1981 * {@link android.provider.Settings.System#canWrite}.</p> 1982 * 1983 * @param networkType specifies which network the request pertains to 1984 * @param feature the name of the feature that is no longer needed 1985 * @return an integer value representing the outcome of the request. 1986 * The interpretation of this value is specific to each networking 1987 * implementation+feature combination, except that the value {@code -1} 1988 * always indicates failure. 1989 * 1990 * @deprecated Deprecated in favor of the cleaner 1991 * {@link #unregisterNetworkCallback(NetworkCallback)} API. 1992 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will 1993 * throw {@code UnsupportedOperationException} if called. 1994 * @removed 1995 */ 1996 @Deprecated stopUsingNetworkFeature(int networkType, String feature)1997 public int stopUsingNetworkFeature(int networkType, String feature) { 1998 checkLegacyRoutingApiAccess(); 1999 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature); 2000 if (netCap == null) { 2001 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " + 2002 feature); 2003 return -1; 2004 } 2005 2006 if (removeRequestForFeature(netCap)) { 2007 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature); 2008 } 2009 return 1; 2010 } 2011 2012 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) networkCapabilitiesForFeature(int networkType, String feature)2013 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) { 2014 if (networkType == TYPE_MOBILE) { 2015 switch (feature) { 2016 case "enableCBS": 2017 return networkCapabilitiesForType(TYPE_MOBILE_CBS); 2018 case "enableDUN": 2019 case "enableDUNAlways": 2020 return networkCapabilitiesForType(TYPE_MOBILE_DUN); 2021 case "enableFOTA": 2022 return networkCapabilitiesForType(TYPE_MOBILE_FOTA); 2023 case "enableHIPRI": 2024 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI); 2025 case "enableIMS": 2026 return networkCapabilitiesForType(TYPE_MOBILE_IMS); 2027 case "enableMMS": 2028 return networkCapabilitiesForType(TYPE_MOBILE_MMS); 2029 case "enableSUPL": 2030 return networkCapabilitiesForType(TYPE_MOBILE_SUPL); 2031 default: 2032 return null; 2033 } 2034 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) { 2035 return networkCapabilitiesForType(TYPE_WIFI_P2P); 2036 } 2037 return null; 2038 } 2039 legacyTypeForNetworkCapabilities(NetworkCapabilities netCap)2040 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) { 2041 if (netCap == null) return TYPE_NONE; 2042 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) { 2043 return TYPE_MOBILE_CBS; 2044 } 2045 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) { 2046 return TYPE_MOBILE_IMS; 2047 } 2048 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) { 2049 return TYPE_MOBILE_FOTA; 2050 } 2051 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) { 2052 return TYPE_MOBILE_DUN; 2053 } 2054 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) { 2055 return TYPE_MOBILE_SUPL; 2056 } 2057 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) { 2058 return TYPE_MOBILE_MMS; 2059 } 2060 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) { 2061 return TYPE_MOBILE_HIPRI; 2062 } 2063 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) { 2064 return TYPE_WIFI_P2P; 2065 } 2066 return TYPE_NONE; 2067 } 2068 2069 private static class LegacyRequest { 2070 NetworkCapabilities networkCapabilities; 2071 NetworkRequest networkRequest; 2072 int expireSequenceNumber; 2073 Network currentNetwork; 2074 int delay = -1; 2075 clearDnsBinding()2076 private void clearDnsBinding() { 2077 if (currentNetwork != null) { 2078 currentNetwork = null; 2079 setProcessDefaultNetworkForHostResolution(null); 2080 } 2081 } 2082 2083 NetworkCallback networkCallback = new NetworkCallback() { 2084 @Override 2085 public void onAvailable(Network network) { 2086 currentNetwork = network; 2087 Log.d(TAG, "startUsingNetworkFeature got Network:" + network); 2088 setProcessDefaultNetworkForHostResolution(network); 2089 } 2090 @Override 2091 public void onLost(Network network) { 2092 if (network.equals(currentNetwork)) clearDnsBinding(); 2093 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network); 2094 } 2095 }; 2096 } 2097 2098 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 2099 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests = 2100 new HashMap<>(); 2101 findRequestForFeature(NetworkCapabilities netCap)2102 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) { 2103 synchronized (sLegacyRequests) { 2104 LegacyRequest l = sLegacyRequests.get(netCap); 2105 if (l != null) return l.networkRequest; 2106 } 2107 return null; 2108 } 2109 renewRequestLocked(LegacyRequest l)2110 private void renewRequestLocked(LegacyRequest l) { 2111 l.expireSequenceNumber++; 2112 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber); 2113 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay); 2114 } 2115 expireRequest(NetworkCapabilities netCap, int sequenceNum)2116 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) { 2117 int ourSeqNum = -1; 2118 synchronized (sLegacyRequests) { 2119 LegacyRequest l = sLegacyRequests.get(netCap); 2120 if (l == null) return; 2121 ourSeqNum = l.expireSequenceNumber; 2122 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap); 2123 } 2124 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum); 2125 } 2126 2127 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) requestNetworkForFeatureLocked(NetworkCapabilities netCap)2128 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) { 2129 int delay = -1; 2130 int type = legacyTypeForNetworkCapabilities(netCap); 2131 try { 2132 delay = mService.getRestoreDefaultNetworkDelay(type); 2133 } catch (RemoteException e) { 2134 throw e.rethrowFromSystemServer(); 2135 } 2136 LegacyRequest l = new LegacyRequest(); 2137 l.networkCapabilities = netCap; 2138 l.delay = delay; 2139 l.expireSequenceNumber = 0; 2140 l.networkRequest = sendRequestForNetwork( 2141 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler()); 2142 if (l.networkRequest == null) return null; 2143 sLegacyRequests.put(netCap, l); 2144 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay); 2145 return l.networkRequest; 2146 } 2147 sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay)2148 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) { 2149 if (delay >= 0) { 2150 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay); 2151 CallbackHandler handler = getDefaultHandler(); 2152 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap); 2153 handler.sendMessageDelayed(msg, delay); 2154 } 2155 } 2156 2157 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) removeRequestForFeature(NetworkCapabilities netCap)2158 private boolean removeRequestForFeature(NetworkCapabilities netCap) { 2159 final LegacyRequest l; 2160 synchronized (sLegacyRequests) { 2161 l = sLegacyRequests.remove(netCap); 2162 } 2163 if (l == null) return false; 2164 unregisterNetworkCallback(l.networkCallback); 2165 l.clearDnsBinding(); 2166 return true; 2167 } 2168 2169 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray(); 2170 static { sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR)2171 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR); sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR)2172 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR); sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR)2173 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR); sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR)2174 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR); sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR)2175 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR); sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR)2176 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR); sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR)2177 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR); sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR)2178 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR); sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI)2179 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI); sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI)2180 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI); sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH)2181 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH); sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET)2182 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET); 2183 } 2184 2185 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray(); 2186 static { sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS)2187 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS); sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN)2188 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN); sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA)2189 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA); sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS)2190 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS); sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS)2191 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS); sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL)2192 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL); sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)2193 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P); 2194 } 2195 2196 /** 2197 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities 2198 * instance suitable for registering a request or callback. Throws an 2199 * IllegalArgumentException if no mapping from the legacy type to 2200 * NetworkCapabilities is known. 2201 * 2202 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest} 2203 * to find the network instead. 2204 * @hide 2205 */ networkCapabilitiesForType(int type)2206 public static NetworkCapabilities networkCapabilitiesForType(int type) { 2207 final NetworkCapabilities nc = new NetworkCapabilities(); 2208 2209 // Map from type to transports. 2210 final int NOT_FOUND = -1; 2211 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND); 2212 if (transport == NOT_FOUND) { 2213 throw new IllegalArgumentException("unknown legacy type: " + type); 2214 } 2215 nc.addTransportType(transport); 2216 2217 // Map from type to capabilities. 2218 nc.addCapability(sLegacyTypeToCapability.get( 2219 type, NetworkCapabilities.NET_CAPABILITY_INTERNET)); 2220 nc.maybeMarkCapabilitiesRestricted(); 2221 return nc; 2222 } 2223 2224 /** @hide */ 2225 public static class PacketKeepaliveCallback { 2226 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) PacketKeepaliveCallback()2227 public PacketKeepaliveCallback() { 2228 } 2229 /** The requested keepalive was successfully started. */ 2230 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) onStarted()2231 public void onStarted() {} 2232 /** The keepalive was resumed after being paused by the system. */ onResumed()2233 public void onResumed() {} 2234 /** The keepalive was successfully stopped. */ 2235 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) onStopped()2236 public void onStopped() {} 2237 /** The keepalive was paused automatically by the system. */ onPaused()2238 public void onPaused() {} 2239 /** An error occurred. */ 2240 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) onError(int error)2241 public void onError(int error) {} 2242 } 2243 2244 /** 2245 * Allows applications to request that the system periodically send specific packets on their 2246 * behalf, using hardware offload to save battery power. 2247 * 2248 * To request that the system send keepalives, call one of the methods that return a 2249 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive}, 2250 * passing in a non-null callback. If the callback is successfully started, the callback's 2251 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called, 2252 * specifying one of the {@code ERROR_*} constants in this class. 2253 * 2254 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call 2255 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or 2256 * {@link PacketKeepaliveCallback#onError} if an error occurred. 2257 * 2258 * @deprecated Use {@link SocketKeepalive} instead. 2259 * 2260 * @hide 2261 */ 2262 public class PacketKeepalive { 2263 2264 private static final String TAG = "PacketKeepalive"; 2265 2266 /** @hide */ 2267 public static final int SUCCESS = 0; 2268 2269 /** @hide */ 2270 public static final int NO_KEEPALIVE = -1; 2271 2272 /** @hide */ 2273 public static final int BINDER_DIED = -10; 2274 2275 /** The specified {@code Network} is not connected. */ 2276 public static final int ERROR_INVALID_NETWORK = -20; 2277 /** The specified IP addresses are invalid. For example, the specified source IP address is 2278 * not configured on the specified {@code Network}. */ 2279 public static final int ERROR_INVALID_IP_ADDRESS = -21; 2280 /** The requested port is invalid. */ 2281 public static final int ERROR_INVALID_PORT = -22; 2282 /** The packet length is invalid (e.g., too long). */ 2283 public static final int ERROR_INVALID_LENGTH = -23; 2284 /** The packet transmission interval is invalid (e.g., too short). */ 2285 public static final int ERROR_INVALID_INTERVAL = -24; 2286 2287 /** The hardware does not support this request. */ 2288 public static final int ERROR_HARDWARE_UNSUPPORTED = -30; 2289 /** The hardware returned an error. */ 2290 public static final int ERROR_HARDWARE_ERROR = -31; 2291 2292 /** The NAT-T destination port for IPsec */ 2293 public static final int NATT_PORT = 4500; 2294 2295 /** The minimum interval in seconds between keepalive packet transmissions */ 2296 public static final int MIN_INTERVAL = 10; 2297 2298 private final Network mNetwork; 2299 private final ISocketKeepaliveCallback mCallback; 2300 private final ExecutorService mExecutor; 2301 2302 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) stop()2303 public void stop() { 2304 try { 2305 mExecutor.execute(() -> { 2306 try { 2307 mService.stopKeepalive(mCallback); 2308 } catch (RemoteException e) { 2309 Log.e(TAG, "Error stopping packet keepalive: ", e); 2310 throw e.rethrowFromSystemServer(); 2311 } 2312 }); 2313 } catch (RejectedExecutionException e) { 2314 // The internal executor has already stopped due to previous event. 2315 } 2316 } 2317 PacketKeepalive(Network network, PacketKeepaliveCallback callback)2318 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) { 2319 Objects.requireNonNull(network, "network cannot be null"); 2320 Objects.requireNonNull(callback, "callback cannot be null"); 2321 mNetwork = network; 2322 mExecutor = Executors.newSingleThreadExecutor(); 2323 mCallback = new ISocketKeepaliveCallback.Stub() { 2324 @Override 2325 public void onStarted() { 2326 final long token = Binder.clearCallingIdentity(); 2327 try { 2328 mExecutor.execute(() -> { 2329 callback.onStarted(); 2330 }); 2331 } finally { 2332 Binder.restoreCallingIdentity(token); 2333 } 2334 } 2335 2336 @Override 2337 public void onResumed() { 2338 final long token = Binder.clearCallingIdentity(); 2339 try { 2340 mExecutor.execute(() -> { 2341 callback.onResumed(); 2342 }); 2343 } finally { 2344 Binder.restoreCallingIdentity(token); 2345 } 2346 } 2347 2348 @Override 2349 public void onStopped() { 2350 final long token = Binder.clearCallingIdentity(); 2351 try { 2352 mExecutor.execute(() -> { 2353 callback.onStopped(); 2354 }); 2355 } finally { 2356 Binder.restoreCallingIdentity(token); 2357 } 2358 mExecutor.shutdown(); 2359 } 2360 2361 @Override 2362 public void onPaused() { 2363 final long token = Binder.clearCallingIdentity(); 2364 try { 2365 mExecutor.execute(() -> { 2366 callback.onPaused(); 2367 }); 2368 } finally { 2369 Binder.restoreCallingIdentity(token); 2370 } 2371 mExecutor.shutdown(); 2372 } 2373 2374 @Override 2375 public void onError(int error) { 2376 final long token = Binder.clearCallingIdentity(); 2377 try { 2378 mExecutor.execute(() -> { 2379 callback.onError(error); 2380 }); 2381 } finally { 2382 Binder.restoreCallingIdentity(token); 2383 } 2384 mExecutor.shutdown(); 2385 } 2386 2387 @Override 2388 public void onDataReceived() { 2389 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke 2390 // this callback when data is received. 2391 } 2392 }; 2393 } 2394 } 2395 2396 /** 2397 * Starts an IPsec NAT-T keepalive packet with the specified parameters. 2398 * 2399 * @deprecated Use {@link #createSocketKeepalive} instead. 2400 * 2401 * @hide 2402 */ 2403 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) startNattKeepalive( Network network, int intervalSeconds, PacketKeepaliveCallback callback, InetAddress srcAddr, int srcPort, InetAddress dstAddr)2404 public PacketKeepalive startNattKeepalive( 2405 Network network, int intervalSeconds, PacketKeepaliveCallback callback, 2406 InetAddress srcAddr, int srcPort, InetAddress dstAddr) { 2407 final PacketKeepalive k = new PacketKeepalive(network, callback); 2408 try { 2409 mService.startNattKeepalive(network, intervalSeconds, k.mCallback, 2410 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress()); 2411 } catch (RemoteException e) { 2412 Log.e(TAG, "Error starting packet keepalive: ", e); 2413 throw e.rethrowFromSystemServer(); 2414 } 2415 return k; 2416 } 2417 2418 // Construct an invalid fd. createInvalidFd()2419 private ParcelFileDescriptor createInvalidFd() { 2420 final int invalidFd = -1; 2421 return ParcelFileDescriptor.adoptFd(invalidFd); 2422 } 2423 2424 /** 2425 * Request that keepalives be started on a IPsec NAT-T socket. 2426 * 2427 * @param network The {@link Network} the socket is on. 2428 * @param socket The socket that needs to be kept alive. 2429 * @param source The source address of the {@link UdpEncapsulationSocket}. 2430 * @param destination The destination address of the {@link UdpEncapsulationSocket}. 2431 * @param executor The executor on which callback will be invoked. The provided {@link Executor} 2432 * must run callback sequentially, otherwise the order of callbacks cannot be 2433 * guaranteed. 2434 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive 2435 * changes. Must be extended by applications that use this API. 2436 * 2437 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the 2438 * given socket. 2439 **/ createSocketKeepalive(@onNull Network network, @NonNull UdpEncapsulationSocket socket, @NonNull InetAddress source, @NonNull InetAddress destination, @NonNull @CallbackExecutor Executor executor, @NonNull Callback callback)2440 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network, 2441 @NonNull UdpEncapsulationSocket socket, 2442 @NonNull InetAddress source, 2443 @NonNull InetAddress destination, 2444 @NonNull @CallbackExecutor Executor executor, 2445 @NonNull Callback callback) { 2446 ParcelFileDescriptor dup; 2447 try { 2448 // Dup is needed here as the pfd inside the socket is owned by the IpSecService, 2449 // which cannot be obtained by the app process. 2450 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor()); 2451 } catch (IOException ignored) { 2452 // Construct an invalid fd, so that if the user later calls start(), it will fail with 2453 // ERROR_INVALID_SOCKET. 2454 dup = createInvalidFd(); 2455 } 2456 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source, 2457 destination, executor, callback); 2458 } 2459 2460 /** 2461 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called 2462 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}. 2463 * 2464 * @param network The {@link Network} the socket is on. 2465 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided 2466 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent 2467 * from that port. 2468 * @param source The source address of the {@link UdpEncapsulationSocket}. 2469 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The 2470 * keepalive packets will always be sent to port 4500 of the given {@code destination}. 2471 * @param executor The executor on which callback will be invoked. The provided {@link Executor} 2472 * must run callback sequentially, otherwise the order of callbacks cannot be 2473 * guaranteed. 2474 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive 2475 * changes. Must be extended by applications that use this API. 2476 * 2477 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the 2478 * given socket. 2479 * @hide 2480 */ 2481 @SystemApi 2482 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD) createNattKeepalive(@onNull Network network, @NonNull ParcelFileDescriptor pfd, @NonNull InetAddress source, @NonNull InetAddress destination, @NonNull @CallbackExecutor Executor executor, @NonNull Callback callback)2483 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network, 2484 @NonNull ParcelFileDescriptor pfd, 2485 @NonNull InetAddress source, 2486 @NonNull InetAddress destination, 2487 @NonNull @CallbackExecutor Executor executor, 2488 @NonNull Callback callback) { 2489 ParcelFileDescriptor dup; 2490 try { 2491 // TODO: Consider remove unnecessary dup. 2492 dup = pfd.dup(); 2493 } catch (IOException ignored) { 2494 // Construct an invalid fd, so that if the user later calls start(), it will fail with 2495 // ERROR_INVALID_SOCKET. 2496 dup = createInvalidFd(); 2497 } 2498 return new NattSocketKeepalive(mService, network, dup, 2499 -1 /* Unused */, source, destination, executor, callback); 2500 } 2501 2502 /** 2503 * Request that keepalives be started on a TCP socket. The socket must be established. 2504 * 2505 * @param network The {@link Network} the socket is on. 2506 * @param socket The socket that needs to be kept alive. 2507 * @param executor The executor on which callback will be invoked. This implementation assumes 2508 * the provided {@link Executor} runs the callbacks in sequence with no 2509 * concurrency. Failing this, no guarantee of correctness can be made. It is 2510 * the responsibility of the caller to ensure the executor provides this 2511 * guarantee. A simple way of creating such an executor is with the standard 2512 * tool {@code Executors.newSingleThreadExecutor}. 2513 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive 2514 * changes. Must be extended by applications that use this API. 2515 * 2516 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the 2517 * given socket. 2518 * @hide 2519 */ 2520 @SystemApi 2521 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD) createSocketKeepalive(@onNull Network network, @NonNull Socket socket, @NonNull @CallbackExecutor Executor executor, @NonNull Callback callback)2522 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network, 2523 @NonNull Socket socket, 2524 @NonNull @CallbackExecutor Executor executor, 2525 @NonNull Callback callback) { 2526 ParcelFileDescriptor dup; 2527 try { 2528 dup = ParcelFileDescriptor.fromSocket(socket); 2529 } catch (UncheckedIOException ignored) { 2530 // Construct an invalid fd, so that if the user later calls start(), it will fail with 2531 // ERROR_INVALID_SOCKET. 2532 dup = createInvalidFd(); 2533 } 2534 return new TcpSocketKeepalive(mService, network, dup, executor, callback); 2535 } 2536 2537 /** 2538 * Get the supported keepalive count for each transport configured in resource overlays. 2539 * 2540 * @return An array of supported keepalive count for each transport type. 2541 * @hide 2542 */ 2543 @RequiresPermission(anyOf = { android.Manifest.permission.NETWORK_SETTINGS, 2544 // CTS 13 used QUERY_ALL_PACKAGES to get the resource value, which was implemented 2545 // as below in KeepaliveUtils. Also allow that permission so that KeepaliveUtils can 2546 // use this method and avoid breaking released CTS. Apps that have this permission 2547 // can query the resource themselves anyway. 2548 android.Manifest.permission.QUERY_ALL_PACKAGES }) getSupportedKeepalives()2549 public int[] getSupportedKeepalives() { 2550 try { 2551 return mService.getSupportedKeepalives(); 2552 } catch (RemoteException e) { 2553 throw e.rethrowFromSystemServer(); 2554 } 2555 } 2556 2557 /** 2558 * Ensure that a network route exists to deliver traffic to the specified 2559 * host via the specified network interface. An attempt to add a route that 2560 * already exists is ignored, but treated as successful. 2561 * 2562 * <p>This method requires the caller to hold either the 2563 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission 2564 * or the ability to modify system settings as determined by 2565 * {@link android.provider.Settings.System#canWrite}.</p> 2566 * 2567 * @param networkType the type of the network over which traffic to the specified 2568 * host is to be routed 2569 * @param hostAddress the IP address of the host to which the route is desired 2570 * @return {@code true} on success, {@code false} on failure 2571 * 2572 * @deprecated Deprecated in favor of the 2573 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, 2574 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API. 2575 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will 2576 * throw {@code UnsupportedOperationException} if called. 2577 * @removed 2578 */ 2579 @Deprecated requestRouteToHost(int networkType, int hostAddress)2580 public boolean requestRouteToHost(int networkType, int hostAddress) { 2581 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress)); 2582 } 2583 2584 /** 2585 * Ensure that a network route exists to deliver traffic to the specified 2586 * host via the specified network interface. An attempt to add a route that 2587 * already exists is ignored, but treated as successful. 2588 * 2589 * <p>This method requires the caller to hold either the 2590 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission 2591 * or the ability to modify system settings as determined by 2592 * {@link android.provider.Settings.System#canWrite}.</p> 2593 * 2594 * @param networkType the type of the network over which traffic to the specified 2595 * host is to be routed 2596 * @param hostAddress the IP address of the host to which the route is desired 2597 * @return {@code true} on success, {@code false} on failure 2598 * @hide 2599 * @deprecated Deprecated in favor of the {@link #requestNetwork} and 2600 * {@link #bindProcessToNetwork} API. 2601 */ 2602 @Deprecated 2603 @UnsupportedAppUsage 2604 @SystemApi(client = MODULE_LIBRARIES) requestRouteToHostAddress(int networkType, InetAddress hostAddress)2605 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) { 2606 checkLegacyRoutingApiAccess(); 2607 try { 2608 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(), 2609 mContext.getOpPackageName(), getAttributionTag()); 2610 } catch (RemoteException e) { 2611 throw e.rethrowFromSystemServer(); 2612 } 2613 } 2614 2615 /** 2616 * @return the context's attribution tag 2617 */ 2618 // TODO: Remove method and replace with direct call once R code is pushed to AOSP getAttributionTag()2619 private @Nullable String getAttributionTag() { 2620 return mContext.getAttributionTag(); 2621 } 2622 2623 /** 2624 * Returns the value of the setting for background data usage. If false, 2625 * applications should not use the network if the application is not in the 2626 * foreground. Developers should respect this setting, and check the value 2627 * of this before performing any background data operations. 2628 * <p> 2629 * All applications that have background services that use the network 2630 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}. 2631 * <p> 2632 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of 2633 * background data depends on several combined factors, and this method will 2634 * always return {@code true}. Instead, when background data is unavailable, 2635 * {@link #getActiveNetworkInfo()} will now appear disconnected. 2636 * 2637 * @return Whether background data usage is allowed. 2638 */ 2639 @Deprecated getBackgroundDataSetting()2640 public boolean getBackgroundDataSetting() { 2641 // assume that background data is allowed; final authority is 2642 // NetworkInfo which may be blocked. 2643 return true; 2644 } 2645 2646 /** 2647 * Sets the value of the setting for background data usage. 2648 * 2649 * @param allowBackgroundData Whether an application should use data while 2650 * it is in the background. 2651 * 2652 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING 2653 * @see #getBackgroundDataSetting() 2654 * @hide 2655 */ 2656 @Deprecated 2657 @UnsupportedAppUsage setBackgroundDataSetting(boolean allowBackgroundData)2658 public void setBackgroundDataSetting(boolean allowBackgroundData) { 2659 // ignored 2660 } 2661 2662 /** 2663 * @hide 2664 * @deprecated Talk to TelephonyManager directly 2665 */ 2666 @Deprecated 2667 @UnsupportedAppUsage getMobileDataEnabled()2668 public boolean getMobileDataEnabled() { 2669 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class); 2670 if (tm != null) { 2671 int subId = SubscriptionManager.getDefaultDataSubscriptionId(); 2672 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId); 2673 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled(); 2674 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId 2675 + " retVal=" + retVal); 2676 return retVal; 2677 } 2678 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false"); 2679 return false; 2680 } 2681 2682 /** 2683 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener} 2684 * to find out when the system default network has gone in to a high power state. 2685 */ 2686 public interface OnNetworkActiveListener { 2687 /** 2688 * Called on the main thread of the process to report that the current data network 2689 * has become active, and it is now a good time to perform any pending network 2690 * operations. Note that this listener only tells you when the network becomes 2691 * active; if at any other time you want to know whether it is active (and thus okay 2692 * to initiate network traffic), you can retrieve its instantaneous state with 2693 * {@link ConnectivityManager#isDefaultNetworkActive}. 2694 */ onNetworkActive()2695 void onNetworkActive(); 2696 } 2697 2698 @GuardedBy("mNetworkActivityListeners") 2699 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener> 2700 mNetworkActivityListeners = new ArrayMap<>(); 2701 2702 /** 2703 * Start listening to reports when the system's default data network is active, meaning it is 2704 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()} 2705 * to determine the current state of the system's default network after registering the 2706 * listener. 2707 * <p> 2708 * If the process default network has been set with 2709 * {@link ConnectivityManager#bindProcessToNetwork} this function will not 2710 * reflect the process's default, but the system default. 2711 * 2712 * @param l The listener to be told when the network is active. 2713 */ addDefaultNetworkActiveListener(final OnNetworkActiveListener l)2714 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) { 2715 final INetworkActivityListener rl = new INetworkActivityListener.Stub() { 2716 @Override 2717 public void onNetworkActive() throws RemoteException { 2718 l.onNetworkActive(); 2719 } 2720 }; 2721 2722 synchronized (mNetworkActivityListeners) { 2723 try { 2724 mService.registerNetworkActivityListener(rl); 2725 mNetworkActivityListeners.put(l, rl); 2726 } catch (RemoteException e) { 2727 throw e.rethrowFromSystemServer(); 2728 } 2729 } 2730 } 2731 2732 /** 2733 * Remove network active listener previously registered with 2734 * {@link #addDefaultNetworkActiveListener}. 2735 * 2736 * @param l Previously registered listener. 2737 */ removeDefaultNetworkActiveListener(@onNull OnNetworkActiveListener l)2738 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) { 2739 synchronized (mNetworkActivityListeners) { 2740 final INetworkActivityListener rl = mNetworkActivityListeners.get(l); 2741 if (rl == null) { 2742 throw new IllegalArgumentException("Listener was not registered."); 2743 } 2744 try { 2745 mService.unregisterNetworkActivityListener(rl); 2746 mNetworkActivityListeners.remove(l); 2747 } catch (RemoteException e) { 2748 throw e.rethrowFromSystemServer(); 2749 } 2750 } 2751 } 2752 2753 /** 2754 * Return whether the data network is currently active. An active network means that 2755 * it is currently in a high power state for performing data transmission. On some 2756 * types of networks, it may be expensive to move and stay in such a state, so it is 2757 * more power efficient to batch network traffic together when the radio is already in 2758 * this state. This method tells you whether right now is currently a good time to 2759 * initiate network traffic, as the network is already active. 2760 */ isDefaultNetworkActive()2761 public boolean isDefaultNetworkActive() { 2762 try { 2763 return mService.isDefaultNetworkActive(); 2764 } catch (RemoteException e) { 2765 throw e.rethrowFromSystemServer(); 2766 } 2767 } 2768 2769 /** 2770 * {@hide} 2771 */ ConnectivityManager(Context context, IConnectivityManager service)2772 public ConnectivityManager(Context context, IConnectivityManager service) { 2773 this(context, service, true /* newStatic */); 2774 } 2775 ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic)2776 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) { 2777 mContext = Objects.requireNonNull(context, "missing context"); 2778 mService = Objects.requireNonNull(service, "missing IConnectivityManager"); 2779 // sInstance is accessed without a lock, so it may actually be reassigned several times with 2780 // different ConnectivityManager, but that's still OK considering its usage. 2781 if (sInstance == null && newStatic) { 2782 final Context appContext = mContext.getApplicationContext(); 2783 // Don't create static ConnectivityManager instance again to prevent infinite loop. 2784 // If the application context is null, we're either in the system process or 2785 // it's the application context very early in app initialization. In both these 2786 // cases, the passed-in Context will not be freed, so it's safe to pass it to the 2787 // service. http://b/27532714 . 2788 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service, 2789 false /* newStatic */); 2790 } 2791 } 2792 2793 /** {@hide} */ 2794 @UnsupportedAppUsage from(Context context)2795 public static ConnectivityManager from(Context context) { 2796 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 2797 } 2798 2799 /** @hide */ getDefaultRequest()2800 public NetworkRequest getDefaultRequest() { 2801 try { 2802 // This is not racy as the default request is final in ConnectivityService. 2803 return mService.getDefaultRequest(); 2804 } catch (RemoteException e) { 2805 throw e.rethrowFromSystemServer(); 2806 } 2807 } 2808 2809 /** 2810 * Check if the package is allowed to write settings. This also records that such an access 2811 * happened. 2812 * 2813 * @return {@code true} iff the package is allowed to write settings. 2814 */ 2815 // TODO: Remove method and replace with direct call once R code is pushed to AOSP checkAndNoteWriteSettingsOperation(@onNull Context context, int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag, boolean throwException)2816 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid, 2817 @NonNull String callingPackage, @Nullable String callingAttributionTag, 2818 boolean throwException) { 2819 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage, 2820 callingAttributionTag, throwException); 2821 } 2822 2823 /** 2824 * @deprecated - use getSystemService. This is a kludge to support static access in certain 2825 * situations where a Context pointer is unavailable. 2826 * @hide 2827 */ 2828 @Deprecated getInstanceOrNull()2829 static ConnectivityManager getInstanceOrNull() { 2830 return sInstance; 2831 } 2832 2833 /** 2834 * @deprecated - use getSystemService. This is a kludge to support static access in certain 2835 * situations where a Context pointer is unavailable. 2836 * @hide 2837 */ 2838 @Deprecated 2839 @UnsupportedAppUsage getInstance()2840 private static ConnectivityManager getInstance() { 2841 if (getInstanceOrNull() == null) { 2842 throw new IllegalStateException("No ConnectivityManager yet constructed"); 2843 } 2844 return getInstanceOrNull(); 2845 } 2846 2847 /** 2848 * Get the set of tetherable, available interfaces. This list is limited by 2849 * device configuration and current interface existence. 2850 * 2851 * @return an array of 0 or more Strings of tetherable interface names. 2852 * 2853 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead. 2854 * {@hide} 2855 */ 2856 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 2857 @UnsupportedAppUsage 2858 @Deprecated getTetherableIfaces()2859 public String[] getTetherableIfaces() { 2860 return getTetheringManager().getTetherableIfaces(); 2861 } 2862 2863 /** 2864 * Get the set of tethered interfaces. 2865 * 2866 * @return an array of 0 or more String of currently tethered interface names. 2867 * 2868 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead. 2869 * {@hide} 2870 */ 2871 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 2872 @UnsupportedAppUsage 2873 @Deprecated getTetheredIfaces()2874 public String[] getTetheredIfaces() { 2875 return getTetheringManager().getTetheredIfaces(); 2876 } 2877 2878 /** 2879 * Get the set of interface names which attempted to tether but 2880 * failed. Re-attempting to tether may cause them to reset to the Tethered 2881 * state. Alternatively, causing the interface to be destroyed and recreated 2882 * may cause them to reset to the available state. 2883 * {@link ConnectivityManager#getLastTetherError} can be used to get more 2884 * information on the cause of the errors. 2885 * 2886 * @return an array of 0 or more String indicating the interface names 2887 * which failed to tether. 2888 * 2889 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead. 2890 * {@hide} 2891 */ 2892 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 2893 @UnsupportedAppUsage 2894 @Deprecated getTetheringErroredIfaces()2895 public String[] getTetheringErroredIfaces() { 2896 return getTetheringManager().getTetheringErroredIfaces(); 2897 } 2898 2899 /** 2900 * Get the set of tethered dhcp ranges. 2901 * 2902 * @deprecated This method is not supported. 2903 * TODO: remove this function when all of clients are removed. 2904 * {@hide} 2905 */ 2906 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) 2907 @Deprecated getTetheredDhcpRanges()2908 public String[] getTetheredDhcpRanges() { 2909 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported"); 2910 } 2911 2912 /** 2913 * Attempt to tether the named interface. This will set up a dhcp server 2914 * on the interface, forward and NAT IP packets and forward DNS requests 2915 * to the best active upstream network interface. Note that if no upstream 2916 * IP network interface is available, dhcp will still run and traffic will be 2917 * allowed between the tethered devices and this device, though upstream net 2918 * access will of course fail until an upstream network interface becomes 2919 * active. 2920 * 2921 * <p>This method requires the caller to hold either the 2922 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission 2923 * or the ability to modify system settings as determined by 2924 * {@link android.provider.Settings.System#canWrite}.</p> 2925 * 2926 * <p>WARNING: New clients should not use this function. The only usages should be in PanService 2927 * and WifiStateMachine which need direct access. All other clients should use 2928 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning 2929 * logic.</p> 2930 * 2931 * @param iface the interface name to tether. 2932 * @return error a {@code TETHER_ERROR} value indicating success or failure type 2933 * @deprecated Use {@link TetheringManager#startTethering} instead 2934 * 2935 * {@hide} 2936 */ 2937 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 2938 @Deprecated tether(String iface)2939 public int tether(String iface) { 2940 return getTetheringManager().tether(iface); 2941 } 2942 2943 /** 2944 * Stop tethering the named interface. 2945 * 2946 * <p>This method requires the caller to hold either the 2947 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission 2948 * or the ability to modify system settings as determined by 2949 * {@link android.provider.Settings.System#canWrite}.</p> 2950 * 2951 * <p>WARNING: New clients should not use this function. The only usages should be in PanService 2952 * and WifiStateMachine which need direct access. All other clients should use 2953 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning 2954 * logic.</p> 2955 * 2956 * @param iface the interface name to untether. 2957 * @return error a {@code TETHER_ERROR} value indicating success or failure type 2958 * 2959 * {@hide} 2960 */ 2961 @UnsupportedAppUsage 2962 @Deprecated untether(String iface)2963 public int untether(String iface) { 2964 return getTetheringManager().untether(iface); 2965 } 2966 2967 /** 2968 * Check if the device allows for tethering. It may be disabled via 2969 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or 2970 * due to device configuration. 2971 * 2972 * <p>If this app does not have permission to use this API, it will always 2973 * return false rather than throw an exception.</p> 2974 * 2975 * <p>If the device has a hotspot provisioning app, the caller is required to hold the 2976 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p> 2977 * 2978 * <p>Otherwise, this method requires the caller to hold the ability to modify system 2979 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p> 2980 * 2981 * @return a boolean - {@code true} indicating Tethering is supported. 2982 * 2983 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead. 2984 * {@hide} 2985 */ 2986 @SystemApi 2987 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED, 2988 android.Manifest.permission.WRITE_SETTINGS}) isTetheringSupported()2989 public boolean isTetheringSupported() { 2990 return getTetheringManager().isTetheringSupported(); 2991 } 2992 2993 /** 2994 * Callback for use with {@link #startTethering} to find out whether tethering succeeded. 2995 * 2996 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead. 2997 * @hide 2998 */ 2999 @SystemApi 3000 @Deprecated 3001 public static abstract class OnStartTetheringCallback { 3002 /** 3003 * Called when tethering has been successfully started. 3004 */ onTetheringStarted()3005 public void onTetheringStarted() {} 3006 3007 /** 3008 * Called when starting tethering failed. 3009 */ onTetheringFailed()3010 public void onTetheringFailed() {} 3011 } 3012 3013 /** 3014 * Convenient overload for 3015 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null 3016 * handler to run on the current thread's {@link Looper}. 3017 * 3018 * @deprecated Use {@link TetheringManager#startTethering} instead. 3019 * @hide 3020 */ 3021 @SystemApi 3022 @Deprecated 3023 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) startTethering(int type, boolean showProvisioningUi, final OnStartTetheringCallback callback)3024 public void startTethering(int type, boolean showProvisioningUi, 3025 final OnStartTetheringCallback callback) { 3026 startTethering(type, showProvisioningUi, callback, null); 3027 } 3028 3029 /** 3030 * Runs tether provisioning for the given type if needed and then starts tethering if 3031 * the check succeeds. If no carrier provisioning is required for tethering, tethering is 3032 * enabled immediately. If provisioning fails, tethering will not be enabled. It also 3033 * schedules tether provisioning re-checks if appropriate. 3034 * 3035 * @param type The type of tethering to start. Must be one of 3036 * {@link ConnectivityManager.TETHERING_WIFI}, 3037 * {@link ConnectivityManager.TETHERING_USB}, or 3038 * {@link ConnectivityManager.TETHERING_BLUETOOTH}. 3039 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there 3040 * is one. This should be true the first time this function is called and also any time 3041 * the user can see this UI. It gives users information from their carrier about the 3042 * check failing and how they can sign up for tethering if possible. 3043 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller 3044 * of the result of trying to tether. 3045 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked. 3046 * 3047 * @deprecated Use {@link TetheringManager#startTethering} instead. 3048 * @hide 3049 */ 3050 @SystemApi 3051 @Deprecated 3052 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) startTethering(int type, boolean showProvisioningUi, final OnStartTetheringCallback callback, Handler handler)3053 public void startTethering(int type, boolean showProvisioningUi, 3054 final OnStartTetheringCallback callback, Handler handler) { 3055 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null."); 3056 3057 final Executor executor = new Executor() { 3058 @Override 3059 public void execute(Runnable command) { 3060 if (handler == null) { 3061 command.run(); 3062 } else { 3063 handler.post(command); 3064 } 3065 } 3066 }; 3067 3068 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() { 3069 @Override 3070 public void onTetheringStarted() { 3071 callback.onTetheringStarted(); 3072 } 3073 3074 @Override 3075 public void onTetheringFailed(final int error) { 3076 callback.onTetheringFailed(); 3077 } 3078 }; 3079 3080 final TetheringRequest request = new TetheringRequest.Builder(type) 3081 .setShouldShowEntitlementUi(showProvisioningUi).build(); 3082 3083 getTetheringManager().startTethering(request, executor, tetheringCallback); 3084 } 3085 3086 /** 3087 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if 3088 * applicable. 3089 * 3090 * @param type The type of tethering to stop. Must be one of 3091 * {@link ConnectivityManager.TETHERING_WIFI}, 3092 * {@link ConnectivityManager.TETHERING_USB}, or 3093 * {@link ConnectivityManager.TETHERING_BLUETOOTH}. 3094 * 3095 * @deprecated Use {@link TetheringManager#stopTethering} instead. 3096 * @hide 3097 */ 3098 @SystemApi 3099 @Deprecated 3100 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) stopTethering(int type)3101 public void stopTethering(int type) { 3102 getTetheringManager().stopTethering(type); 3103 } 3104 3105 /** 3106 * Callback for use with {@link registerTetheringEventCallback} to find out tethering 3107 * upstream status. 3108 * 3109 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead. 3110 * @hide 3111 */ 3112 @SystemApi 3113 @Deprecated 3114 public abstract static class OnTetheringEventCallback { 3115 3116 /** 3117 * Called when tethering upstream changed. This can be called multiple times and can be 3118 * called any time. 3119 * 3120 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't 3121 * have any upstream. 3122 */ onUpstreamChanged(@ullable Network network)3123 public void onUpstreamChanged(@Nullable Network network) {} 3124 } 3125 3126 @GuardedBy("mTetheringEventCallbacks") 3127 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback> 3128 mTetheringEventCallbacks = new ArrayMap<>(); 3129 3130 /** 3131 * Start listening to tethering change events. Any new added callback will receive the last 3132 * tethering status right away. If callback is registered when tethering has no upstream or 3133 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called 3134 * with a null argument. The same callback object cannot be registered twice. 3135 * 3136 * @param executor the executor on which callback will be invoked. 3137 * @param callback the callback to be called when tethering has change events. 3138 * 3139 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead. 3140 * @hide 3141 */ 3142 @SystemApi 3143 @Deprecated 3144 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) registerTetheringEventCallback( @onNull @allbackExecutor Executor executor, @NonNull final OnTetheringEventCallback callback)3145 public void registerTetheringEventCallback( 3146 @NonNull @CallbackExecutor Executor executor, 3147 @NonNull final OnTetheringEventCallback callback) { 3148 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null."); 3149 3150 final TetheringEventCallback tetherCallback = 3151 new TetheringEventCallback() { 3152 @Override 3153 public void onUpstreamChanged(@Nullable Network network) { 3154 callback.onUpstreamChanged(network); 3155 } 3156 }; 3157 3158 synchronized (mTetheringEventCallbacks) { 3159 mTetheringEventCallbacks.put(callback, tetherCallback); 3160 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback); 3161 } 3162 } 3163 3164 /** 3165 * Remove tethering event callback previously registered with 3166 * {@link #registerTetheringEventCallback}. 3167 * 3168 * @param callback previously registered callback. 3169 * 3170 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead. 3171 * @hide 3172 */ 3173 @SystemApi 3174 @Deprecated 3175 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) unregisterTetheringEventCallback( @onNull final OnTetheringEventCallback callback)3176 public void unregisterTetheringEventCallback( 3177 @NonNull final OnTetheringEventCallback callback) { 3178 Objects.requireNonNull(callback, "The callback must be non-null"); 3179 synchronized (mTetheringEventCallbacks) { 3180 final TetheringEventCallback tetherCallback = 3181 mTetheringEventCallbacks.remove(callback); 3182 getTetheringManager().unregisterTetheringEventCallback(tetherCallback); 3183 } 3184 } 3185 3186 3187 /** 3188 * Get the list of regular expressions that define any tetherable 3189 * USB network interfaces. If USB tethering is not supported by the 3190 * device, this list should be empty. 3191 * 3192 * @return an array of 0 or more regular expression Strings defining 3193 * what interfaces are considered tetherable usb interfaces. 3194 * 3195 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead. 3196 * {@hide} 3197 */ 3198 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 3199 @UnsupportedAppUsage 3200 @Deprecated getTetherableUsbRegexs()3201 public String[] getTetherableUsbRegexs() { 3202 return getTetheringManager().getTetherableUsbRegexs(); 3203 } 3204 3205 /** 3206 * Get the list of regular expressions that define any tetherable 3207 * Wifi network interfaces. If Wifi tethering is not supported by the 3208 * device, this list should be empty. 3209 * 3210 * @return an array of 0 or more regular expression Strings defining 3211 * what interfaces are considered tetherable wifi interfaces. 3212 * 3213 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead. 3214 * {@hide} 3215 */ 3216 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 3217 @UnsupportedAppUsage 3218 @Deprecated getTetherableWifiRegexs()3219 public String[] getTetherableWifiRegexs() { 3220 return getTetheringManager().getTetherableWifiRegexs(); 3221 } 3222 3223 /** 3224 * Get the list of regular expressions that define any tetherable 3225 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the 3226 * device, this list should be empty. 3227 * 3228 * @return an array of 0 or more regular expression Strings defining 3229 * what interfaces are considered tetherable bluetooth interfaces. 3230 * 3231 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged( 3232 *TetheringManager.TetheringInterfaceRegexps)} instead. 3233 * {@hide} 3234 */ 3235 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 3236 @UnsupportedAppUsage 3237 @Deprecated getTetherableBluetoothRegexs()3238 public String[] getTetherableBluetoothRegexs() { 3239 return getTetheringManager().getTetherableBluetoothRegexs(); 3240 } 3241 3242 /** 3243 * Attempt to both alter the mode of USB and Tethering of USB. A 3244 * utility method to deal with some of the complexity of USB - will 3245 * attempt to switch to Rndis and subsequently tether the resulting 3246 * interface on {@code true} or turn off tethering and switch off 3247 * Rndis on {@code false}. 3248 * 3249 * <p>This method requires the caller to hold either the 3250 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission 3251 * or the ability to modify system settings as determined by 3252 * {@link android.provider.Settings.System#canWrite}.</p> 3253 * 3254 * @param enable a boolean - {@code true} to enable tethering 3255 * @return error a {@code TETHER_ERROR} value indicating success or failure type 3256 * @deprecated Use {@link TetheringManager#startTethering} instead 3257 * 3258 * {@hide} 3259 */ 3260 @UnsupportedAppUsage 3261 @Deprecated setUsbTethering(boolean enable)3262 public int setUsbTethering(boolean enable) { 3263 return getTetheringManager().setUsbTethering(enable); 3264 } 3265 3266 /** 3267 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}. 3268 * {@hide} 3269 */ 3270 @SystemApi 3271 @Deprecated 3272 public static final int TETHER_ERROR_NO_ERROR = 0; 3273 /** 3274 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}. 3275 * {@hide} 3276 */ 3277 @Deprecated 3278 public static final int TETHER_ERROR_UNKNOWN_IFACE = 3279 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE; 3280 /** 3281 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}. 3282 * {@hide} 3283 */ 3284 @Deprecated 3285 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 3286 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL; 3287 /** 3288 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}. 3289 * {@hide} 3290 */ 3291 @Deprecated 3292 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED; 3293 /** 3294 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}. 3295 * {@hide} 3296 */ 3297 @Deprecated 3298 public static final int TETHER_ERROR_UNAVAIL_IFACE = 3299 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE; 3300 /** 3301 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}. 3302 * {@hide} 3303 */ 3304 @Deprecated 3305 public static final int TETHER_ERROR_MASTER_ERROR = 3306 TetheringManager.TETHER_ERROR_INTERNAL_ERROR; 3307 /** 3308 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}. 3309 * {@hide} 3310 */ 3311 @Deprecated 3312 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 3313 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR; 3314 /** 3315 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}. 3316 * {@hide} 3317 */ 3318 @Deprecated 3319 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 3320 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR; 3321 /** 3322 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}. 3323 * {@hide} 3324 */ 3325 @Deprecated 3326 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 3327 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR; 3328 /** 3329 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}. 3330 * {@hide} 3331 */ 3332 @Deprecated 3333 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 3334 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR; 3335 /** 3336 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}. 3337 * {@hide} 3338 */ 3339 @Deprecated 3340 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 3341 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR; 3342 /** 3343 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}. 3344 * {@hide} 3345 */ 3346 @SystemApi 3347 @Deprecated 3348 public static final int TETHER_ERROR_PROVISION_FAILED = 11; 3349 /** 3350 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}. 3351 * {@hide} 3352 */ 3353 @Deprecated 3354 public static final int TETHER_ERROR_DHCPSERVER_ERROR = 3355 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR; 3356 /** 3357 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}. 3358 * {@hide} 3359 */ 3360 @SystemApi 3361 @Deprecated 3362 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13; 3363 3364 /** 3365 * Get a more detailed error code after a Tethering or Untethering 3366 * request asynchronously failed. 3367 * 3368 * @param iface The name of the interface of interest 3369 * @return error The error code of the last error tethering or untethering the named 3370 * interface 3371 * 3372 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead. 3373 * {@hide} 3374 */ 3375 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 3376 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 3377 @Deprecated getLastTetherError(String iface)3378 public int getLastTetherError(String iface) { 3379 int error = getTetheringManager().getLastTetherError(iface); 3380 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) { 3381 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been 3382 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE 3383 // instead. 3384 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE; 3385 } 3386 return error; 3387 } 3388 3389 /** @hide */ 3390 @Retention(RetentionPolicy.SOURCE) 3391 @IntDef(value = { 3392 TETHER_ERROR_NO_ERROR, 3393 TETHER_ERROR_PROVISION_FAILED, 3394 TETHER_ERROR_ENTITLEMENT_UNKONWN, 3395 }) 3396 public @interface EntitlementResultCode { 3397 } 3398 3399 /** 3400 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether 3401 * entitlement succeeded. 3402 * 3403 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead. 3404 * @hide 3405 */ 3406 @SystemApi 3407 @Deprecated 3408 public interface OnTetheringEntitlementResultListener { 3409 /** 3410 * Called to notify entitlement result. 3411 * 3412 * @param resultCode an int value of entitlement result. It may be one of 3413 * {@link #TETHER_ERROR_NO_ERROR}, 3414 * {@link #TETHER_ERROR_PROVISION_FAILED}, or 3415 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}. 3416 */ onTetheringEntitlementResult(@ntitlementResultCode int resultCode)3417 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode); 3418 } 3419 3420 /** 3421 * Get the last value of the entitlement check on this downstream. If the cached value is 3422 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the 3423 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not 3424 * guaranteed that the UI-based entitlement check will complete in any specific time period 3425 * and it may in fact never complete. Any successful entitlement check the platform performs for 3426 * any reason will update the cached value. 3427 * 3428 * @param type the downstream type of tethering. Must be one of 3429 * {@link #TETHERING_WIFI}, 3430 * {@link #TETHERING_USB}, or 3431 * {@link #TETHERING_BLUETOOTH}. 3432 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check. 3433 * @param executor the executor on which callback will be invoked. 3434 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to 3435 * notify the caller of the result of entitlement check. The listener may be called zero 3436 * or one time. 3437 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead. 3438 * {@hide} 3439 */ 3440 @SystemApi 3441 @Deprecated 3442 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi, @NonNull @CallbackExecutor Executor executor, @NonNull final OnTetheringEntitlementResultListener listener)3443 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi, 3444 @NonNull @CallbackExecutor Executor executor, 3445 @NonNull final OnTetheringEntitlementResultListener listener) { 3446 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null."); 3447 ResultReceiver wrappedListener = new ResultReceiver(null) { 3448 @Override 3449 protected void onReceiveResult(int resultCode, Bundle resultData) { 3450 final long token = Binder.clearCallingIdentity(); 3451 try { 3452 executor.execute(() -> { 3453 listener.onTetheringEntitlementResult(resultCode); 3454 }); 3455 } finally { 3456 Binder.restoreCallingIdentity(token); 3457 } 3458 } 3459 }; 3460 3461 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener, 3462 showEntitlementUi); 3463 } 3464 3465 /** 3466 * Report network connectivity status. This is currently used only 3467 * to alter status bar UI. 3468 * <p>This method requires the caller to hold the permission 3469 * {@link android.Manifest.permission#STATUS_BAR}. 3470 * 3471 * @param networkType The type of network you want to report on 3472 * @param percentage The quality of the connection 0 is bad, 100 is good 3473 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead. 3474 * {@hide} 3475 */ reportInetCondition(int networkType, int percentage)3476 public void reportInetCondition(int networkType, int percentage) { 3477 printStackTrace(); 3478 try { 3479 mService.reportInetCondition(networkType, percentage); 3480 } catch (RemoteException e) { 3481 throw e.rethrowFromSystemServer(); 3482 } 3483 } 3484 3485 /** 3486 * Report a problem network to the framework. This provides a hint to the system 3487 * that there might be connectivity problems on this network and may cause 3488 * the framework to re-evaluate network connectivity and/or switch to another 3489 * network. 3490 * 3491 * @param network The {@link Network} the application was attempting to use 3492 * or {@code null} to indicate the current default network. 3493 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both 3494 * working and non-working connectivity. 3495 */ 3496 @Deprecated reportBadNetwork(@ullable Network network)3497 public void reportBadNetwork(@Nullable Network network) { 3498 printStackTrace(); 3499 try { 3500 // One of these will be ignored because it matches system's current state. 3501 // The other will trigger the necessary reevaluation. 3502 mService.reportNetworkConnectivity(network, true); 3503 mService.reportNetworkConnectivity(network, false); 3504 } catch (RemoteException e) { 3505 throw e.rethrowFromSystemServer(); 3506 } 3507 } 3508 3509 /** 3510 * Report to the framework whether a network has working connectivity. 3511 * This provides a hint to the system that a particular network is providing 3512 * working connectivity or not. In response the framework may re-evaluate 3513 * the network's connectivity and might take further action thereafter. 3514 * 3515 * @param network The {@link Network} the application was attempting to use 3516 * or {@code null} to indicate the current default network. 3517 * @param hasConnectivity {@code true} if the application was able to successfully access the 3518 * Internet using {@code network} or {@code false} if not. 3519 */ reportNetworkConnectivity(@ullable Network network, boolean hasConnectivity)3520 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) { 3521 printStackTrace(); 3522 try { 3523 mService.reportNetworkConnectivity(network, hasConnectivity); 3524 } catch (RemoteException e) { 3525 throw e.rethrowFromSystemServer(); 3526 } 3527 } 3528 3529 /** 3530 * Set a network-independent global HTTP proxy. 3531 * 3532 * This sets an HTTP proxy that applies to all networks and overrides any network-specific 3533 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when 3534 * accessing any network, regardless of what the settings for that network are. 3535 * 3536 * Note that HTTP proxies are by nature typically network-dependent, and setting a global 3537 * proxy is likely to break networking on multiple networks. This method is only meant 3538 * for device policy clients looking to do general internal filtering or similar use cases. 3539 * 3540 * @see #getGlobalProxy 3541 * @see LinkProperties#getHttpProxy 3542 * 3543 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this 3544 * method with a {@code null} value will clear the global HTTP proxy. 3545 * @hide 3546 */ 3547 // Used by Device Policy Manager to set the global proxy. 3548 @SystemApi(client = MODULE_LIBRARIES) 3549 @RequiresPermission(android.Manifest.permission.NETWORK_STACK) setGlobalProxy(@ullable final ProxyInfo p)3550 public void setGlobalProxy(@Nullable final ProxyInfo p) { 3551 try { 3552 mService.setGlobalProxy(p); 3553 } catch (RemoteException e) { 3554 throw e.rethrowFromSystemServer(); 3555 } 3556 } 3557 3558 /** 3559 * Retrieve any network-independent global HTTP proxy. 3560 * 3561 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null} 3562 * if no global HTTP proxy is set. 3563 * @hide 3564 */ 3565 @SystemApi(client = MODULE_LIBRARIES) 3566 @Nullable getGlobalProxy()3567 public ProxyInfo getGlobalProxy() { 3568 try { 3569 return mService.getGlobalProxy(); 3570 } catch (RemoteException e) { 3571 throw e.rethrowFromSystemServer(); 3572 } 3573 } 3574 3575 /** 3576 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a 3577 * network-specific HTTP proxy. If {@code network} is null, the 3578 * network-specific proxy returned is the proxy of the default active 3579 * network. 3580 * 3581 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no 3582 * global HTTP proxy is set, {@code ProxyInfo} for {@code network}, 3583 * or when {@code network} is {@code null}, 3584 * the {@code ProxyInfo} for the default active network. Returns 3585 * {@code null} when no proxy applies or the caller doesn't have 3586 * permission to use {@code network}. 3587 * @hide 3588 */ getProxyForNetwork(Network network)3589 public ProxyInfo getProxyForNetwork(Network network) { 3590 try { 3591 return mService.getProxyForNetwork(network); 3592 } catch (RemoteException e) { 3593 throw e.rethrowFromSystemServer(); 3594 } 3595 } 3596 3597 /** 3598 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned, 3599 * otherwise if this process is bound to a {@link Network} using 3600 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise 3601 * the default network's proxy is returned. 3602 * 3603 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no 3604 * HTTP proxy is active. 3605 */ 3606 @Nullable getDefaultProxy()3607 public ProxyInfo getDefaultProxy() { 3608 return getProxyForNetwork(getBoundNetworkForProcess()); 3609 } 3610 3611 /** 3612 * Returns whether the hardware supports the given network type. 3613 * 3614 * This doesn't indicate there is coverage or such a network is available, just whether the 3615 * hardware supports it. For example a GSM phone without a SIM card will return {@code true} 3616 * for mobile data, but a WiFi only tablet would return {@code false}. 3617 * 3618 * @param networkType The network type we'd like to check 3619 * @return {@code true} if supported, else {@code false} 3620 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead. 3621 * @hide 3622 */ 3623 @Deprecated 3624 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) 3625 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562) isNetworkSupported(int networkType)3626 public boolean isNetworkSupported(int networkType) { 3627 try { 3628 return mService.isNetworkSupported(networkType); 3629 } catch (RemoteException e) { 3630 throw e.rethrowFromSystemServer(); 3631 } 3632 } 3633 3634 /** 3635 * Returns if the currently active data network is metered. A network is 3636 * classified as metered when the user is sensitive to heavy data usage on 3637 * that connection due to monetary costs, data limitations or 3638 * battery/performance issues. You should check this before doing large 3639 * data transfers, and warn the user or delay the operation until another 3640 * network is available. 3641 * 3642 * @return {@code true} if large transfers should be avoided, otherwise 3643 * {@code false}. 3644 */ 3645 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) isActiveNetworkMetered()3646 public boolean isActiveNetworkMetered() { 3647 try { 3648 return mService.isActiveNetworkMetered(); 3649 } catch (RemoteException e) { 3650 throw e.rethrowFromSystemServer(); 3651 } 3652 } 3653 3654 /** 3655 * Set sign in error notification to visible or invisible 3656 * 3657 * @hide 3658 * @deprecated Doesn't properly deal with multiple connected networks of the same type. 3659 */ 3660 @Deprecated setProvisioningNotificationVisible(boolean visible, int networkType, String action)3661 public void setProvisioningNotificationVisible(boolean visible, int networkType, 3662 String action) { 3663 try { 3664 mService.setProvisioningNotificationVisible(visible, networkType, action); 3665 } catch (RemoteException e) { 3666 throw e.rethrowFromSystemServer(); 3667 } 3668 } 3669 3670 /** 3671 * Set the value for enabling/disabling airplane mode 3672 * 3673 * @param enable whether to enable airplane mode or not 3674 * 3675 * @hide 3676 */ 3677 @RequiresPermission(anyOf = { 3678 android.Manifest.permission.NETWORK_AIRPLANE_MODE, 3679 android.Manifest.permission.NETWORK_SETTINGS, 3680 android.Manifest.permission.NETWORK_SETUP_WIZARD, 3681 android.Manifest.permission.NETWORK_STACK}) 3682 @SystemApi setAirplaneMode(boolean enable)3683 public void setAirplaneMode(boolean enable) { 3684 try { 3685 mService.setAirplaneMode(enable); 3686 } catch (RemoteException e) { 3687 throw e.rethrowFromSystemServer(); 3688 } 3689 } 3690 3691 /** 3692 * Registers the specified {@link NetworkProvider}. 3693 * Each listener must only be registered once. The listener can be unregistered with 3694 * {@link #unregisterNetworkProvider}. 3695 * 3696 * @param provider the provider to register 3697 * @return the ID of the provider. This ID must be used by the provider when registering 3698 * {@link android.net.NetworkAgent}s. 3699 * @hide 3700 */ 3701 @SystemApi 3702 @RequiresPermission(anyOf = { 3703 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 3704 android.Manifest.permission.NETWORK_FACTORY}) registerNetworkProvider(@onNull NetworkProvider provider)3705 public int registerNetworkProvider(@NonNull NetworkProvider provider) { 3706 if (provider.getProviderId() != NetworkProvider.ID_NONE) { 3707 throw new IllegalStateException("NetworkProviders can only be registered once"); 3708 } 3709 3710 try { 3711 int providerId = mService.registerNetworkProvider(provider.getMessenger(), 3712 provider.getName()); 3713 provider.setProviderId(providerId); 3714 } catch (RemoteException e) { 3715 throw e.rethrowFromSystemServer(); 3716 } 3717 return provider.getProviderId(); 3718 } 3719 3720 /** 3721 * Unregisters the specified NetworkProvider. 3722 * 3723 * @param provider the provider to unregister 3724 * @hide 3725 */ 3726 @SystemApi 3727 @RequiresPermission(anyOf = { 3728 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 3729 android.Manifest.permission.NETWORK_FACTORY}) unregisterNetworkProvider(@onNull NetworkProvider provider)3730 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) { 3731 try { 3732 mService.unregisterNetworkProvider(provider.getMessenger()); 3733 } catch (RemoteException e) { 3734 throw e.rethrowFromSystemServer(); 3735 } 3736 provider.setProviderId(NetworkProvider.ID_NONE); 3737 } 3738 3739 /** 3740 * Register or update a network offer with ConnectivityService. 3741 * 3742 * ConnectivityService keeps track of offers made by the various providers and matches 3743 * them to networking requests made by apps or the system. A callback identifies an offer 3744 * uniquely, and later calls with the same callback update the offer. The provider supplies a 3745 * score and the capabilities of the network it might be able to bring up ; these act as 3746 * filters used by ConnectivityService to only send those requests that can be fulfilled by the 3747 * provider. 3748 * 3749 * The provider is under no obligation to be able to bring up the network it offers at any 3750 * given time. Instead, this mechanism is meant to limit requests received by providers 3751 * to those they actually have a chance to fulfill, as providers don't have a way to compare 3752 * the quality of the network satisfying a given request to their own offer. 3753 * 3754 * An offer can be updated by calling this again with the same callback object. This is 3755 * similar to calling unofferNetwork and offerNetwork again, but will only update the 3756 * provider with the changes caused by the changes in the offer. 3757 * 3758 * @param provider The provider making this offer. 3759 * @param score The prospective score of the network. 3760 * @param caps The prospective capabilities of the network. 3761 * @param callback The callback to call when this offer is needed or unneeded. 3762 * @hide exposed via the NetworkProvider class. 3763 */ 3764 @RequiresPermission(anyOf = { 3765 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 3766 android.Manifest.permission.NETWORK_FACTORY}) offerNetwork(@onNull final int providerId, @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps, @NonNull final INetworkOfferCallback callback)3767 public void offerNetwork(@NonNull final int providerId, 3768 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps, 3769 @NonNull final INetworkOfferCallback callback) { 3770 try { 3771 mService.offerNetwork(providerId, 3772 Objects.requireNonNull(score, "null score"), 3773 Objects.requireNonNull(caps, "null caps"), 3774 Objects.requireNonNull(callback, "null callback")); 3775 } catch (RemoteException e) { 3776 throw e.rethrowFromSystemServer(); 3777 } 3778 } 3779 3780 /** 3781 * Withdraw a network offer made with {@link #offerNetwork}. 3782 * 3783 * @param callback The callback passed at registration time. This must be the same object 3784 * that was passed to {@link #offerNetwork} 3785 * @hide exposed via the NetworkProvider class. 3786 */ unofferNetwork(@onNull final INetworkOfferCallback callback)3787 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) { 3788 try { 3789 mService.unofferNetwork(Objects.requireNonNull(callback)); 3790 } catch (RemoteException e) { 3791 throw e.rethrowFromSystemServer(); 3792 } 3793 } 3794 /** @hide exposed via the NetworkProvider class. */ 3795 @RequiresPermission(anyOf = { 3796 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 3797 android.Manifest.permission.NETWORK_FACTORY}) declareNetworkRequestUnfulfillable(@onNull NetworkRequest request)3798 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) { 3799 try { 3800 mService.declareNetworkRequestUnfulfillable(request); 3801 } catch (RemoteException e) { 3802 throw e.rethrowFromSystemServer(); 3803 } 3804 } 3805 3806 /** 3807 * @hide 3808 * Register a NetworkAgent with ConnectivityService. 3809 * @return Network corresponding to NetworkAgent. 3810 */ 3811 @RequiresPermission(anyOf = { 3812 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 3813 android.Manifest.permission.NETWORK_FACTORY}) registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp, NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config, int providerId)3814 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp, 3815 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config, 3816 int providerId) { 3817 try { 3818 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId); 3819 } catch (RemoteException e) { 3820 throw e.rethrowFromSystemServer(); 3821 } 3822 } 3823 3824 /** 3825 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network 3826 * changes. Should be extended by applications wanting notifications. 3827 * 3828 * A {@code NetworkCallback} is registered by calling 3829 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, 3830 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)}, 3831 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is 3832 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}. 3833 * A {@code NetworkCallback} should be registered at most once at any time. 3834 * A {@code NetworkCallback} that has been unregistered can be registered again. 3835 */ 3836 public static class NetworkCallback { 3837 /** 3838 * No flags associated with this callback. 3839 * @hide 3840 */ 3841 public static final int FLAG_NONE = 0; 3842 3843 /** 3844 * Inclusion of this flag means location-sensitive redaction requests keeping location info. 3845 * 3846 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information. 3847 * Prior to Android 12, this information is always returned to apps holding the appropriate 3848 * permission, possibly noting that the app has used location. 3849 * <p>In Android 12 and above, by default the sent objects do not contain any location 3850 * information, even if the app holds the necessary permissions, and the system does not 3851 * take note of location usage by the app. Apps can request that location information is 3852 * included, in which case the system will check location permission and the location 3853 * toggle state, and take note of location usage by the app if any such information is 3854 * returned. 3855 * 3856 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent 3857 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}. 3858 * <p> 3859 * These include: 3860 * <li> Some transport info instances (retrieved via 3861 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo} 3862 * contain location sensitive information. 3863 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location 3864 * sensitive for wifi suggestor apps (i.e using 3865 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li> 3866 * </p> 3867 * <p> 3868 * Note: 3869 * <li> Retrieving this location sensitive information (subject to app's location 3870 * permissions) will be noted by system. </li> 3871 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does 3872 * not include location sensitive information. 3873 */ 3874 // Note: Some existing fields which are location sensitive may still be included without 3875 // this flag if the app targets SDK < S (to maintain backwards compatibility). 3876 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0; 3877 3878 /** @hide */ 3879 @Retention(RetentionPolicy.SOURCE) 3880 @IntDef(flag = true, prefix = "FLAG_", value = { 3881 FLAG_NONE, 3882 FLAG_INCLUDE_LOCATION_INFO 3883 }) 3884 public @interface Flag { } 3885 3886 /** 3887 * All the valid flags for error checking. 3888 */ 3889 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO; 3890 NetworkCallback()3891 public NetworkCallback() { 3892 this(FLAG_NONE); 3893 } 3894 NetworkCallback(@lag int flags)3895 public NetworkCallback(@Flag int flags) { 3896 if ((flags & VALID_FLAGS) != flags) { 3897 throw new IllegalArgumentException("Invalid flags"); 3898 } 3899 mFlags = flags; 3900 } 3901 3902 /** 3903 * Called when the framework connects to a new network to evaluate whether it satisfies this 3904 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable} 3905 * callback. There is no guarantee that this new network will satisfy any requests, or that 3906 * the network will stay connected for longer than the time necessary to evaluate it. 3907 * <p> 3908 * Most applications <b>should not</b> act on this callback, and should instead use 3909 * {@link #onAvailable}. This callback is intended for use by applications that can assist 3910 * the framework in properly evaluating the network — for example, an application that 3911 * can automatically log in to a captive portal without user intervention. 3912 * 3913 * @param network The {@link Network} of the network that is being evaluated. 3914 * 3915 * @hide 3916 */ onPreCheck(@onNull Network network)3917 public void onPreCheck(@NonNull Network network) {} 3918 3919 /** 3920 * Called when the framework connects and has declared a new network ready for use. 3921 * This callback may be called more than once if the {@link Network} that is 3922 * satisfying the request changes. 3923 * 3924 * @param network The {@link Network} of the satisfying network. 3925 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network. 3926 * @param linkProperties The {@link LinkProperties} of the satisfying network. 3927 * @param blocked Whether access to the {@link Network} is blocked due to system policy. 3928 * @hide 3929 */ onAvailable(@onNull Network network, @NonNull NetworkCapabilities networkCapabilities, @NonNull LinkProperties linkProperties, @BlockedReason int blocked)3930 public final void onAvailable(@NonNull Network network, 3931 @NonNull NetworkCapabilities networkCapabilities, 3932 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) { 3933 // Internally only this method is called when a new network is available, and 3934 // it calls the callback in the same way and order that older versions used 3935 // to call so as not to change the behavior. 3936 onAvailable(network, networkCapabilities, linkProperties, blocked != 0); 3937 onBlockedStatusChanged(network, blocked); 3938 } 3939 3940 /** 3941 * Legacy variant of onAvailable that takes a boolean blocked reason. 3942 * 3943 * This method has never been public API, but it's not final, so there may be apps that 3944 * implemented it and rely on it being called. Do our best not to break them. 3945 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after 3946 * this method is called. There does not seem to be a way to avoid this. 3947 * TODO: add a compat check to move apps off this method, and eventually stop calling it. 3948 * 3949 * @hide 3950 */ onAvailable(@onNull Network network, @NonNull NetworkCapabilities networkCapabilities, @NonNull LinkProperties linkProperties, boolean blocked)3951 public void onAvailable(@NonNull Network network, 3952 @NonNull NetworkCapabilities networkCapabilities, 3953 @NonNull LinkProperties linkProperties, boolean blocked) { 3954 onAvailable(network); 3955 if (!networkCapabilities.hasCapability( 3956 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) { 3957 onNetworkSuspended(network); 3958 } 3959 onCapabilitiesChanged(network, networkCapabilities); 3960 onLinkPropertiesChanged(network, linkProperties); 3961 // No call to onBlockedStatusChanged here. That is done by the caller. 3962 } 3963 3964 /** 3965 * Called when the framework connects and has declared a new network ready for use. 3966 * 3967 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may 3968 * be available at the same time, and onAvailable will be called for each of these as they 3969 * appear. 3970 * 3971 * <p>For callbacks registered with {@link #requestNetwork} and 3972 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument 3973 * is the new best network for this request and is now tracked by this callback ; this 3974 * callback will no longer receive method calls about other networks that may have been 3975 * passed to this method previously. The previously-best network may have disconnected, or 3976 * it may still be around and the newly-best network may simply be better. 3977 * 3978 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately 3979 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} 3980 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call 3981 * to {@link #onBlockedStatusChanged(Network, boolean)}. 3982 * 3983 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or 3984 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in 3985 * this callback as this is prone to race conditions (there is no guarantee the objects 3986 * returned by these methods will be current). Instead, wait for a call to 3987 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and 3988 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed 3989 * to be well-ordered with respect to other callbacks. 3990 * 3991 * @param network The {@link Network} of the satisfying network. 3992 */ onAvailable(@onNull Network network)3993 public void onAvailable(@NonNull Network network) {} 3994 3995 /** 3996 * Called when the network is about to be lost, typically because there are no outstanding 3997 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call 3998 * with the new replacement network for graceful handover. This method is not guaranteed 3999 * to be called before {@link NetworkCallback#onLost} is called, for example in case a 4000 * network is suddenly disconnected. 4001 * 4002 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or 4003 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in 4004 * this callback as this is prone to race conditions ; calling these methods while in a 4005 * callback may return an outdated or even a null object. 4006 * 4007 * @param network The {@link Network} that is about to be lost. 4008 * @param maxMsToLive The time in milliseconds the system intends to keep the network 4009 * connected for graceful handover; note that the network may still 4010 * suffer a hard loss at any time. 4011 */ onLosing(@onNull Network network, int maxMsToLive)4012 public void onLosing(@NonNull Network network, int maxMsToLive) {} 4013 4014 /** 4015 * Called when a network disconnects or otherwise no longer satisfies this request or 4016 * callback. 4017 * 4018 * <p>If the callback was registered with requestNetwork() or 4019 * registerDefaultNetworkCallback(), it will only be invoked against the last network 4020 * returned by onAvailable() when that network is lost and no other network satisfies 4021 * the criteria of the request. 4022 * 4023 * <p>If the callback was registered with registerNetworkCallback() it will be called for 4024 * each network which no longer satisfies the criteria of the callback. 4025 * 4026 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or 4027 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in 4028 * this callback as this is prone to race conditions ; calling these methods while in a 4029 * callback may return an outdated or even a null object. 4030 * 4031 * @param network The {@link Network} lost. 4032 */ onLost(@onNull Network network)4033 public void onLost(@NonNull Network network) {} 4034 4035 /** 4036 * Called if no network is found within the timeout time specified in 4037 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the 4038 * requested network request cannot be fulfilled (whether or not a timeout was 4039 * specified). When this callback is invoked the associated 4040 * {@link NetworkRequest} will have already been removed and released, as if 4041 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called. 4042 */ onUnavailable()4043 public void onUnavailable() {} 4044 4045 /** 4046 * Called when the network corresponding to this request changes capabilities but still 4047 * satisfies the requested criteria. 4048 * 4049 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed 4050 * to be called immediately after {@link #onAvailable}. 4051 * 4052 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous 4053 * ConnectivityManager methods in this callback as this is prone to race conditions : 4054 * calling these methods while in a callback may return an outdated or even a null object. 4055 * 4056 * @param network The {@link Network} whose capabilities have changed. 4057 * @param networkCapabilities The new {@link NetworkCapabilities} for this 4058 * network. 4059 */ onCapabilitiesChanged(@onNull Network network, @NonNull NetworkCapabilities networkCapabilities)4060 public void onCapabilitiesChanged(@NonNull Network network, 4061 @NonNull NetworkCapabilities networkCapabilities) {} 4062 4063 /** 4064 * Called when the network corresponding to this request changes {@link LinkProperties}. 4065 * 4066 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed 4067 * to be called immediately after {@link #onAvailable}. 4068 * 4069 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous 4070 * ConnectivityManager methods in this callback as this is prone to race conditions : 4071 * calling these methods while in a callback may return an outdated or even a null object. 4072 * 4073 * @param network The {@link Network} whose link properties have changed. 4074 * @param linkProperties The new {@link LinkProperties} for this network. 4075 */ onLinkPropertiesChanged(@onNull Network network, @NonNull LinkProperties linkProperties)4076 public void onLinkPropertiesChanged(@NonNull Network network, 4077 @NonNull LinkProperties linkProperties) {} 4078 4079 /** 4080 * Called when the network the framework connected to for this request suspends data 4081 * transmission temporarily. 4082 * 4083 * <p>This generally means that while the TCP connections are still live temporarily 4084 * network data fails to transfer. To give a specific example, this is used on cellular 4085 * networks to mask temporary outages when driving through a tunnel, etc. In general this 4086 * means read operations on sockets on this network will block once the buffers are 4087 * drained, and write operations will block once the buffers are full. 4088 * 4089 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or 4090 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in 4091 * this callback as this is prone to race conditions (there is no guarantee the objects 4092 * returned by these methods will be current). 4093 * 4094 * @hide 4095 */ onNetworkSuspended(@onNull Network network)4096 public void onNetworkSuspended(@NonNull Network network) {} 4097 4098 /** 4099 * Called when the network the framework connected to for this request 4100 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be 4101 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call. 4102 4103 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or 4104 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in 4105 * this callback as this is prone to race conditions : calling these methods while in a 4106 * callback may return an outdated or even a null object. 4107 * 4108 * @hide 4109 */ onNetworkResumed(@onNull Network network)4110 public void onNetworkResumed(@NonNull Network network) {} 4111 4112 /** 4113 * Called when access to the specified network is blocked or unblocked. 4114 * 4115 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or 4116 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in 4117 * this callback as this is prone to race conditions : calling these methods while in a 4118 * callback may return an outdated or even a null object. 4119 * 4120 * @param network The {@link Network} whose blocked status has changed. 4121 * @param blocked The blocked status of this {@link Network}. 4122 */ onBlockedStatusChanged(@onNull Network network, boolean blocked)4123 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {} 4124 4125 /** 4126 * Called when access to the specified network is blocked or unblocked, or the reason for 4127 * access being blocked changes. 4128 * 4129 * If a NetworkCallback object implements this method, 4130 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called. 4131 * 4132 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or 4133 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in 4134 * this callback as this is prone to race conditions : calling these methods while in a 4135 * callback may return an outdated or even a null object. 4136 * 4137 * @param network The {@link Network} whose blocked status has changed. 4138 * @param blocked The blocked status of this {@link Network}. 4139 * @hide 4140 */ 4141 @SystemApi(client = MODULE_LIBRARIES) onBlockedStatusChanged(@onNull Network network, @BlockedReason int blocked)4142 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) { 4143 onBlockedStatusChanged(network, blocked != 0); 4144 } 4145 4146 private NetworkRequest networkRequest; 4147 private final int mFlags; 4148 } 4149 4150 /** 4151 * Constant error codes used by ConnectivityService to communicate about failures and errors 4152 * across a Binder boundary. 4153 * @hide 4154 */ 4155 public interface Errors { 4156 int TOO_MANY_REQUESTS = 1; 4157 } 4158 4159 /** @hide */ 4160 public static class TooManyRequestsException extends RuntimeException {} 4161 convertServiceException(ServiceSpecificException e)4162 private static RuntimeException convertServiceException(ServiceSpecificException e) { 4163 switch (e.errorCode) { 4164 case Errors.TOO_MANY_REQUESTS: 4165 return new TooManyRequestsException(); 4166 default: 4167 Log.w(TAG, "Unknown service error code " + e.errorCode); 4168 return new RuntimeException(e); 4169 } 4170 } 4171 4172 /** @hide */ 4173 public static final int CALLBACK_PRECHECK = 1; 4174 /** @hide */ 4175 public static final int CALLBACK_AVAILABLE = 2; 4176 /** @hide arg1 = TTL */ 4177 public static final int CALLBACK_LOSING = 3; 4178 /** @hide */ 4179 public static final int CALLBACK_LOST = 4; 4180 /** @hide */ 4181 public static final int CALLBACK_UNAVAIL = 5; 4182 /** @hide */ 4183 public static final int CALLBACK_CAP_CHANGED = 6; 4184 /** @hide */ 4185 public static final int CALLBACK_IP_CHANGED = 7; 4186 /** @hide obj = NetworkCapabilities, arg1 = seq number */ 4187 private static final int EXPIRE_LEGACY_REQUEST = 8; 4188 /** @hide */ 4189 public static final int CALLBACK_SUSPENDED = 9; 4190 /** @hide */ 4191 public static final int CALLBACK_RESUMED = 10; 4192 /** @hide */ 4193 public static final int CALLBACK_BLK_CHANGED = 11; 4194 4195 /** @hide */ getCallbackName(int whichCallback)4196 public static String getCallbackName(int whichCallback) { 4197 switch (whichCallback) { 4198 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK"; 4199 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE"; 4200 case CALLBACK_LOSING: return "CALLBACK_LOSING"; 4201 case CALLBACK_LOST: return "CALLBACK_LOST"; 4202 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL"; 4203 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED"; 4204 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED"; 4205 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST"; 4206 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED"; 4207 case CALLBACK_RESUMED: return "CALLBACK_RESUMED"; 4208 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED"; 4209 default: 4210 return Integer.toString(whichCallback); 4211 } 4212 } 4213 4214 private static class CallbackHandler extends Handler { 4215 private static final String TAG = "ConnectivityManager.CallbackHandler"; 4216 private static final boolean DBG = false; 4217 CallbackHandler(Looper looper)4218 CallbackHandler(Looper looper) { 4219 super(looper); 4220 } 4221 CallbackHandler(Handler handler)4222 CallbackHandler(Handler handler) { 4223 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper()); 4224 } 4225 4226 @Override handleMessage(Message message)4227 public void handleMessage(Message message) { 4228 if (message.what == EXPIRE_LEGACY_REQUEST) { 4229 // the sInstance can't be null because to send this message a ConnectivityManager 4230 // instance must have been created prior to creating the thread on which this 4231 // Handler is running. 4232 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1); 4233 return; 4234 } 4235 4236 final NetworkRequest request = getObject(message, NetworkRequest.class); 4237 final Network network = getObject(message, Network.class); 4238 final NetworkCallback callback; 4239 synchronized (sCallbacks) { 4240 callback = sCallbacks.get(request); 4241 if (callback == null) { 4242 Log.w(TAG, 4243 "callback not found for " + getCallbackName(message.what) + " message"); 4244 return; 4245 } 4246 if (message.what == CALLBACK_UNAVAIL) { 4247 sCallbacks.remove(request); 4248 callback.networkRequest = ALREADY_UNREGISTERED; 4249 } 4250 } 4251 if (DBG) { 4252 Log.d(TAG, getCallbackName(message.what) + " for network " + network); 4253 } 4254 4255 switch (message.what) { 4256 case CALLBACK_PRECHECK: { 4257 callback.onPreCheck(network); 4258 break; 4259 } 4260 case CALLBACK_AVAILABLE: { 4261 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class); 4262 LinkProperties lp = getObject(message, LinkProperties.class); 4263 callback.onAvailable(network, cap, lp, message.arg1); 4264 break; 4265 } 4266 case CALLBACK_LOSING: { 4267 callback.onLosing(network, message.arg1); 4268 break; 4269 } 4270 case CALLBACK_LOST: { 4271 callback.onLost(network); 4272 break; 4273 } 4274 case CALLBACK_UNAVAIL: { 4275 callback.onUnavailable(); 4276 break; 4277 } 4278 case CALLBACK_CAP_CHANGED: { 4279 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class); 4280 callback.onCapabilitiesChanged(network, cap); 4281 break; 4282 } 4283 case CALLBACK_IP_CHANGED: { 4284 LinkProperties lp = getObject(message, LinkProperties.class); 4285 callback.onLinkPropertiesChanged(network, lp); 4286 break; 4287 } 4288 case CALLBACK_SUSPENDED: { 4289 callback.onNetworkSuspended(network); 4290 break; 4291 } 4292 case CALLBACK_RESUMED: { 4293 callback.onNetworkResumed(network); 4294 break; 4295 } 4296 case CALLBACK_BLK_CHANGED: { 4297 callback.onBlockedStatusChanged(network, message.arg1); 4298 } 4299 } 4300 } 4301 getObject(Message msg, Class<T> c)4302 private <T> T getObject(Message msg, Class<T> c) { 4303 return (T) msg.getData().getParcelable(c.getSimpleName()); 4304 } 4305 } 4306 getDefaultHandler()4307 private CallbackHandler getDefaultHandler() { 4308 synchronized (sCallbacks) { 4309 if (sCallbackHandler == null) { 4310 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper()); 4311 } 4312 return sCallbackHandler; 4313 } 4314 } 4315 4316 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>(); 4317 private static CallbackHandler sCallbackHandler; 4318 sendRequestForNetwork(int asUid, NetworkCapabilities need, NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler)4319 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need, 4320 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType, 4321 CallbackHandler handler) { 4322 printStackTrace(); 4323 checkCallbackNotNull(callback); 4324 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) { 4325 throw new IllegalArgumentException("null NetworkCapabilities"); 4326 } 4327 final NetworkRequest request; 4328 final String callingPackageName = mContext.getOpPackageName(); 4329 try { 4330 synchronized(sCallbacks) { 4331 if (callback.networkRequest != null 4332 && callback.networkRequest != ALREADY_UNREGISTERED) { 4333 // TODO: throw exception instead and enforce 1:1 mapping of callbacks 4334 // and requests (http://b/20701525). 4335 Log.e(TAG, "NetworkCallback was already registered"); 4336 } 4337 Messenger messenger = new Messenger(handler); 4338 Binder binder = new Binder(); 4339 final int callbackFlags = callback.mFlags; 4340 if (reqType == LISTEN) { 4341 request = mService.listenForNetwork( 4342 need, messenger, binder, callbackFlags, callingPackageName, 4343 getAttributionTag()); 4344 } else { 4345 request = mService.requestNetwork( 4346 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder, 4347 legacyType, callbackFlags, callingPackageName, getAttributionTag()); 4348 } 4349 if (request != null) { 4350 sCallbacks.put(request, callback); 4351 } 4352 callback.networkRequest = request; 4353 } 4354 } catch (RemoteException e) { 4355 throw e.rethrowFromSystemServer(); 4356 } catch (ServiceSpecificException e) { 4357 throw convertServiceException(e); 4358 } 4359 return request; 4360 } 4361 sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler)4362 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback, 4363 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) { 4364 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType, 4365 legacyType, handler); 4366 } 4367 4368 /** 4369 * Helper function to request a network with a particular legacy type. 4370 * 4371 * This API is only for use in internal system code that requests networks with legacy type and 4372 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use 4373 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead. 4374 * 4375 * @param request {@link NetworkRequest} describing this request. 4376 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network 4377 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must 4378 * be a positive value (i.e. >0). 4379 * @param legacyType to specify the network type(#TYPE_*). 4380 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked. 4381 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note 4382 * the callback must not be shared - it uniquely specifies this request. 4383 * 4384 * @hide 4385 */ 4386 @SystemApi 4387 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK) requestNetwork(@onNull NetworkRequest request, int timeoutMs, int legacyType, @NonNull Handler handler, @NonNull NetworkCallback networkCallback)4388 public void requestNetwork(@NonNull NetworkRequest request, 4389 int timeoutMs, int legacyType, @NonNull Handler handler, 4390 @NonNull NetworkCallback networkCallback) { 4391 if (legacyType == TYPE_NONE) { 4392 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type"); 4393 } 4394 CallbackHandler cbHandler = new CallbackHandler(handler); 4395 NetworkCapabilities nc = request.networkCapabilities; 4396 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler); 4397 } 4398 4399 /** 4400 * Request a network to satisfy a set of {@link NetworkCapabilities}. 4401 * 4402 * <p>This method will attempt to find the best network that matches the passed 4403 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the 4404 * criteria. The platform will evaluate which network is the best at its own discretion. 4405 * Throughput, latency, cost per byte, policy, user preference and other considerations 4406 * may be factored in the decision of what is considered the best network. 4407 * 4408 * <p>As long as this request is outstanding, the platform will try to maintain the best network 4409 * matching this request, while always attempting to match the request to a better network if 4410 * possible. If a better match is found, the platform will switch this request to the now-best 4411 * network and inform the app of the newly best network by invoking 4412 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform 4413 * will not try to maintain any other network than the best one currently matching the request: 4414 * a network not matching any network request may be disconnected at any time. 4415 * 4416 * <p>For example, an application could use this method to obtain a connected cellular network 4417 * even if the device currently has a data connection over Ethernet. This may cause the cellular 4418 * radio to consume additional power. Or, an application could inform the system that it wants 4419 * a network supporting sending MMSes and have the system let it know about the currently best 4420 * MMS-supporting network through the provided {@link NetworkCallback}. 4421 * 4422 * <p>The status of the request can be followed by listening to the various callbacks described 4423 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be 4424 * used to direct traffic to the network (although accessing some networks may be subject to 4425 * holding specific permissions). Callers will learn about the specific characteristics of the 4426 * network through 4427 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and 4428 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the 4429 * provided {@link NetworkCallback} will only be invoked due to changes in the best network 4430 * matching the request at any given time; therefore when a better network matching the request 4431 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called 4432 * with the new network after which no further updates are given about the previously-best 4433 * network, unless it becomes the best again at some later time. All callbacks are invoked 4434 * in order on the same thread, which by default is a thread created by the framework running 4435 * in the app. 4436 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the 4437 * callbacks are invoked. 4438 * 4439 * <p>This{@link NetworkRequest} will live until released via 4440 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at 4441 * which point the system may let go of the network at any time. 4442 * 4443 * <p>A version of this method which takes a timeout is 4444 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only 4445 * wait for a limited amount of time for the network to become unavailable. 4446 * 4447 * <p>It is presently unsupported to request a network with mutable 4448 * {@link NetworkCapabilities} such as 4449 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or 4450 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL} 4451 * as these {@code NetworkCapabilities} represent states that a particular 4452 * network may never attain, and whether a network will attain these states 4453 * is unknown prior to bringing up the network so the framework does not 4454 * know how to go about satisfying a request with these capabilities. 4455 * 4456 * <p>This method requires the caller to hold either the 4457 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission 4458 * or the ability to modify system settings as determined by 4459 * {@link android.provider.Settings.System#canWrite}.</p> 4460 * 4461 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 4462 * number of outstanding requests to 100 per app (identified by their UID), shared with 4463 * all variants of this method, of {@link #registerNetworkCallback} as well as 4464 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 4465 * Requesting a network with this method will count toward this limit. If this limit is 4466 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 4467 * make sure to unregister the callbacks with 4468 * {@link #unregisterNetworkCallback(NetworkCallback)}. 4469 * 4470 * @param request {@link NetworkRequest} describing this request. 4471 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note 4472 * the callback must not be shared - it uniquely specifies this request. 4473 * The callback is invoked on the default internal Handler. 4474 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities. 4475 * @throws SecurityException if missing the appropriate permissions. 4476 * @throws RuntimeException if the app already has too many callbacks registered. 4477 */ requestNetwork(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback)4478 public void requestNetwork(@NonNull NetworkRequest request, 4479 @NonNull NetworkCallback networkCallback) { 4480 requestNetwork(request, networkCallback, getDefaultHandler()); 4481 } 4482 4483 /** 4484 * Request a network to satisfy a set of {@link NetworkCapabilities}. 4485 * 4486 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)} 4487 * but runs all the callbacks on the passed Handler. 4488 * 4489 * <p>This method has the same permission requirements as 4490 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations, 4491 * and throws the same exceptions in the same conditions. 4492 * 4493 * @param request {@link NetworkRequest} describing this request. 4494 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note 4495 * the callback must not be shared - it uniquely specifies this request. 4496 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked. 4497 */ requestNetwork(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback, @NonNull Handler handler)4498 public void requestNetwork(@NonNull NetworkRequest request, 4499 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) { 4500 CallbackHandler cbHandler = new CallbackHandler(handler); 4501 NetworkCapabilities nc = request.networkCapabilities; 4502 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler); 4503 } 4504 4505 /** 4506 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited 4507 * by a timeout. 4508 * 4509 * This function behaves identically to the non-timed-out version 4510 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network 4511 * is not found within the given time (in milliseconds) the 4512 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be 4513 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does 4514 * not have to be released if timed-out (it is automatically released). Unregistering a 4515 * request that timed out is not an error. 4516 * 4517 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small 4518 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided 4519 * for that purpose. Calling this method will attempt to bring up the requested network. 4520 * 4521 * <p>This method has the same permission requirements as 4522 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations, 4523 * and throws the same exceptions in the same conditions. 4524 * 4525 * @param request {@link NetworkRequest} describing this request. 4526 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note 4527 * the callback must not be shared - it uniquely specifies this request. 4528 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network 4529 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must 4530 * be a positive value (i.e. >0). 4531 */ requestNetwork(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback, int timeoutMs)4532 public void requestNetwork(@NonNull NetworkRequest request, 4533 @NonNull NetworkCallback networkCallback, int timeoutMs) { 4534 checkTimeout(timeoutMs); 4535 NetworkCapabilities nc = request.networkCapabilities; 4536 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, 4537 getDefaultHandler()); 4538 } 4539 4540 /** 4541 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited 4542 * by a timeout. 4543 * 4544 * This method behaves identically to 4545 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks 4546 * on the passed Handler. 4547 * 4548 * <p>This method has the same permission requirements as 4549 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations, 4550 * and throws the same exceptions in the same conditions. 4551 * 4552 * @param request {@link NetworkRequest} describing this request. 4553 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note 4554 * the callback must not be shared - it uniquely specifies this request. 4555 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked. 4556 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network 4557 * before {@link NetworkCallback#onUnavailable} is called. 4558 */ requestNetwork(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs)4559 public void requestNetwork(@NonNull NetworkRequest request, 4560 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) { 4561 checkTimeout(timeoutMs); 4562 CallbackHandler cbHandler = new CallbackHandler(handler); 4563 NetworkCapabilities nc = request.networkCapabilities; 4564 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler); 4565 } 4566 4567 /** 4568 * The lookup key for a {@link Network} object included with the intent after 4569 * successfully finding a network for the applications request. Retrieve it with 4570 * {@link android.content.Intent#getParcelableExtra(String)}. 4571 * <p> 4572 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)} 4573 * then you must get a ConnectivityManager instance before doing so. 4574 */ 4575 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK"; 4576 4577 /** 4578 * The lookup key for a {@link NetworkRequest} object included with the intent after 4579 * successfully finding a network for the applications request. Retrieve it with 4580 * {@link android.content.Intent#getParcelableExtra(String)}. 4581 */ 4582 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST"; 4583 4584 4585 /** 4586 * Request a network to satisfy a set of {@link NetworkCapabilities}. 4587 * 4588 * This function behaves identically to the version that takes a NetworkCallback, but instead 4589 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means 4590 * the request may outlive the calling application and get called back when a suitable 4591 * network is found. 4592 * <p> 4593 * The operation is an Intent broadcast that goes to a broadcast receiver that 4594 * you registered with {@link Context#registerReceiver} or through the 4595 * <receiver> tag in an AndroidManifest.xml file 4596 * <p> 4597 * The operation Intent is delivered with two extras, a {@link Network} typed 4598 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest} 4599 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing 4600 * the original requests parameters. It is important to create a new, 4601 * {@link NetworkCallback} based request before completing the processing of the 4602 * Intent to reserve the network or it will be released shortly after the Intent 4603 * is processed. 4604 * <p> 4605 * If there is already a request for this Intent registered (with the equality of 4606 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and 4607 * replaced by this one, effectively releasing the previous {@link NetworkRequest}. 4608 * <p> 4609 * The request may be released normally by calling 4610 * {@link #releaseNetworkRequest(android.app.PendingIntent)}. 4611 * <p>It is presently unsupported to request a network with either 4612 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or 4613 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL} 4614 * as these {@code NetworkCapabilities} represent states that a particular 4615 * network may never attain, and whether a network will attain these states 4616 * is unknown prior to bringing up the network so the framework does not 4617 * know how to go about satisfying a request with these capabilities. 4618 * 4619 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 4620 * number of outstanding requests to 100 per app (identified by their UID), shared with 4621 * all variants of this method, of {@link #registerNetworkCallback} as well as 4622 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 4623 * Requesting a network with this method will count toward this limit. If this limit is 4624 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 4625 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)} 4626 * or {@link #releaseNetworkRequest(PendingIntent)}. 4627 * 4628 * <p>This method requires the caller to hold either the 4629 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission 4630 * or the ability to modify system settings as determined by 4631 * {@link android.provider.Settings.System#canWrite}.</p> 4632 * 4633 * @param request {@link NetworkRequest} describing this request. 4634 * @param operation Action to perform when the network is available (corresponds 4635 * to the {@link NetworkCallback#onAvailable} call. Typically 4636 * comes from {@link PendingIntent#getBroadcast}. Cannot be null. 4637 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities. 4638 * @throws SecurityException if missing the appropriate permissions. 4639 * @throws RuntimeException if the app already has too many callbacks registered. 4640 */ requestNetwork(@onNull NetworkRequest request, @NonNull PendingIntent operation)4641 public void requestNetwork(@NonNull NetworkRequest request, 4642 @NonNull PendingIntent operation) { 4643 printStackTrace(); 4644 checkPendingIntentNotNull(operation); 4645 try { 4646 mService.pendingRequestForNetwork( 4647 request.networkCapabilities, operation, mContext.getOpPackageName(), 4648 getAttributionTag()); 4649 } catch (RemoteException e) { 4650 throw e.rethrowFromSystemServer(); 4651 } catch (ServiceSpecificException e) { 4652 throw convertServiceException(e); 4653 } 4654 } 4655 4656 /** 4657 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} 4658 * <p> 4659 * This method has the same behavior as 4660 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to 4661 * releasing network resources and disconnecting. 4662 * 4663 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the 4664 * PendingIntent passed to 4665 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the 4666 * corresponding NetworkRequest you'd like to remove. Cannot be null. 4667 */ releaseNetworkRequest(@onNull PendingIntent operation)4668 public void releaseNetworkRequest(@NonNull PendingIntent operation) { 4669 printStackTrace(); 4670 checkPendingIntentNotNull(operation); 4671 try { 4672 mService.releasePendingNetworkRequest(operation); 4673 } catch (RemoteException e) { 4674 throw e.rethrowFromSystemServer(); 4675 } 4676 } 4677 checkPendingIntentNotNull(PendingIntent intent)4678 private static void checkPendingIntentNotNull(PendingIntent intent) { 4679 Objects.requireNonNull(intent, "PendingIntent cannot be null."); 4680 } 4681 checkCallbackNotNull(NetworkCallback callback)4682 private static void checkCallbackNotNull(NetworkCallback callback) { 4683 Objects.requireNonNull(callback, "null NetworkCallback"); 4684 } 4685 checkTimeout(int timeoutMs)4686 private static void checkTimeout(int timeoutMs) { 4687 if (timeoutMs <= 0) { 4688 throw new IllegalArgumentException("timeoutMs must be strictly positive."); 4689 } 4690 } 4691 4692 /** 4693 * Registers to receive notifications about all networks which satisfy the given 4694 * {@link NetworkRequest}. The callbacks will continue to be called until 4695 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is 4696 * called. 4697 * 4698 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 4699 * number of outstanding requests to 100 per app (identified by their UID), shared with 4700 * all variants of this method, of {@link #requestNetwork} as well as 4701 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 4702 * Requesting a network with this method will count toward this limit. If this limit is 4703 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 4704 * make sure to unregister the callbacks with 4705 * {@link #unregisterNetworkCallback(NetworkCallback)}. 4706 * 4707 * @param request {@link NetworkRequest} describing this request. 4708 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable 4709 * networks change state. 4710 * The callback is invoked on the default internal Handler. 4711 * @throws RuntimeException if the app already has too many callbacks registered. 4712 */ 4713 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) registerNetworkCallback(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback)4714 public void registerNetworkCallback(@NonNull NetworkRequest request, 4715 @NonNull NetworkCallback networkCallback) { 4716 registerNetworkCallback(request, networkCallback, getDefaultHandler()); 4717 } 4718 4719 /** 4720 * Registers to receive notifications about all networks which satisfy the given 4721 * {@link NetworkRequest}. The callbacks will continue to be called until 4722 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is 4723 * called. 4724 * 4725 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 4726 * number of outstanding requests to 100 per app (identified by their UID), shared with 4727 * all variants of this method, of {@link #requestNetwork} as well as 4728 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 4729 * Requesting a network with this method will count toward this limit. If this limit is 4730 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 4731 * make sure to unregister the callbacks with 4732 * {@link #unregisterNetworkCallback(NetworkCallback)}. 4733 * 4734 * 4735 * @param request {@link NetworkRequest} describing this request. 4736 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable 4737 * networks change state. 4738 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked. 4739 * @throws RuntimeException if the app already has too many callbacks registered. 4740 */ 4741 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) registerNetworkCallback(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback, @NonNull Handler handler)4742 public void registerNetworkCallback(@NonNull NetworkRequest request, 4743 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) { 4744 CallbackHandler cbHandler = new CallbackHandler(handler); 4745 NetworkCapabilities nc = request.networkCapabilities; 4746 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler); 4747 } 4748 4749 /** 4750 * Registers a PendingIntent to be sent when a network is available which satisfies the given 4751 * {@link NetworkRequest}. 4752 * 4753 * This function behaves identically to the version that takes a NetworkCallback, but instead 4754 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means 4755 * the request may outlive the calling application and get called back when a suitable 4756 * network is found. 4757 * <p> 4758 * The operation is an Intent broadcast that goes to a broadcast receiver that 4759 * you registered with {@link Context#registerReceiver} or through the 4760 * <receiver> tag in an AndroidManifest.xml file 4761 * <p> 4762 * The operation Intent is delivered with two extras, a {@link Network} typed 4763 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest} 4764 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing 4765 * the original requests parameters. 4766 * <p> 4767 * If there is already a request for this Intent registered (with the equality of 4768 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and 4769 * replaced by this one, effectively releasing the previous {@link NetworkRequest}. 4770 * <p> 4771 * The request may be released normally by calling 4772 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}. 4773 * 4774 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 4775 * number of outstanding requests to 100 per app (identified by their UID), shared with 4776 * all variants of this method, of {@link #requestNetwork} as well as 4777 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 4778 * Requesting a network with this method will count toward this limit. If this limit is 4779 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 4780 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)} 4781 * or {@link #releaseNetworkRequest(PendingIntent)}. 4782 * 4783 * @param request {@link NetworkRequest} describing this request. 4784 * @param operation Action to perform when the network is available (corresponds 4785 * to the {@link NetworkCallback#onAvailable} call. Typically 4786 * comes from {@link PendingIntent#getBroadcast}. Cannot be null. 4787 * @throws RuntimeException if the app already has too many callbacks registered. 4788 */ 4789 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) registerNetworkCallback(@onNull NetworkRequest request, @NonNull PendingIntent operation)4790 public void registerNetworkCallback(@NonNull NetworkRequest request, 4791 @NonNull PendingIntent operation) { 4792 printStackTrace(); 4793 checkPendingIntentNotNull(operation); 4794 try { 4795 mService.pendingListenForNetwork( 4796 request.networkCapabilities, operation, mContext.getOpPackageName(), 4797 getAttributionTag()); 4798 } catch (RemoteException e) { 4799 throw e.rethrowFromSystemServer(); 4800 } catch (ServiceSpecificException e) { 4801 throw convertServiceException(e); 4802 } 4803 } 4804 4805 /** 4806 * Registers to receive notifications about changes in the application's default network. This 4807 * may be a physical network or a virtual network, such as a VPN that applies to the 4808 * application. The callbacks will continue to be called until either the application exits or 4809 * {@link #unregisterNetworkCallback(NetworkCallback)} is called. 4810 * 4811 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 4812 * number of outstanding requests to 100 per app (identified by their UID), shared with 4813 * all variants of this method, of {@link #requestNetwork} as well as 4814 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 4815 * Requesting a network with this method will count toward this limit. If this limit is 4816 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 4817 * make sure to unregister the callbacks with 4818 * {@link #unregisterNetworkCallback(NetworkCallback)}. 4819 * 4820 * @param networkCallback The {@link NetworkCallback} that the system will call as the 4821 * application's default network changes. 4822 * The callback is invoked on the default internal Handler. 4823 * @throws RuntimeException if the app already has too many callbacks registered. 4824 */ 4825 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) registerDefaultNetworkCallback(@onNull NetworkCallback networkCallback)4826 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) { 4827 registerDefaultNetworkCallback(networkCallback, getDefaultHandler()); 4828 } 4829 4830 /** 4831 * Registers to receive notifications about changes in the application's default network. This 4832 * may be a physical network or a virtual network, such as a VPN that applies to the 4833 * application. The callbacks will continue to be called until either the application exits or 4834 * {@link #unregisterNetworkCallback(NetworkCallback)} is called. 4835 * 4836 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 4837 * number of outstanding requests to 100 per app (identified by their UID), shared with 4838 * all variants of this method, of {@link #requestNetwork} as well as 4839 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 4840 * Requesting a network with this method will count toward this limit. If this limit is 4841 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 4842 * make sure to unregister the callbacks with 4843 * {@link #unregisterNetworkCallback(NetworkCallback)}. 4844 * 4845 * @param networkCallback The {@link NetworkCallback} that the system will call as the 4846 * application's default network changes. 4847 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked. 4848 * @throws RuntimeException if the app already has too many callbacks registered. 4849 */ 4850 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) registerDefaultNetworkCallback(@onNull NetworkCallback networkCallback, @NonNull Handler handler)4851 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback, 4852 @NonNull Handler handler) { 4853 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler); 4854 } 4855 4856 /** 4857 * Registers to receive notifications about changes in the default network for the specified 4858 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the 4859 * UID. The callbacks will continue to be called until either the application exits or 4860 * {@link #unregisterNetworkCallback(NetworkCallback)} is called. 4861 * 4862 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 4863 * number of outstanding requests to 100 per app (identified by their UID), shared with 4864 * all variants of this method, of {@link #requestNetwork} as well as 4865 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 4866 * Requesting a network with this method will count toward this limit. If this limit is 4867 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 4868 * make sure to unregister the callbacks with 4869 * {@link #unregisterNetworkCallback(NetworkCallback)}. 4870 * 4871 * @param uid the UID for which to track default network changes. 4872 * @param networkCallback The {@link NetworkCallback} that the system will call as the 4873 * UID's default network changes. 4874 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked. 4875 * @throws RuntimeException if the app already has too many callbacks registered. 4876 * @hide 4877 */ 4878 @SystemApi(client = MODULE_LIBRARIES) 4879 @SuppressLint({"ExecutorRegistration", "PairedRegistration"}) 4880 @RequiresPermission(anyOf = { 4881 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 4882 android.Manifest.permission.NETWORK_SETTINGS}) registerDefaultNetworkCallbackForUid(int uid, @NonNull NetworkCallback networkCallback, @NonNull Handler handler)4883 public void registerDefaultNetworkCallbackForUid(int uid, 4884 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) { 4885 CallbackHandler cbHandler = new CallbackHandler(handler); 4886 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */, 4887 TRACK_DEFAULT, TYPE_NONE, cbHandler); 4888 } 4889 4890 /** 4891 * Registers to receive notifications about changes in the system default network. The callbacks 4892 * will continue to be called until either the application exits or 4893 * {@link #unregisterNetworkCallback(NetworkCallback)} is called. 4894 * 4895 * This method should not be used to determine networking state seen by applications, because in 4896 * many cases, most or even all application traffic may not use the default network directly, 4897 * and traffic from different applications may go on different networks by default. As an 4898 * example, if a VPN is connected, traffic from all applications might be sent through the VPN 4899 * and not onto the system default network. Applications or system components desiring to do 4900 * determine network state as seen by applications should use other methods such as 4901 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}. 4902 * 4903 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 4904 * number of outstanding requests to 100 per app (identified by their UID), shared with 4905 * all variants of this method, of {@link #requestNetwork} as well as 4906 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 4907 * Requesting a network with this method will count toward this limit. If this limit is 4908 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 4909 * make sure to unregister the callbacks with 4910 * {@link #unregisterNetworkCallback(NetworkCallback)}. 4911 * 4912 * @param networkCallback The {@link NetworkCallback} that the system will call as the 4913 * system default network changes. 4914 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked. 4915 * @throws RuntimeException if the app already has too many callbacks registered. 4916 * 4917 * @hide 4918 */ 4919 @SystemApi(client = MODULE_LIBRARIES) 4920 @SuppressLint({"ExecutorRegistration", "PairedRegistration"}) 4921 @RequiresPermission(anyOf = { 4922 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 4923 android.Manifest.permission.NETWORK_SETTINGS, 4924 android.Manifest.permission.NETWORK_SETUP_WIZARD, 4925 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS}) registerSystemDefaultNetworkCallback(@onNull NetworkCallback networkCallback, @NonNull Handler handler)4926 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback, 4927 @NonNull Handler handler) { 4928 CallbackHandler cbHandler = new CallbackHandler(handler); 4929 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0, 4930 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler); 4931 } 4932 4933 /** 4934 * Registers to receive notifications about the best matching network which satisfy the given 4935 * {@link NetworkRequest}. The callbacks will continue to be called until 4936 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is 4937 * called. 4938 * 4939 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 4940 * number of outstanding requests to 100 per app (identified by their UID), shared with 4941 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as 4942 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 4943 * Requesting a network with this method will count toward this limit. If this limit is 4944 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 4945 * make sure to unregister the callbacks with 4946 * {@link #unregisterNetworkCallback(NetworkCallback)}. 4947 * 4948 * 4949 * @param request {@link NetworkRequest} describing this request. 4950 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable 4951 * networks change state. 4952 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked. 4953 * @throws RuntimeException if the app already has too many callbacks registered. 4954 */ 4955 @SuppressLint("ExecutorRegistration") registerBestMatchingNetworkCallback(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback, @NonNull Handler handler)4956 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request, 4957 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) { 4958 final NetworkCapabilities nc = request.networkCapabilities; 4959 final CallbackHandler cbHandler = new CallbackHandler(handler); 4960 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler); 4961 } 4962 4963 /** 4964 * Requests bandwidth update for a given {@link Network} and returns whether the update request 4965 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying 4966 * network connection for updated bandwidth information. The caller will be notified via 4967 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this 4968 * method assumes that the caller has previously called 4969 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network 4970 * changes. 4971 * 4972 * @param network {@link Network} specifying which network you're interested. 4973 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid. 4974 */ requestBandwidthUpdate(@onNull Network network)4975 public boolean requestBandwidthUpdate(@NonNull Network network) { 4976 try { 4977 return mService.requestBandwidthUpdate(network); 4978 } catch (RemoteException e) { 4979 throw e.rethrowFromSystemServer(); 4980 } 4981 } 4982 4983 /** 4984 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from 4985 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and 4986 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls. 4987 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork}, 4988 * any networks that the device brought up only to satisfy that request will be disconnected. 4989 * 4990 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop 4991 * triggering it as soon as this call returns. 4992 * 4993 * @param networkCallback The {@link NetworkCallback} used when making the request. 4994 */ unregisterNetworkCallback(@onNull NetworkCallback networkCallback)4995 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) { 4996 printStackTrace(); 4997 checkCallbackNotNull(networkCallback); 4998 final List<NetworkRequest> reqs = new ArrayList<>(); 4999 // Find all requests associated to this callback and stop callback triggers immediately. 5000 // Callback is reusable immediately. http://b/20701525, http://b/35921499. 5001 synchronized (sCallbacks) { 5002 if (networkCallback.networkRequest == null) { 5003 throw new IllegalArgumentException("NetworkCallback was not registered"); 5004 } 5005 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) { 5006 Log.d(TAG, "NetworkCallback was already unregistered"); 5007 return; 5008 } 5009 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) { 5010 if (e.getValue() == networkCallback) { 5011 reqs.add(e.getKey()); 5012 } 5013 } 5014 // TODO: throw exception if callback was registered more than once (http://b/20701525). 5015 for (NetworkRequest r : reqs) { 5016 try { 5017 mService.releaseNetworkRequest(r); 5018 } catch (RemoteException e) { 5019 throw e.rethrowFromSystemServer(); 5020 } 5021 // Only remove mapping if rpc was successful. 5022 sCallbacks.remove(r); 5023 } 5024 networkCallback.networkRequest = ALREADY_UNREGISTERED; 5025 } 5026 } 5027 5028 /** 5029 * Unregisters a callback previously registered via 5030 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}. 5031 * 5032 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the 5033 * PendingIntent passed to 5034 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}. 5035 * Cannot be null. 5036 */ unregisterNetworkCallback(@onNull PendingIntent operation)5037 public void unregisterNetworkCallback(@NonNull PendingIntent operation) { 5038 releaseNetworkRequest(operation); 5039 } 5040 5041 /** 5042 * Informs the system whether it should switch to {@code network} regardless of whether it is 5043 * validated or not. If {@code accept} is true, and the network was explicitly selected by the 5044 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become 5045 * the system default network regardless of any other network that's currently connected. If 5046 * {@code always} is true, then the choice is remembered, so that the next time the user 5047 * connects to this network, the system will switch to it. 5048 * 5049 * @param network The network to accept. 5050 * @param accept Whether to accept the network even if unvalidated. 5051 * @param always Whether to remember this choice in the future. 5052 * 5053 * @hide 5054 */ 5055 @SystemApi(client = MODULE_LIBRARIES) 5056 @RequiresPermission(anyOf = { 5057 android.Manifest.permission.NETWORK_SETTINGS, 5058 android.Manifest.permission.NETWORK_SETUP_WIZARD, 5059 android.Manifest.permission.NETWORK_STACK, 5060 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) setAcceptUnvalidated(@onNull Network network, boolean accept, boolean always)5061 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) { 5062 try { 5063 mService.setAcceptUnvalidated(network, accept, always); 5064 } catch (RemoteException e) { 5065 throw e.rethrowFromSystemServer(); 5066 } 5067 } 5068 5069 /** 5070 * Informs the system whether it should consider the network as validated even if it only has 5071 * partial connectivity. If {@code accept} is true, then the network will be considered as 5072 * validated even if connectivity is only partial. If {@code always} is true, then the choice 5073 * is remembered, so that the next time the user connects to this network, the system will 5074 * switch to it. 5075 * 5076 * @param network The network to accept. 5077 * @param accept Whether to consider the network as validated even if it has partial 5078 * connectivity. 5079 * @param always Whether to remember this choice in the future. 5080 * 5081 * @hide 5082 */ 5083 @SystemApi(client = MODULE_LIBRARIES) 5084 @RequiresPermission(anyOf = { 5085 android.Manifest.permission.NETWORK_SETTINGS, 5086 android.Manifest.permission.NETWORK_SETUP_WIZARD, 5087 android.Manifest.permission.NETWORK_STACK, 5088 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) setAcceptPartialConnectivity(@onNull Network network, boolean accept, boolean always)5089 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept, 5090 boolean always) { 5091 try { 5092 mService.setAcceptPartialConnectivity(network, accept, always); 5093 } catch (RemoteException e) { 5094 throw e.rethrowFromSystemServer(); 5095 } 5096 } 5097 5098 /** 5099 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is 5100 * only meaningful if the system is configured not to penalize such networks, e.g., if the 5101 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code 5102 * NETWORK_AVOID_BAD_WIFI setting is unset}. 5103 * 5104 * @param network The network to accept. 5105 * 5106 * @hide 5107 */ 5108 @SystemApi(client = MODULE_LIBRARIES) 5109 @RequiresPermission(anyOf = { 5110 android.Manifest.permission.NETWORK_SETTINGS, 5111 android.Manifest.permission.NETWORK_SETUP_WIZARD, 5112 android.Manifest.permission.NETWORK_STACK, 5113 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) setAvoidUnvalidated(@onNull Network network)5114 public void setAvoidUnvalidated(@NonNull Network network) { 5115 try { 5116 mService.setAvoidUnvalidated(network); 5117 } catch (RemoteException e) { 5118 throw e.rethrowFromSystemServer(); 5119 } 5120 } 5121 5122 /** 5123 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration. 5124 * 5125 * @param timeMs The expired current time. The value should be set within a limited time from 5126 * now. 5127 * 5128 * @hide 5129 */ setTestAllowBadWifiUntil(long timeMs)5130 public void setTestAllowBadWifiUntil(long timeMs) { 5131 try { 5132 mService.setTestAllowBadWifiUntil(timeMs); 5133 } catch (RemoteException e) { 5134 throw e.rethrowFromSystemServer(); 5135 } 5136 } 5137 5138 /** 5139 * Requests that the system open the captive portal app on the specified network. 5140 * 5141 * <p>This is to be used on networks where a captive portal was detected, as per 5142 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}. 5143 * 5144 * @param network The network to log into. 5145 * 5146 * @hide 5147 */ 5148 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 5149 @RequiresPermission(anyOf = { 5150 android.Manifest.permission.NETWORK_SETTINGS, 5151 android.Manifest.permission.NETWORK_STACK, 5152 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 5153 }) startCaptivePortalApp(@onNull Network network)5154 public void startCaptivePortalApp(@NonNull Network network) { 5155 try { 5156 mService.startCaptivePortalApp(network); 5157 } catch (RemoteException e) { 5158 throw e.rethrowFromSystemServer(); 5159 } 5160 } 5161 5162 /** 5163 * Requests that the system open the captive portal app with the specified extras. 5164 * 5165 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the 5166 * corresponding permission. 5167 * @param network Network on which the captive portal was detected. 5168 * @param appExtras Extras to include in the app start intent. 5169 * @hide 5170 */ 5171 @SystemApi 5172 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK) startCaptivePortalApp(@onNull Network network, @NonNull Bundle appExtras)5173 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) { 5174 try { 5175 mService.startCaptivePortalAppInternal(network, appExtras); 5176 } catch (RemoteException e) { 5177 throw e.rethrowFromSystemServer(); 5178 } 5179 } 5180 5181 /** 5182 * Determine whether the device is configured to avoid bad Wi-Fi. 5183 * @hide 5184 */ 5185 @SystemApi 5186 @RequiresPermission(anyOf = { 5187 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, 5188 android.Manifest.permission.NETWORK_STACK}) shouldAvoidBadWifi()5189 public boolean shouldAvoidBadWifi() { 5190 try { 5191 return mService.shouldAvoidBadWifi(); 5192 } catch (RemoteException e) { 5193 throw e.rethrowFromSystemServer(); 5194 } 5195 } 5196 5197 /** 5198 * It is acceptable to briefly use multipath data to provide seamless connectivity for 5199 * time-sensitive user-facing operations when the system default network is temporarily 5200 * unresponsive. The amount of data should be limited (less than one megabyte for every call to 5201 * this method), and the operation should be infrequent to ensure that data usage is limited. 5202 * 5203 * An example of such an operation might be a time-sensitive foreground activity, such as a 5204 * voice command, that the user is performing while walking out of range of a Wi-Fi network. 5205 */ 5206 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0; 5207 5208 /** 5209 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide 5210 * a backup channel for traffic that is primarily going over another network. 5211 * 5212 * An example might be maintaining backup connections to peers or servers for the purpose of 5213 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic 5214 * on backup paths should be negligible compared to the traffic on the main path. 5215 */ 5216 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1; 5217 5218 /** 5219 * It is acceptable to use metered data to improve network latency and performance. 5220 */ 5221 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2; 5222 5223 /** 5224 * Return value to use for unmetered networks. On such networks we currently set all the flags 5225 * to true. 5226 * @hide 5227 */ 5228 public static final int MULTIPATH_PREFERENCE_UNMETERED = 5229 MULTIPATH_PREFERENCE_HANDOVER | 5230 MULTIPATH_PREFERENCE_RELIABILITY | 5231 MULTIPATH_PREFERENCE_PERFORMANCE; 5232 5233 /** @hide */ 5234 @Retention(RetentionPolicy.SOURCE) 5235 @IntDef(flag = true, value = { 5236 MULTIPATH_PREFERENCE_HANDOVER, 5237 MULTIPATH_PREFERENCE_RELIABILITY, 5238 MULTIPATH_PREFERENCE_PERFORMANCE, 5239 }) 5240 public @interface MultipathPreference { 5241 } 5242 5243 /** 5244 * Provides a hint to the calling application on whether it is desirable to use the 5245 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.) 5246 * for multipath data transfer on this network when it is not the system default network. 5247 * Applications desiring to use multipath network protocols should call this method before 5248 * each such operation. 5249 * 5250 * @param network The network on which the application desires to use multipath data. 5251 * If {@code null}, this method will return a preference that will generally 5252 * apply to metered networks. 5253 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants. 5254 */ 5255 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) getMultipathPreference(@ullable Network network)5256 public @MultipathPreference int getMultipathPreference(@Nullable Network network) { 5257 try { 5258 return mService.getMultipathPreference(network); 5259 } catch (RemoteException e) { 5260 throw e.rethrowFromSystemServer(); 5261 } 5262 } 5263 5264 /** 5265 * Resets all connectivity manager settings back to factory defaults. 5266 * @hide 5267 */ 5268 @SystemApi(client = MODULE_LIBRARIES) 5269 @RequiresPermission(anyOf = { 5270 android.Manifest.permission.NETWORK_SETTINGS, 5271 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) factoryReset()5272 public void factoryReset() { 5273 try { 5274 mService.factoryReset(); 5275 getTetheringManager().stopAllTethering(); 5276 } catch (RemoteException e) { 5277 throw e.rethrowFromSystemServer(); 5278 } 5279 } 5280 5281 /** 5282 * Binds the current process to {@code network}. All Sockets created in the future 5283 * (and not explicitly bound via a bound SocketFactory from 5284 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to 5285 * {@code network}. All host name resolutions will be limited to {@code network} as well. 5286 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to 5287 * work and all host name resolutions will fail. This is by design so an application doesn't 5288 * accidentally use Sockets it thinks are still bound to a particular {@link Network}. 5289 * To clear binding pass {@code null} for {@code network}. Using individually bound 5290 * Sockets created by Network.getSocketFactory().createSocket() and 5291 * performing network-specific host name resolutions via 5292 * {@link Network#getAllByName Network.getAllByName} is preferred to calling 5293 * {@code bindProcessToNetwork}. 5294 * 5295 * @param network The {@link Network} to bind the current process to, or {@code null} to clear 5296 * the current binding. 5297 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid. 5298 */ bindProcessToNetwork(@ullable Network network)5299 public boolean bindProcessToNetwork(@Nullable Network network) { 5300 // Forcing callers to call through non-static function ensures ConnectivityManager 5301 // instantiated. 5302 return setProcessDefaultNetwork(network); 5303 } 5304 5305 /** 5306 * Binds the current process to {@code network}. All Sockets created in the future 5307 * (and not explicitly bound via a bound SocketFactory from 5308 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to 5309 * {@code network}. All host name resolutions will be limited to {@code network} as well. 5310 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to 5311 * work and all host name resolutions will fail. This is by design so an application doesn't 5312 * accidentally use Sockets it thinks are still bound to a particular {@link Network}. 5313 * To clear binding pass {@code null} for {@code network}. Using individually bound 5314 * Sockets created by Network.getSocketFactory().createSocket() and 5315 * performing network-specific host name resolutions via 5316 * {@link Network#getAllByName Network.getAllByName} is preferred to calling 5317 * {@code setProcessDefaultNetwork}. 5318 * 5319 * @param network The {@link Network} to bind the current process to, or {@code null} to clear 5320 * the current binding. 5321 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid. 5322 * @deprecated This function can throw {@link IllegalStateException}. Use 5323 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork} 5324 * is a direct replacement. 5325 */ 5326 @Deprecated setProcessDefaultNetwork(@ullable Network network)5327 public static boolean setProcessDefaultNetwork(@Nullable Network network) { 5328 int netId = (network == null) ? NETID_UNSET : network.netId; 5329 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess()); 5330 5331 if (netId != NETID_UNSET) { 5332 netId = network.getNetIdForResolv(); 5333 } 5334 5335 if (!NetworkUtils.bindProcessToNetwork(netId)) { 5336 return false; 5337 } 5338 5339 if (!isSameNetId) { 5340 // Set HTTP proxy system properties to match network. 5341 // TODO: Deprecate this static method and replace it with a non-static version. 5342 try { 5343 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy()); 5344 } catch (SecurityException e) { 5345 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy. 5346 Log.e(TAG, "Can't set proxy properties", e); 5347 } 5348 // Must flush DNS cache as new network may have different DNS resolutions. 5349 InetAddress.clearDnsCache(); 5350 // Must flush socket pool as idle sockets will be bound to previous network and may 5351 // cause subsequent fetches to be performed on old network. 5352 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange(); 5353 } 5354 5355 return true; 5356 } 5357 5358 /** 5359 * Returns the {@link Network} currently bound to this process via 5360 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound. 5361 * 5362 * @return {@code Network} to which this process is bound, or {@code null}. 5363 */ 5364 @Nullable getBoundNetworkForProcess()5365 public Network getBoundNetworkForProcess() { 5366 // Forcing callers to call through non-static function ensures ConnectivityManager has been 5367 // instantiated. 5368 return getProcessDefaultNetwork(); 5369 } 5370 5371 /** 5372 * Returns the {@link Network} currently bound to this process via 5373 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound. 5374 * 5375 * @return {@code Network} to which this process is bound, or {@code null}. 5376 * @deprecated Using this function can lead to other functions throwing 5377 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead. 5378 * {@code getBoundNetworkForProcess} is a direct replacement. 5379 */ 5380 @Deprecated 5381 @Nullable getProcessDefaultNetwork()5382 public static Network getProcessDefaultNetwork() { 5383 int netId = NetworkUtils.getBoundNetworkForProcess(); 5384 if (netId == NETID_UNSET) return null; 5385 return new Network(netId); 5386 } 5387 unsupportedStartingFrom(int version)5388 private void unsupportedStartingFrom(int version) { 5389 if (Process.myUid() == Process.SYSTEM_UID) { 5390 // The getApplicationInfo() call we make below is not supported in system context. Let 5391 // the call through here, and rely on the fact that ConnectivityService will refuse to 5392 // allow the system to use these APIs anyway. 5393 return; 5394 } 5395 5396 if (mContext.getApplicationInfo().targetSdkVersion >= version) { 5397 throw new UnsupportedOperationException( 5398 "This method is not supported in target SDK version " + version + " and above"); 5399 } 5400 } 5401 5402 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature, 5403 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException. 5404 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and 5405 // remove these exemptions. Note that this check is not secure, and apps can still access these 5406 // functions by accessing ConnectivityService directly. However, it should be clear that doing 5407 // so is unsupported and may break in the future. http://b/22728205 checkLegacyRoutingApiAccess()5408 private void checkLegacyRoutingApiAccess() { 5409 unsupportedStartingFrom(VERSION_CODES.M); 5410 } 5411 5412 /** 5413 * Binds host resolutions performed by this process to {@code network}. 5414 * {@link #bindProcessToNetwork} takes precedence over this setting. 5415 * 5416 * @param network The {@link Network} to bind host resolutions from the current process to, or 5417 * {@code null} to clear the current binding. 5418 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid. 5419 * @hide 5420 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}. 5421 */ 5422 @Deprecated 5423 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) setProcessDefaultNetworkForHostResolution(Network network)5424 public static boolean setProcessDefaultNetworkForHostResolution(Network network) { 5425 return NetworkUtils.bindProcessToNetworkForHostResolution( 5426 (network == null) ? NETID_UNSET : network.getNetIdForResolv()); 5427 } 5428 5429 /** 5430 * Device is not restricting metered network activity while application is running on 5431 * background. 5432 */ 5433 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1; 5434 5435 /** 5436 * Device is restricting metered network activity while application is running on background, 5437 * but application is allowed to bypass it. 5438 * <p> 5439 * In this state, application should take action to mitigate metered network access. 5440 * For example, a music streaming application should switch to a low-bandwidth bitrate. 5441 */ 5442 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2; 5443 5444 /** 5445 * Device is restricting metered network activity while application is running on background. 5446 * <p> 5447 * In this state, application should not try to use the network while running on background, 5448 * because it would be denied. 5449 */ 5450 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3; 5451 5452 /** 5453 * A change in the background metered network activity restriction has occurred. 5454 * <p> 5455 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction 5456 * applies to them. 5457 * <p> 5458 * This is only sent to registered receivers, not manifest receivers. 5459 */ 5460 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 5461 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED = 5462 "android.net.conn.RESTRICT_BACKGROUND_CHANGED"; 5463 5464 /** @hide */ 5465 @Retention(RetentionPolicy.SOURCE) 5466 @IntDef(flag = false, value = { 5467 RESTRICT_BACKGROUND_STATUS_DISABLED, 5468 RESTRICT_BACKGROUND_STATUS_WHITELISTED, 5469 RESTRICT_BACKGROUND_STATUS_ENABLED, 5470 }) 5471 public @interface RestrictBackgroundStatus { 5472 } 5473 5474 /** 5475 * Determines if the calling application is subject to metered network restrictions while 5476 * running on background. 5477 * 5478 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED}, 5479 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED}, 5480 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED} 5481 */ getRestrictBackgroundStatus()5482 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() { 5483 try { 5484 return mService.getRestrictBackgroundStatusByCaller(); 5485 } catch (RemoteException e) { 5486 throw e.rethrowFromSystemServer(); 5487 } 5488 } 5489 5490 /** 5491 * The network watchlist is a list of domains and IP addresses that are associated with 5492 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file 5493 * currently used by the system for validation purposes. 5494 * 5495 * @return Hash of network watchlist config file. Null if config does not exist. 5496 */ 5497 @Nullable getNetworkWatchlistConfigHash()5498 public byte[] getNetworkWatchlistConfigHash() { 5499 try { 5500 return mService.getNetworkWatchlistConfigHash(); 5501 } catch (RemoteException e) { 5502 Log.e(TAG, "Unable to get watchlist config hash"); 5503 throw e.rethrowFromSystemServer(); 5504 } 5505 } 5506 5507 /** 5508 * Returns the {@code uid} of the owner of a network connection. 5509 * 5510 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code 5511 * IPPROTO_UDP} currently supported. 5512 * @param local The local {@link InetSocketAddress} of a connection. 5513 * @param remote The remote {@link InetSocketAddress} of a connection. 5514 * @return {@code uid} if the connection is found and the app has permission to observe it 5515 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link 5516 * android.os.Process#INVALID_UID} if the connection is not found. 5517 * @throws SecurityException if the caller is not the active VpnService for the current 5518 * user. 5519 * @throws IllegalArgumentException if an unsupported protocol is requested. 5520 */ getConnectionOwnerUid( int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote)5521 public int getConnectionOwnerUid( 5522 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) { 5523 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote); 5524 try { 5525 return mService.getConnectionOwnerUid(connectionInfo); 5526 } catch (RemoteException e) { 5527 throw e.rethrowFromSystemServer(); 5528 } 5529 } 5530 printStackTrace()5531 private void printStackTrace() { 5532 if (DEBUG) { 5533 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace(); 5534 final StringBuffer sb = new StringBuffer(); 5535 for (int i = 3; i < callStack.length; i++) { 5536 final String stackTrace = callStack[i].toString(); 5537 if (stackTrace == null || stackTrace.contains("android.os")) { 5538 break; 5539 } 5540 sb.append(" [").append(stackTrace).append("]"); 5541 } 5542 Log.d(TAG, "StackLog:" + sb.toString()); 5543 } 5544 } 5545 5546 /** @hide */ startOrGetTestNetworkManager()5547 public TestNetworkManager startOrGetTestNetworkManager() { 5548 final IBinder tnBinder; 5549 try { 5550 tnBinder = mService.startOrGetTestNetworkService(); 5551 } catch (RemoteException e) { 5552 throw e.rethrowFromSystemServer(); 5553 } 5554 5555 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder)); 5556 } 5557 5558 /** @hide */ createDiagnosticsManager()5559 public ConnectivityDiagnosticsManager createDiagnosticsManager() { 5560 return new ConnectivityDiagnosticsManager(mContext, mService); 5561 } 5562 5563 /** 5564 * Simulates a Data Stall for the specified Network. 5565 * 5566 * <p>This method should only be used for tests. 5567 * 5568 * <p>The caller must be the owner of the specified Network. This simulates a data stall to 5569 * have the system behave as if it had happened, but does not actually stall connectivity. 5570 * 5571 * @param detectionMethod The detection method used to identify the Data Stall. 5572 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*. 5573 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per 5574 * SystemClock.elapsedRealtime. 5575 * @param network The Network for which a Data Stall is being simluated. 5576 * @param extras The PersistableBundle of extras included in the Data Stall notification. 5577 * @throws SecurityException if the caller is not the owner of the given network. 5578 * @hide 5579 */ 5580 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 5581 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS, 5582 android.Manifest.permission.NETWORK_STACK}) simulateDataStall(@etectionMethod int detectionMethod, long timestampMillis, @NonNull Network network, @NonNull PersistableBundle extras)5583 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis, 5584 @NonNull Network network, @NonNull PersistableBundle extras) { 5585 try { 5586 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras); 5587 } catch (RemoteException e) { 5588 e.rethrowFromSystemServer(); 5589 } 5590 } 5591 5592 @NonNull 5593 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>(); 5594 5595 /** 5596 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will 5597 * receive available QoS events related to the {@link Network} and local ip + port 5598 * specified within socketInfo. 5599 * <p/> 5600 * The same {@link QosCallback} must be unregistered before being registered a second time, 5601 * otherwise {@link QosCallbackRegistrationException} is thrown. 5602 * <p/> 5603 * This API does not, in itself, require any permission if called with a network that is not 5604 * restricted. However, the underlying implementation currently only supports the IMS network, 5605 * which is always restricted. That means non-preinstalled callers can't possibly find this API 5606 * useful, because they'd never be called back on networks that they would have access to. 5607 * 5608 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is 5609 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission. 5610 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered. 5611 * @throws RuntimeException if the app already has too many callbacks registered. 5612 * 5613 * Exceptions after the time of registration is passed through 5614 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}. 5615 * 5616 * @param socketInfo the socket information used to match QoS events 5617 * @param executor The executor on which the callback will be invoked. The provided 5618 * {@link Executor} must run callback sequentially, otherwise the order of 5619 * callbacks cannot be guaranteed.onQosCallbackRegistered 5620 * @param callback receives qos events that satisfy socketInfo 5621 * 5622 * @hide 5623 */ 5624 @SystemApi registerQosCallback(@onNull final QosSocketInfo socketInfo, @CallbackExecutor @NonNull final Executor executor, @NonNull final QosCallback callback)5625 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo, 5626 @CallbackExecutor @NonNull final Executor executor, 5627 @NonNull final QosCallback callback) { 5628 Objects.requireNonNull(socketInfo, "socketInfo must be non-null"); 5629 Objects.requireNonNull(executor, "executor must be non-null"); 5630 Objects.requireNonNull(callback, "callback must be non-null"); 5631 5632 try { 5633 synchronized (mQosCallbackConnections) { 5634 if (getQosCallbackConnection(callback) == null) { 5635 final QosCallbackConnection connection = 5636 new QosCallbackConnection(this, callback, executor); 5637 mQosCallbackConnections.add(connection); 5638 mService.registerQosSocketCallback(socketInfo, connection); 5639 } else { 5640 Log.e(TAG, "registerQosCallback: Callback already registered"); 5641 throw new QosCallbackRegistrationException(); 5642 } 5643 } 5644 } catch (final RemoteException e) { 5645 Log.e(TAG, "registerQosCallback: Error while registering ", e); 5646 5647 // The same unregister method method is called for consistency even though nothing 5648 // will be sent to the ConnectivityService since the callback was never successfully 5649 // registered. 5650 unregisterQosCallback(callback); 5651 e.rethrowFromSystemServer(); 5652 } catch (final ServiceSpecificException e) { 5653 Log.e(TAG, "registerQosCallback: Error while registering ", e); 5654 unregisterQosCallback(callback); 5655 throw convertServiceException(e); 5656 } 5657 } 5658 5659 /** 5660 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive 5661 * events once unregistered and can be registered a second time. 5662 * <p/> 5663 * If the {@link QosCallback} does not have an active registration, it is a no-op. 5664 * 5665 * @param callback the callback being unregistered 5666 * 5667 * @hide 5668 */ 5669 @SystemApi unregisterQosCallback(@onNull final QosCallback callback)5670 public void unregisterQosCallback(@NonNull final QosCallback callback) { 5671 Objects.requireNonNull(callback, "The callback must be non-null"); 5672 try { 5673 synchronized (mQosCallbackConnections) { 5674 final QosCallbackConnection connection = getQosCallbackConnection(callback); 5675 if (connection != null) { 5676 connection.stopReceivingMessages(); 5677 mService.unregisterQosCallback(connection); 5678 mQosCallbackConnections.remove(connection); 5679 } else { 5680 Log.d(TAG, "unregisterQosCallback: Callback not registered"); 5681 } 5682 } 5683 } catch (final RemoteException e) { 5684 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e); 5685 e.rethrowFromSystemServer(); 5686 } 5687 } 5688 5689 /** 5690 * Gets the connection related to the callback. 5691 * 5692 * @param callback the callback to look up 5693 * @return the related connection 5694 */ 5695 @Nullable getQosCallbackConnection(final QosCallback callback)5696 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) { 5697 for (final QosCallbackConnection connection : mQosCallbackConnections) { 5698 // Checking by reference here is intentional 5699 if (connection.getCallback() == callback) { 5700 return connection; 5701 } 5702 } 5703 return null; 5704 } 5705 5706 /** 5707 * Request a network to satisfy a set of {@link NetworkCapabilities}, but 5708 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can 5709 * be used to request that the system provide a network without causing the network to be 5710 * in the foreground. 5711 * 5712 * <p>This method will attempt to find the best network that matches the passed 5713 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the 5714 * criteria. The platform will evaluate which network is the best at its own discretion. 5715 * Throughput, latency, cost per byte, policy, user preference and other considerations 5716 * may be factored in the decision of what is considered the best network. 5717 * 5718 * <p>As long as this request is outstanding, the platform will try to maintain the best network 5719 * matching this request, while always attempting to match the request to a better network if 5720 * possible. If a better match is found, the platform will switch this request to the now-best 5721 * network and inform the app of the newly best network by invoking 5722 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform 5723 * will not try to maintain any other network than the best one currently matching the request: 5724 * a network not matching any network request may be disconnected at any time. 5725 * 5726 * <p>For example, an application could use this method to obtain a connected cellular network 5727 * even if the device currently has a data connection over Ethernet. This may cause the cellular 5728 * radio to consume additional power. Or, an application could inform the system that it wants 5729 * a network supporting sending MMSes and have the system let it know about the currently best 5730 * MMS-supporting network through the provided {@link NetworkCallback}. 5731 * 5732 * <p>The status of the request can be followed by listening to the various callbacks described 5733 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be 5734 * used to direct traffic to the network (although accessing some networks may be subject to 5735 * holding specific permissions). Callers will learn about the specific characteristics of the 5736 * network through 5737 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and 5738 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the 5739 * provided {@link NetworkCallback} will only be invoked due to changes in the best network 5740 * matching the request at any given time; therefore when a better network matching the request 5741 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called 5742 * with the new network after which no further updates are given about the previously-best 5743 * network, unless it becomes the best again at some later time. All callbacks are invoked 5744 * in order on the same thread, which by default is a thread created by the framework running 5745 * in the app. 5746 * 5747 * <p>This{@link NetworkRequest} will live until released via 5748 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at 5749 * which point the system may let go of the network at any time. 5750 * 5751 * <p>It is presently unsupported to request a network with mutable 5752 * {@link NetworkCapabilities} such as 5753 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or 5754 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL} 5755 * as these {@code NetworkCapabilities} represent states that a particular 5756 * network may never attain, and whether a network will attain these states 5757 * is unknown prior to bringing up the network so the framework does not 5758 * know how to go about satisfying a request with these capabilities. 5759 * 5760 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the 5761 * number of outstanding requests to 100 per app (identified by their UID), shared with 5762 * all variants of this method, of {@link #registerNetworkCallback} as well as 5763 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}. 5764 * Requesting a network with this method will count toward this limit. If this limit is 5765 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, 5766 * make sure to unregister the callbacks with 5767 * {@link #unregisterNetworkCallback(NetworkCallback)}. 5768 * 5769 * @param request {@link NetworkRequest} describing this request. 5770 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note 5771 * the callback must not be shared - it uniquely specifies this request. 5772 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked. 5773 * If null, the callback is invoked on the default internal Handler. 5774 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities. 5775 * @throws SecurityException if missing the appropriate permissions. 5776 * @throws RuntimeException if the app already has too many callbacks registered. 5777 * 5778 * @hide 5779 */ 5780 @SystemApi(client = MODULE_LIBRARIES) 5781 @SuppressLint("ExecutorRegistration") 5782 @RequiresPermission(anyOf = { 5783 android.Manifest.permission.NETWORK_SETTINGS, 5784 android.Manifest.permission.NETWORK_STACK, 5785 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 5786 }) requestBackgroundNetwork(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback, @SuppressLint("ListenerLast") @NonNull Handler handler)5787 public void requestBackgroundNetwork(@NonNull NetworkRequest request, 5788 @NonNull NetworkCallback networkCallback, 5789 @SuppressLint("ListenerLast") @NonNull Handler handler) { 5790 final NetworkCapabilities nc = request.networkCapabilities; 5791 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST, 5792 TYPE_NONE, new CallbackHandler(handler)); 5793 } 5794 5795 /** 5796 * Used by automotive devices to set the network preferences used to direct traffic at an 5797 * application level as per the given OemNetworkPreferences. An example use-case would be an 5798 * automotive OEM wanting to provide connectivity for applications critical to the usage of a 5799 * vehicle via a particular network. 5800 * 5801 * Calling this will overwrite the existing preference. 5802 * 5803 * @param preference {@link OemNetworkPreferences} The application network preference to be set. 5804 * @param executor the executor on which listener will be invoked. 5805 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to 5806 * communicate completion of setOemNetworkPreference(). This will only be 5807 * called once upon successful completion of setOemNetworkPreference(). 5808 * @throws IllegalArgumentException if {@code preference} contains invalid preference values. 5809 * @throws SecurityException if missing the appropriate permissions. 5810 * @throws UnsupportedOperationException if called on a non-automotive device. 5811 * @hide 5812 */ 5813 @SystemApi 5814 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE) setOemNetworkPreference(@onNull final OemNetworkPreferences preference, @Nullable @CallbackExecutor final Executor executor, @Nullable final Runnable listener)5815 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference, 5816 @Nullable @CallbackExecutor final Executor executor, 5817 @Nullable final Runnable listener) { 5818 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null"); 5819 if (null != listener) { 5820 Objects.requireNonNull(executor, "Executor must be non-null"); 5821 } 5822 final IOnCompleteListener listenerInternal = listener == null ? null : 5823 new IOnCompleteListener.Stub() { 5824 @Override 5825 public void onComplete() { 5826 executor.execute(listener::run); 5827 } 5828 }; 5829 5830 try { 5831 mService.setOemNetworkPreference(preference, listenerInternal); 5832 } catch (RemoteException e) { 5833 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString()); 5834 throw e.rethrowFromSystemServer(); 5835 } 5836 } 5837 5838 /** 5839 * Request that a user profile is put by default on a network matching a given preference. 5840 * 5841 * See the documentation for the individual preferences for a description of the supported 5842 * behaviors. 5843 * 5844 * @param profile the profile concerned. 5845 * @param preference the preference for this profile. 5846 * @param executor an executor to execute the listener on. Optional if listener is null. 5847 * @param listener an optional listener to listen for completion of the operation. 5848 * @throws IllegalArgumentException if {@code profile} is not a valid user profile. 5849 * @throws SecurityException if missing the appropriate permissions. 5850 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)} 5851 * instead as it provides a more flexible API with more options. 5852 * @hide 5853 */ 5854 // This function is for establishing per-profile default networking and can only be called by 5855 // the device policy manager, running as the system server. It would make no sense to call it 5856 // on a context for a user because it does not establish a setting on behalf of a user, rather 5857 // it establishes a setting for a user on behalf of the DPM. 5858 @SuppressLint({"UserHandle"}) 5859 @SystemApi(client = MODULE_LIBRARIES) 5860 @RequiresPermission(android.Manifest.permission.NETWORK_STACK) 5861 @Deprecated setProfileNetworkPreference(@onNull final UserHandle profile, @ProfileNetworkPreferencePolicy final int preference, @Nullable @CallbackExecutor final Executor executor, @Nullable final Runnable listener)5862 public void setProfileNetworkPreference(@NonNull final UserHandle profile, 5863 @ProfileNetworkPreferencePolicy final int preference, 5864 @Nullable @CallbackExecutor final Executor executor, 5865 @Nullable final Runnable listener) { 5866 5867 ProfileNetworkPreference.Builder preferenceBuilder = 5868 new ProfileNetworkPreference.Builder(); 5869 preferenceBuilder.setPreference(preference); 5870 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) { 5871 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1); 5872 } 5873 setProfileNetworkPreferences(profile, 5874 List.of(preferenceBuilder.build()), executor, listener); 5875 } 5876 5877 /** 5878 * Set a list of default network selection policies for a user profile. 5879 * 5880 * Calling this API with a user handle defines the entire policy for that user handle. 5881 * It will overwrite any setting previously set for the same user profile, 5882 * and not affect previously set settings for other handles. 5883 * 5884 * Call this API with an empty list to remove settings for this user profile. 5885 * 5886 * See {@link ProfileNetworkPreference} for more details on each preference 5887 * parameter. 5888 * 5889 * @param profile the user profile for which the preference is being set. 5890 * @param profileNetworkPreferences the list of profile network preferences for the 5891 * provided profile. 5892 * @param executor an executor to execute the listener on. Optional if listener is null. 5893 * @param listener an optional listener to listen for completion of the operation. 5894 * @throws IllegalArgumentException if {@code profile} is not a valid user profile. 5895 * @throws SecurityException if missing the appropriate permissions. 5896 * @hide 5897 */ 5898 @SystemApi(client = MODULE_LIBRARIES) 5899 @RequiresPermission(android.Manifest.permission.NETWORK_STACK) setProfileNetworkPreferences( @onNull final UserHandle profile, @NonNull List<ProfileNetworkPreference> profileNetworkPreferences, @Nullable @CallbackExecutor final Executor executor, @Nullable final Runnable listener)5900 public void setProfileNetworkPreferences( 5901 @NonNull final UserHandle profile, 5902 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences, 5903 @Nullable @CallbackExecutor final Executor executor, 5904 @Nullable final Runnable listener) { 5905 if (null != listener) { 5906 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener"); 5907 } 5908 final IOnCompleteListener proxy; 5909 if (null == listener) { 5910 proxy = null; 5911 } else { 5912 proxy = new IOnCompleteListener.Stub() { 5913 @Override 5914 public void onComplete() { 5915 executor.execute(listener::run); 5916 } 5917 }; 5918 } 5919 try { 5920 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy); 5921 } catch (RemoteException e) { 5922 throw e.rethrowFromSystemServer(); 5923 } 5924 } 5925 5926 // The first network ID of IPSec tunnel interface. 5927 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512 5928 // The network ID range of IPSec tunnel interface. 5929 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024 5930 5931 /** 5932 * Get the network ID range reserved for IPSec tunnel interfaces. 5933 * 5934 * @return A Range which indicates the network ID range of IPSec tunnel interface. 5935 * @hide 5936 */ 5937 @SystemApi(client = MODULE_LIBRARIES) 5938 @NonNull getIpSecNetIdRange()5939 public static Range<Integer> getIpSecNetIdRange() { 5940 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1); 5941 } 5942 5943 /** 5944 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks 5945 * even when background data is restricted. The deny list takes precedence over the allow list. 5946 * 5947 * @param uid uid of target app 5948 * @throws IllegalStateException if updating allow list failed. 5949 * @hide 5950 */ 5951 @SystemApi(client = MODULE_LIBRARIES) 5952 @RequiresPermission(anyOf = { 5953 android.Manifest.permission.NETWORK_SETTINGS, 5954 android.Manifest.permission.NETWORK_STACK, 5955 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 5956 }) addUidToMeteredNetworkAllowList(final int uid)5957 public void addUidToMeteredNetworkAllowList(final int uid) { 5958 try { 5959 mService.updateMeteredNetworkAllowList(uid, true /* add */); 5960 } catch (RemoteException e) { 5961 throw e.rethrowFromSystemServer(); 5962 } 5963 } 5964 5965 /** 5966 * Removes the specified UID from the list of UIDs that are allowed to use background data on 5967 * metered networks when background data is restricted. The deny list takes precedence over 5968 * the allow list. 5969 * 5970 * @param uid uid of target app 5971 * @throws IllegalStateException if updating allow list failed. 5972 * @hide 5973 */ 5974 @SystemApi(client = MODULE_LIBRARIES) 5975 @RequiresPermission(anyOf = { 5976 android.Manifest.permission.NETWORK_SETTINGS, 5977 android.Manifest.permission.NETWORK_STACK, 5978 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 5979 }) removeUidFromMeteredNetworkAllowList(final int uid)5980 public void removeUidFromMeteredNetworkAllowList(final int uid) { 5981 try { 5982 mService.updateMeteredNetworkAllowList(uid, false /* remove */); 5983 } catch (RemoteException e) { 5984 throw e.rethrowFromSystemServer(); 5985 } 5986 } 5987 5988 /** 5989 * Adds the specified UID to the list of UIDs that are not allowed to use background data on 5990 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}. 5991 * 5992 * @param uid uid of target app 5993 * @throws IllegalStateException if updating deny list failed. 5994 * @hide 5995 */ 5996 @SystemApi(client = MODULE_LIBRARIES) 5997 @RequiresPermission(anyOf = { 5998 android.Manifest.permission.NETWORK_SETTINGS, 5999 android.Manifest.permission.NETWORK_STACK, 6000 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 6001 }) addUidToMeteredNetworkDenyList(final int uid)6002 public void addUidToMeteredNetworkDenyList(final int uid) { 6003 try { 6004 mService.updateMeteredNetworkDenyList(uid, true /* add */); 6005 } catch (RemoteException e) { 6006 throw e.rethrowFromSystemServer(); 6007 } 6008 } 6009 6010 /** 6011 * Removes the specified UID from the list of UIDs that can use background data on metered 6012 * networks if background data is not restricted. The deny list takes precedence over the 6013 * allow list. 6014 * 6015 * @param uid uid of target app 6016 * @throws IllegalStateException if updating deny list failed. 6017 * @hide 6018 */ 6019 @SystemApi(client = MODULE_LIBRARIES) 6020 @RequiresPermission(anyOf = { 6021 android.Manifest.permission.NETWORK_SETTINGS, 6022 android.Manifest.permission.NETWORK_STACK, 6023 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 6024 }) removeUidFromMeteredNetworkDenyList(final int uid)6025 public void removeUidFromMeteredNetworkDenyList(final int uid) { 6026 try { 6027 mService.updateMeteredNetworkDenyList(uid, false /* remove */); 6028 } catch (RemoteException e) { 6029 throw e.rethrowFromSystemServer(); 6030 } 6031 } 6032 6033 /** 6034 * Sets a firewall rule for the specified UID on the specified chain. 6035 * 6036 * @param chain target chain. 6037 * @param uid uid to allow/deny. 6038 * @param rule firewall rule to allow/drop packets. 6039 * @throws IllegalStateException if updating firewall rule failed. 6040 * @throws IllegalArgumentException if {@code rule} is not a valid rule. 6041 * @hide 6042 */ 6043 @SystemApi(client = MODULE_LIBRARIES) 6044 @RequiresPermission(anyOf = { 6045 android.Manifest.permission.NETWORK_SETTINGS, 6046 android.Manifest.permission.NETWORK_STACK, 6047 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 6048 }) setUidFirewallRule(@irewallChain final int chain, final int uid, @FirewallRule final int rule)6049 public void setUidFirewallRule(@FirewallChain final int chain, final int uid, 6050 @FirewallRule final int rule) { 6051 try { 6052 mService.setUidFirewallRule(chain, uid, rule); 6053 } catch (RemoteException e) { 6054 throw e.rethrowFromSystemServer(); 6055 } 6056 } 6057 6058 /** 6059 * Get firewall rule of specified firewall chain on specified uid. 6060 * 6061 * @param chain target chain. 6062 * @param uid target uid 6063 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY 6064 * @throws UnsupportedOperationException if called on pre-T devices. 6065 * @throws ServiceSpecificException in case of failure, with an error code indicating the 6066 * cause of the failure. 6067 * @hide 6068 */ 6069 @RequiresPermission(anyOf = { 6070 android.Manifest.permission.NETWORK_SETTINGS, 6071 android.Manifest.permission.NETWORK_STACK, 6072 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 6073 }) getUidFirewallRule(@irewallChain final int chain, final int uid)6074 public int getUidFirewallRule(@FirewallChain final int chain, final int uid) { 6075 try { 6076 return mService.getUidFirewallRule(chain, uid); 6077 } catch (RemoteException e) { 6078 throw e.rethrowFromSystemServer(); 6079 } 6080 } 6081 6082 /** 6083 * Enables or disables the specified firewall chain. 6084 * 6085 * @param chain target chain. 6086 * @param enable whether the chain should be enabled. 6087 * @throws UnsupportedOperationException if called on pre-T devices. 6088 * @throws IllegalStateException if enabling or disabling the firewall chain failed. 6089 * @hide 6090 */ 6091 @SystemApi(client = MODULE_LIBRARIES) 6092 @RequiresPermission(anyOf = { 6093 android.Manifest.permission.NETWORK_SETTINGS, 6094 android.Manifest.permission.NETWORK_STACK, 6095 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 6096 }) setFirewallChainEnabled(@irewallChain final int chain, final boolean enable)6097 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) { 6098 try { 6099 mService.setFirewallChainEnabled(chain, enable); 6100 } catch (RemoteException e) { 6101 throw e.rethrowFromSystemServer(); 6102 } 6103 } 6104 6105 /** 6106 * Get the specified firewall chain's status. 6107 * 6108 * @param chain target chain. 6109 * @return {@code true} if chain is enabled, {@code false} if chain is disabled. 6110 * @throws UnsupportedOperationException if called on pre-T devices. 6111 * @throws ServiceSpecificException in case of failure, with an error code indicating the 6112 * cause of the failure. 6113 * @hide 6114 */ 6115 @RequiresPermission(anyOf = { 6116 android.Manifest.permission.NETWORK_SETTINGS, 6117 android.Manifest.permission.NETWORK_STACK, 6118 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 6119 }) getFirewallChainEnabled(@irewallChain final int chain)6120 public boolean getFirewallChainEnabled(@FirewallChain final int chain) { 6121 try { 6122 return mService.getFirewallChainEnabled(chain); 6123 } catch (RemoteException e) { 6124 throw e.rethrowFromSystemServer(); 6125 } 6126 } 6127 6128 /** 6129 * Replaces the contents of the specified UID-based firewall chain. 6130 * 6131 * @param chain target chain to replace. 6132 * @param uids The list of UIDs to be placed into chain. 6133 * @throws UnsupportedOperationException if called on pre-T devices. 6134 * @throws IllegalArgumentException if {@code chain} is not a valid chain. 6135 * @hide 6136 */ 6137 @SystemApi(client = MODULE_LIBRARIES) 6138 @RequiresPermission(anyOf = { 6139 android.Manifest.permission.NETWORK_SETTINGS, 6140 android.Manifest.permission.NETWORK_STACK, 6141 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK 6142 }) replaceFirewallChain(@irewallChain final int chain, @NonNull final int[] uids)6143 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) { 6144 Objects.requireNonNull(uids); 6145 try { 6146 mService.replaceFirewallChain(chain, uids); 6147 } catch (RemoteException e) { 6148 throw e.rethrowFromSystemServer(); 6149 } 6150 } 6151 6152 /** @hide */ getCompanionDeviceManagerProxyService()6153 public IBinder getCompanionDeviceManagerProxyService() { 6154 try { 6155 return mService.getCompanionDeviceManagerProxyService(); 6156 } catch (RemoteException e) { 6157 throw e.rethrowFromSystemServer(); 6158 } 6159 } 6160 } 6161