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