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