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