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