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