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      * Dummy 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 lockdownWhitelist 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 whitelisted 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> lockdownWhitelist)1096     public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
1097             boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
1098         try {
1099             return mService.setAlwaysOnVpnPackage(
1100                     userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
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         /** The requested keepalive was successfully started. */
1729         @UnsupportedAppUsage
onStarted()1730         public void onStarted() {}
1731         /** The keepalive was successfully stopped. */
1732         @UnsupportedAppUsage
onStopped()1733         public void onStopped() {}
1734         /** An error occurred. */
1735         @UnsupportedAppUsage
onError(int error)1736         public void onError(int error) {}
1737     }
1738 
1739     /**
1740      * Allows applications to request that the system periodically send specific packets on their
1741      * behalf, using hardware offload to save battery power.
1742      *
1743      * To request that the system send keepalives, call one of the methods that return a
1744      * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1745      * passing in a non-null callback. If the callback is successfully started, the callback's
1746      * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1747      * specifying one of the {@code ERROR_*} constants in this class.
1748      *
1749      * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1750      * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1751      * {@link PacketKeepaliveCallback#onError} if an error occurred.
1752      *
1753      * @deprecated Use {@link SocketKeepalive} instead.
1754      *
1755      * @hide
1756      */
1757     public class PacketKeepalive {
1758 
1759         private static final String TAG = "PacketKeepalive";
1760 
1761         /** @hide */
1762         public static final int SUCCESS = 0;
1763 
1764         /** @hide */
1765         public static final int NO_KEEPALIVE = -1;
1766 
1767         /** @hide */
1768         public static final int BINDER_DIED = -10;
1769 
1770         /** The specified {@code Network} is not connected. */
1771         public static final int ERROR_INVALID_NETWORK = -20;
1772         /** The specified IP addresses are invalid. For example, the specified source IP address is
1773           * not configured on the specified {@code Network}. */
1774         public static final int ERROR_INVALID_IP_ADDRESS = -21;
1775         /** The requested port is invalid. */
1776         public static final int ERROR_INVALID_PORT = -22;
1777         /** The packet length is invalid (e.g., too long). */
1778         public static final int ERROR_INVALID_LENGTH = -23;
1779         /** The packet transmission interval is invalid (e.g., too short). */
1780         public static final int ERROR_INVALID_INTERVAL = -24;
1781 
1782         /** The hardware does not support this request. */
1783         public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
1784         /** The hardware returned an error. */
1785         public static final int ERROR_HARDWARE_ERROR = -31;
1786 
1787         /** The NAT-T destination port for IPsec */
1788         public static final int NATT_PORT = 4500;
1789 
1790         /** The minimum interval in seconds between keepalive packet transmissions */
1791         public static final int MIN_INTERVAL = 10;
1792 
1793         private final Network mNetwork;
1794         private final ISocketKeepaliveCallback mCallback;
1795         private final ExecutorService mExecutor;
1796 
1797         private volatile Integer mSlot;
1798 
1799         @UnsupportedAppUsage
stop()1800         public void stop() {
1801             try {
1802                 mExecutor.execute(() -> {
1803                     try {
1804                         if (mSlot != null) {
1805                             mService.stopKeepalive(mNetwork, mSlot);
1806                         }
1807                     } catch (RemoteException e) {
1808                         Log.e(TAG, "Error stopping packet keepalive: ", e);
1809                         throw e.rethrowFromSystemServer();
1810                     }
1811                 });
1812             } catch (RejectedExecutionException e) {
1813                 // The internal executor has already stopped due to previous event.
1814             }
1815         }
1816 
PacketKeepalive(Network network, PacketKeepaliveCallback callback)1817         private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
1818             Preconditions.checkNotNull(network, "network cannot be null");
1819             Preconditions.checkNotNull(callback, "callback cannot be null");
1820             mNetwork = network;
1821             mExecutor = Executors.newSingleThreadExecutor();
1822             mCallback = new ISocketKeepaliveCallback.Stub() {
1823                 @Override
1824                 public void onStarted(int slot) {
1825                     Binder.withCleanCallingIdentity(() ->
1826                             mExecutor.execute(() -> {
1827                                 mSlot = slot;
1828                                 callback.onStarted();
1829                             }));
1830                 }
1831 
1832                 @Override
1833                 public void onStopped() {
1834                     Binder.withCleanCallingIdentity(() ->
1835                             mExecutor.execute(() -> {
1836                                 mSlot = null;
1837                                 callback.onStopped();
1838                             }));
1839                     mExecutor.shutdown();
1840                 }
1841 
1842                 @Override
1843                 public void onError(int error) {
1844                     Binder.withCleanCallingIdentity(() ->
1845                             mExecutor.execute(() -> {
1846                                 mSlot = null;
1847                                 callback.onError(error);
1848                             }));
1849                     mExecutor.shutdown();
1850                 }
1851 
1852                 @Override
1853                 public void onDataReceived() {
1854                     // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1855                     // this callback when data is received.
1856                 }
1857             };
1858         }
1859     }
1860 
1861     /**
1862      * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1863      *
1864      * @deprecated Use {@link #createSocketKeepalive} instead.
1865      *
1866      * @hide
1867      */
1868     @UnsupportedAppUsage
startNattKeepalive( Network network, int intervalSeconds, PacketKeepaliveCallback callback, InetAddress srcAddr, int srcPort, InetAddress dstAddr)1869     public PacketKeepalive startNattKeepalive(
1870             Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1871             InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1872         final PacketKeepalive k = new PacketKeepalive(network, callback);
1873         try {
1874             mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
1875                     srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1876         } catch (RemoteException e) {
1877             Log.e(TAG, "Error starting packet keepalive: ", e);
1878             throw e.rethrowFromSystemServer();
1879         }
1880         return k;
1881     }
1882 
1883     /**
1884      * Request that keepalives be started on a IPsec NAT-T socket.
1885      *
1886      * @param network The {@link Network} the socket is on.
1887      * @param socket The socket that needs to be kept alive.
1888      * @param source The source address of the {@link UdpEncapsulationSocket}.
1889      * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1890      * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1891      *                 must run callback sequentially, otherwise the order of callbacks cannot be
1892      *                 guaranteed.
1893      * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1894      *        changes. Must be extended by applications that use this API.
1895      *
1896      * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1897      *         given socket.
1898      **/
createSocketKeepalive(@onNull Network network, @NonNull UdpEncapsulationSocket socket, @NonNull InetAddress source, @NonNull InetAddress destination, @NonNull @CallbackExecutor Executor executor, @NonNull Callback callback)1899     public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
1900             @NonNull UdpEncapsulationSocket socket,
1901             @NonNull InetAddress source,
1902             @NonNull InetAddress destination,
1903             @NonNull @CallbackExecutor Executor executor,
1904             @NonNull Callback callback) {
1905         ParcelFileDescriptor dup;
1906         try {
1907             // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1908             // which cannot be obtained by the app process.
1909             dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1910         } catch (IOException ignored) {
1911             // Construct an invalid fd, so that if the user later calls start(), it will fail with
1912             // ERROR_INVALID_SOCKET.
1913             dup = new ParcelFileDescriptor(new FileDescriptor());
1914         }
1915         return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1916                 destination, executor, callback);
1917     }
1918 
1919     /**
1920      * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1921      * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1922      *
1923      * @param network The {@link Network} the socket is on.
1924      * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1925      *        {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1926      *        from that port.
1927      * @param source The source address of the {@link UdpEncapsulationSocket}.
1928      * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1929      *        keepalive packets will always be sent to port 4500 of the given {@code destination}.
1930      * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1931      *                 must run callback sequentially, otherwise the order of callbacks cannot be
1932      *                 guaranteed.
1933      * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1934      *        changes. Must be extended by applications that use this API.
1935      *
1936      * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1937      *         given socket.
1938      * @hide
1939      */
1940     @SystemApi
1941     @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)1942     public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1943             @NonNull ParcelFileDescriptor pfd,
1944             @NonNull InetAddress source,
1945             @NonNull InetAddress destination,
1946             @NonNull @CallbackExecutor Executor executor,
1947             @NonNull Callback callback) {
1948         ParcelFileDescriptor dup;
1949         try {
1950             // TODO: Consider remove unnecessary dup.
1951             dup = pfd.dup();
1952         } catch (IOException ignored) {
1953             // Construct an invalid fd, so that if the user later calls start(), it will fail with
1954             // ERROR_INVALID_SOCKET.
1955             dup = new ParcelFileDescriptor(new FileDescriptor());
1956         }
1957         return new NattSocketKeepalive(mService, network, dup,
1958                 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
1959     }
1960 
1961     /**
1962      * Request that keepalives be started on a TCP socket.
1963      * The socket must be established.
1964      *
1965      * @param network The {@link Network} the socket is on.
1966      * @param socket The socket that needs to be kept alive.
1967      * @param executor The executor on which callback will be invoked. This implementation assumes
1968      *                 the provided {@link Executor} runs the callbacks in sequence with no
1969      *                 concurrency. Failing this, no guarantee of correctness can be made. It is
1970      *                 the responsibility of the caller to ensure the executor provides this
1971      *                 guarantee. A simple way of creating such an executor is with the standard
1972      *                 tool {@code Executors.newSingleThreadExecutor}.
1973      * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1974      *        changes. Must be extended by applications that use this API.
1975      *
1976      * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1977      *         given socket.
1978      * @hide
1979      */
1980     @SystemApi
1981     @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
createSocketKeepalive(@onNull Network network, @NonNull Socket socket, @NonNull Executor executor, @NonNull Callback callback)1982     public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
1983             @NonNull Socket socket,
1984             @NonNull Executor executor,
1985             @NonNull Callback callback) {
1986         ParcelFileDescriptor dup;
1987         try {
1988             dup = ParcelFileDescriptor.fromSocket(socket);
1989         } catch (UncheckedIOException ignored) {
1990             // Construct an invalid fd, so that if the user later calls start(), it will fail with
1991             // ERROR_INVALID_SOCKET.
1992             dup = new ParcelFileDescriptor(new FileDescriptor());
1993         }
1994         return new TcpSocketKeepalive(mService, network, dup, executor, callback);
1995     }
1996 
1997     /**
1998      * Ensure that a network route exists to deliver traffic to the specified
1999      * host via the specified network interface. An attempt to add a route that
2000      * already exists is ignored, but treated as successful.
2001      *
2002      * <p>This method requires the caller to hold either the
2003      * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2004      * or the ability to modify system settings as determined by
2005      * {@link android.provider.Settings.System#canWrite}.</p>
2006      *
2007      * @param networkType the type of the network over which traffic to the specified
2008      * host is to be routed
2009      * @param hostAddress the IP address of the host to which the route is desired
2010      * @return {@code true} on success, {@code false} on failure
2011      *
2012      * @deprecated Deprecated in favor of the
2013      *             {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2014      *             {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2015      *             In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2016      *             throw {@code UnsupportedOperationException} if called.
2017      * @removed
2018      */
2019     @Deprecated
requestRouteToHost(int networkType, int hostAddress)2020     public boolean requestRouteToHost(int networkType, int hostAddress) {
2021         return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2022     }
2023 
2024     /**
2025      * Ensure that a network route exists to deliver traffic to the specified
2026      * host via the specified network interface. An attempt to add a route that
2027      * already exists is ignored, but treated as successful.
2028      *
2029      * <p>This method requires the caller to hold either the
2030      * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2031      * or the ability to modify system settings as determined by
2032      * {@link android.provider.Settings.System#canWrite}.</p>
2033      *
2034      * @param networkType the type of the network over which traffic to the specified
2035      * host is to be routed
2036      * @param hostAddress the IP address of the host to which the route is desired
2037      * @return {@code true} on success, {@code false} on failure
2038      * @hide
2039      * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2040      *             {@link #bindProcessToNetwork} API.
2041      */
2042     @Deprecated
2043     @UnsupportedAppUsage
requestRouteToHostAddress(int networkType, InetAddress hostAddress)2044     public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2045         checkLegacyRoutingApiAccess();
2046         try {
2047             return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
2048         } catch (RemoteException e) {
2049             throw e.rethrowFromSystemServer();
2050         }
2051     }
2052 
2053     /**
2054      * Returns the value of the setting for background data usage. If false,
2055      * applications should not use the network if the application is not in the
2056      * foreground. Developers should respect this setting, and check the value
2057      * of this before performing any background data operations.
2058      * <p>
2059      * All applications that have background services that use the network
2060      * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2061      * <p>
2062      * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2063      * background data depends on several combined factors, and this method will
2064      * always return {@code true}. Instead, when background data is unavailable,
2065      * {@link #getActiveNetworkInfo()} will now appear disconnected.
2066      *
2067      * @return Whether background data usage is allowed.
2068      */
2069     @Deprecated
getBackgroundDataSetting()2070     public boolean getBackgroundDataSetting() {
2071         // assume that background data is allowed; final authority is
2072         // NetworkInfo which may be blocked.
2073         return true;
2074     }
2075 
2076     /**
2077      * Sets the value of the setting for background data usage.
2078      *
2079      * @param allowBackgroundData Whether an application should use data while
2080      *            it is in the background.
2081      *
2082      * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2083      * @see #getBackgroundDataSetting()
2084      * @hide
2085      */
2086     @Deprecated
2087     @UnsupportedAppUsage
setBackgroundDataSetting(boolean allowBackgroundData)2088     public void setBackgroundDataSetting(boolean allowBackgroundData) {
2089         // ignored
2090     }
2091 
2092     /** {@hide} */
2093     @Deprecated
2094     @UnsupportedAppUsage
getActiveNetworkQuotaInfo()2095     public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2096         try {
2097             return mService.getActiveNetworkQuotaInfo();
2098         } catch (RemoteException e) {
2099             throw e.rethrowFromSystemServer();
2100         }
2101     }
2102 
2103     /**
2104      * @hide
2105      * @deprecated Talk to TelephonyManager directly
2106      */
2107     @Deprecated
2108     @UnsupportedAppUsage
getMobileDataEnabled()2109     public boolean getMobileDataEnabled() {
2110         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2111         if (tm != null) {
2112             int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2113             Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2114             boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2115             Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2116                     + " retVal=" + retVal);
2117             return retVal;
2118         }
2119         Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2120         return false;
2121     }
2122 
2123     /**
2124      * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2125      * to find out when the system default network has gone in to a high power state.
2126      */
2127     public interface OnNetworkActiveListener {
2128         /**
2129          * Called on the main thread of the process to report that the current data network
2130          * has become active, and it is now a good time to perform any pending network
2131          * operations.  Note that this listener only tells you when the network becomes
2132          * active; if at any other time you want to know whether it is active (and thus okay
2133          * to initiate network traffic), you can retrieve its instantaneous state with
2134          * {@link ConnectivityManager#isDefaultNetworkActive}.
2135          */
onNetworkActive()2136         void onNetworkActive();
2137     }
2138 
getNetworkManagementService()2139     private INetworkManagementService getNetworkManagementService() {
2140         synchronized (this) {
2141             if (mNMService != null) {
2142                 return mNMService;
2143             }
2144             IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2145             mNMService = INetworkManagementService.Stub.asInterface(b);
2146             return mNMService;
2147         }
2148     }
2149 
2150     private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2151             mNetworkActivityListeners = new ArrayMap<>();
2152 
2153     /**
2154      * Start listening to reports when the system's default data network is active, meaning it is
2155      * a good time to perform network traffic.  Use {@link #isDefaultNetworkActive()}
2156      * to determine the current state of the system's default network after registering the
2157      * listener.
2158      * <p>
2159      * If the process default network has been set with
2160      * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2161      * reflect the process's default, but the system default.
2162      *
2163      * @param l The listener to be told when the network is active.
2164      */
addDefaultNetworkActiveListener(final OnNetworkActiveListener l)2165     public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
2166         INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2167             @Override
2168             public void onNetworkActive() throws RemoteException {
2169                 l.onNetworkActive();
2170             }
2171         };
2172 
2173         try {
2174             getNetworkManagementService().registerNetworkActivityListener(rl);
2175             mNetworkActivityListeners.put(l, rl);
2176         } catch (RemoteException e) {
2177             throw e.rethrowFromSystemServer();
2178         }
2179     }
2180 
2181     /**
2182      * Remove network active listener previously registered with
2183      * {@link #addDefaultNetworkActiveListener}.
2184      *
2185      * @param l Previously registered listener.
2186      */
removeDefaultNetworkActiveListener(@onNull OnNetworkActiveListener l)2187     public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
2188         INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2189         Preconditions.checkArgument(rl != null, "Listener was not registered.");
2190         try {
2191             getNetworkManagementService().unregisterNetworkActivityListener(rl);
2192         } catch (RemoteException e) {
2193             throw e.rethrowFromSystemServer();
2194         }
2195     }
2196 
2197     /**
2198      * Return whether the data network is currently active.  An active network means that
2199      * it is currently in a high power state for performing data transmission.  On some
2200      * types of networks, it may be expensive to move and stay in such a state, so it is
2201      * more power efficient to batch network traffic together when the radio is already in
2202      * this state.  This method tells you whether right now is currently a good time to
2203      * initiate network traffic, as the network is already active.
2204      */
isDefaultNetworkActive()2205     public boolean isDefaultNetworkActive() {
2206         try {
2207             return getNetworkManagementService().isNetworkActive();
2208         } catch (RemoteException e) {
2209             throw e.rethrowFromSystemServer();
2210         }
2211     }
2212 
2213     /**
2214      * {@hide}
2215      */
ConnectivityManager(Context context, IConnectivityManager service)2216     public ConnectivityManager(Context context, IConnectivityManager service) {
2217         mContext = Preconditions.checkNotNull(context, "missing context");
2218         mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
2219         mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
2220         sInstance = this;
2221     }
2222 
2223     /** {@hide} */
2224     @UnsupportedAppUsage
from(Context context)2225     public static ConnectivityManager from(Context context) {
2226         return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2227     }
2228 
2229     /** @hide */
getDefaultRequest()2230     public NetworkRequest getDefaultRequest() {
2231         try {
2232             // This is not racy as the default request is final in ConnectivityService.
2233             return mService.getDefaultRequest();
2234         } catch (RemoteException e) {
2235             throw e.rethrowFromSystemServer();
2236         }
2237     }
2238 
2239     /* TODO: These permissions checks don't belong in client-side code. Move them to
2240      * services.jar, possibly in com.android.server.net. */
2241 
2242     /** {@hide} */
enforceChangePermission(Context context)2243     public static final void enforceChangePermission(Context context) {
2244         int uid = Binder.getCallingUid();
2245         Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2246                 .getPackageNameForUid(context, uid), true /* throwException */);
2247     }
2248 
2249     /**
2250      * @deprecated - use getSystemService. This is a kludge to support static access in certain
2251      *               situations where a Context pointer is unavailable.
2252      * @hide
2253      */
2254     @Deprecated
getInstanceOrNull()2255     static ConnectivityManager getInstanceOrNull() {
2256         return sInstance;
2257     }
2258 
2259     /**
2260      * @deprecated - use getSystemService. This is a kludge to support static access in certain
2261      *               situations where a Context pointer is unavailable.
2262      * @hide
2263      */
2264     @Deprecated
2265     @UnsupportedAppUsage
getInstance()2266     private static ConnectivityManager getInstance() {
2267         if (getInstanceOrNull() == null) {
2268             throw new IllegalStateException("No ConnectivityManager yet constructed");
2269         }
2270         return getInstanceOrNull();
2271     }
2272 
2273     /**
2274      * Get the set of tetherable, available interfaces.  This list is limited by
2275      * device configuration and current interface existence.
2276      *
2277      * @return an array of 0 or more Strings of tetherable interface names.
2278      *
2279      * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2280      * {@hide}
2281      */
2282     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2283     @UnsupportedAppUsage
2284     @Deprecated
getTetherableIfaces()2285     public String[] getTetherableIfaces() {
2286         return mTetheringManager.getTetherableIfaces();
2287     }
2288 
2289     /**
2290      * Get the set of tethered interfaces.
2291      *
2292      * @return an array of 0 or more String of currently tethered interface names.
2293      *
2294      * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2295      * {@hide}
2296      */
2297     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2298     @UnsupportedAppUsage
2299     @Deprecated
getTetheredIfaces()2300     public String[] getTetheredIfaces() {
2301         return mTetheringManager.getTetheredIfaces();
2302     }
2303 
2304     /**
2305      * Get the set of interface names which attempted to tether but
2306      * failed.  Re-attempting to tether may cause them to reset to the Tethered
2307      * state.  Alternatively, causing the interface to be destroyed and recreated
2308      * may cause them to reset to the available state.
2309      * {@link ConnectivityManager#getLastTetherError} can be used to get more
2310      * information on the cause of the errors.
2311      *
2312      * @return an array of 0 or more String indicating the interface names
2313      *        which failed to tether.
2314      *
2315      * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2316      * {@hide}
2317      */
2318     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2319     @UnsupportedAppUsage
2320     @Deprecated
getTetheringErroredIfaces()2321     public String[] getTetheringErroredIfaces() {
2322         return mTetheringManager.getTetheringErroredIfaces();
2323     }
2324 
2325     /**
2326      * Get the set of tethered dhcp ranges.
2327      *
2328      * @deprecated This method is not supported.
2329      * TODO: remove this function when all of clients are removed.
2330      * {@hide}
2331      */
2332     @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2333     @Deprecated
getTetheredDhcpRanges()2334     public String[] getTetheredDhcpRanges() {
2335         throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2336     }
2337 
2338     /**
2339      * Attempt to tether the named interface.  This will setup a dhcp server
2340      * on the interface, forward and NAT IP packets and forward DNS requests
2341      * to the best active upstream network interface.  Note that if no upstream
2342      * IP network interface is available, dhcp will still run and traffic will be
2343      * allowed between the tethered devices and this device, though upstream net
2344      * access will of course fail until an upstream network interface becomes
2345      * active.
2346      *
2347      * <p>This method requires the caller to hold either the
2348      * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2349      * or the ability to modify system settings as determined by
2350      * {@link android.provider.Settings.System#canWrite}.</p>
2351      *
2352      * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2353      * and WifiStateMachine which need direct access. All other clients should use
2354      * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2355      * logic.</p>
2356      *
2357      * @param iface the interface name to tether.
2358      * @return error a {@code TETHER_ERROR} value indicating success or failure type
2359      * @deprecated Use {@link TetheringManager#startTethering} instead
2360      *
2361      * {@hide}
2362      */
2363     @UnsupportedAppUsage
2364     @Deprecated
tether(String iface)2365     public int tether(String iface) {
2366         return mTetheringManager.tether(iface);
2367     }
2368 
2369     /**
2370      * Stop tethering the named interface.
2371      *
2372      * <p>This method requires the caller to hold either the
2373      * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2374      * or the ability to modify system settings as determined by
2375      * {@link android.provider.Settings.System#canWrite}.</p>
2376      *
2377      * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2378      * and WifiStateMachine which need direct access. All other clients should use
2379      * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2380      * logic.</p>
2381      *
2382      * @param iface the interface name to untether.
2383      * @return error a {@code TETHER_ERROR} value indicating success or failure type
2384      *
2385      * {@hide}
2386      */
2387     @UnsupportedAppUsage
2388     @Deprecated
untether(String iface)2389     public int untether(String iface) {
2390         return mTetheringManager.untether(iface);
2391     }
2392 
2393     /**
2394      * Check if the device allows for tethering.  It may be disabled via
2395      * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2396      * due to device configuration.
2397      *
2398      * <p>If this app does not have permission to use this API, it will always
2399      * return false rather than throw an exception.</p>
2400      *
2401      * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2402      * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2403      *
2404      * <p>Otherwise, this method requires the caller to hold the ability to modify system
2405      * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2406      *
2407      * @return a boolean - {@code true} indicating Tethering is supported.
2408      *
2409      * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2410      * {@hide}
2411      */
2412     @SystemApi
2413     @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2414             android.Manifest.permission.WRITE_SETTINGS})
isTetheringSupported()2415     public boolean isTetheringSupported() {
2416         return mTetheringManager.isTetheringSupported();
2417     }
2418 
2419     /**
2420      * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2421      *
2422      * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2423      * @hide
2424      */
2425     @SystemApi
2426     @Deprecated
2427     public static abstract class OnStartTetheringCallback {
2428         /**
2429          * Called when tethering has been successfully started.
2430          */
onTetheringStarted()2431         public void onTetheringStarted() {}
2432 
2433         /**
2434          * Called when starting tethering failed.
2435          */
onTetheringFailed()2436         public void onTetheringFailed() {}
2437     }
2438 
2439     /**
2440      * Convenient overload for
2441      * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2442      * handler to run on the current thread's {@link Looper}.
2443      *
2444      * @deprecated Use {@link TetheringManager#startTethering} instead.
2445      * @hide
2446      */
2447     @SystemApi
2448     @Deprecated
2449     @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
startTethering(int type, boolean showProvisioningUi, final OnStartTetheringCallback callback)2450     public void startTethering(int type, boolean showProvisioningUi,
2451             final OnStartTetheringCallback callback) {
2452         startTethering(type, showProvisioningUi, callback, null);
2453     }
2454 
2455     /**
2456      * Runs tether provisioning for the given type if needed and then starts tethering if
2457      * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2458      * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2459      * schedules tether provisioning re-checks if appropriate.
2460      *
2461      * @param type The type of tethering to start. Must be one of
2462      *         {@link ConnectivityManager.TETHERING_WIFI},
2463      *         {@link ConnectivityManager.TETHERING_USB}, or
2464      *         {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2465      * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2466      *         is one. This should be true the first time this function is called and also any time
2467      *         the user can see this UI. It gives users information from their carrier about the
2468      *         check failing and how they can sign up for tethering if possible.
2469      * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2470      *         of the result of trying to tether.
2471      * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2472      *
2473      * @deprecated Use {@link TetheringManager#startTethering} instead.
2474      * @hide
2475      */
2476     @SystemApi
2477     @Deprecated
2478     @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
startTethering(int type, boolean showProvisioningUi, final OnStartTetheringCallback callback, Handler handler)2479     public void startTethering(int type, boolean showProvisioningUi,
2480             final OnStartTetheringCallback callback, Handler handler) {
2481         Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
2482 
2483         final Executor executor = new Executor() {
2484             @Override
2485             public void execute(Runnable command) {
2486                 if (handler == null) {
2487                     command.run();
2488                 } else {
2489                     handler.post(command);
2490                 }
2491             }
2492         };
2493 
2494         final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2495             @Override
2496             public void onTetheringStarted() {
2497                 callback.onTetheringStarted();
2498             }
2499 
2500             @Override
2501             public void onTetheringFailed(final int error) {
2502                 callback.onTetheringFailed();
2503             }
2504         };
2505 
2506         final TetheringRequest request = new TetheringRequest.Builder(type)
2507                 .setShouldShowEntitlementUi(showProvisioningUi).build();
2508 
2509         mTetheringManager.startTethering(request, executor, tetheringCallback);
2510     }
2511 
2512     /**
2513      * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2514      * applicable.
2515      *
2516      * @param type The type of tethering to stop. Must be one of
2517      *         {@link ConnectivityManager.TETHERING_WIFI},
2518      *         {@link ConnectivityManager.TETHERING_USB}, or
2519      *         {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2520      *
2521      * @deprecated Use {@link TetheringManager#stopTethering} instead.
2522      * @hide
2523      */
2524     @SystemApi
2525     @Deprecated
2526     @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
stopTethering(int type)2527     public void stopTethering(int type) {
2528         mTetheringManager.stopTethering(type);
2529     }
2530 
2531     /**
2532      * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2533      * upstream status.
2534      *
2535      * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2536      * @hide
2537      */
2538     @SystemApi
2539     @Deprecated
2540     public abstract static class OnTetheringEventCallback {
2541 
2542         /**
2543          * Called when tethering upstream changed. This can be called multiple times and can be
2544          * called any time.
2545          *
2546          * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2547          * have any upstream.
2548          */
onUpstreamChanged(@ullable Network network)2549         public void onUpstreamChanged(@Nullable Network network) {}
2550     }
2551 
2552     @GuardedBy("mTetheringEventCallbacks")
2553     private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2554             mTetheringEventCallbacks = new ArrayMap<>();
2555 
2556     /**
2557      * Start listening to tethering change events. Any new added callback will receive the last
2558      * tethering status right away. If callback is registered when tethering has no upstream or
2559      * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2560      * with a null argument. The same callback object cannot be registered twice.
2561      *
2562      * @param executor the executor on which callback will be invoked.
2563      * @param callback the callback to be called when tethering has change events.
2564      *
2565      * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2566      * @hide
2567      */
2568     @SystemApi
2569     @Deprecated
2570     @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
registerTetheringEventCallback( @onNull @allbackExecutor Executor executor, @NonNull final OnTetheringEventCallback callback)2571     public void registerTetheringEventCallback(
2572             @NonNull @CallbackExecutor Executor executor,
2573             @NonNull final OnTetheringEventCallback callback) {
2574         Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2575 
2576         final TetheringEventCallback tetherCallback =
2577                 new TetheringEventCallback() {
2578                     @Override
2579                     public void onUpstreamChanged(@Nullable Network network) {
2580                         callback.onUpstreamChanged(network);
2581                     }
2582                 };
2583 
2584         synchronized (mTetheringEventCallbacks) {
2585             mTetheringEventCallbacks.put(callback, tetherCallback);
2586             mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
2587         }
2588     }
2589 
2590     /**
2591      * Remove tethering event callback previously registered with
2592      * {@link #registerTetheringEventCallback}.
2593      *
2594      * @param callback previously registered callback.
2595      *
2596      * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
2597      * @hide
2598      */
2599     @SystemApi
2600     @Deprecated
2601     @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
unregisterTetheringEventCallback( @onNull final OnTetheringEventCallback callback)2602     public void unregisterTetheringEventCallback(
2603             @NonNull final OnTetheringEventCallback callback) {
2604         Objects.requireNonNull(callback, "The callback must be non-null");
2605         synchronized (mTetheringEventCallbacks) {
2606             final TetheringEventCallback tetherCallback =
2607                     mTetheringEventCallbacks.remove(callback);
2608             mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
2609         }
2610     }
2611 
2612 
2613     /**
2614      * Get the list of regular expressions that define any tetherable
2615      * USB network interfaces.  If USB tethering is not supported by the
2616      * device, this list should be empty.
2617      *
2618      * @return an array of 0 or more regular expression Strings defining
2619      *        what interfaces are considered tetherable usb interfaces.
2620      *
2621      * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2622      * {@hide}
2623      */
2624     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2625     @UnsupportedAppUsage
2626     @Deprecated
getTetherableUsbRegexs()2627     public String[] getTetherableUsbRegexs() {
2628         return mTetheringManager.getTetherableUsbRegexs();
2629     }
2630 
2631     /**
2632      * Get the list of regular expressions that define any tetherable
2633      * Wifi network interfaces.  If Wifi tethering is not supported by the
2634      * device, this list should be empty.
2635      *
2636      * @return an array of 0 or more regular expression Strings defining
2637      *        what interfaces are considered tetherable wifi interfaces.
2638      *
2639      * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2640      * {@hide}
2641      */
2642     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2643     @UnsupportedAppUsage
2644     @Deprecated
getTetherableWifiRegexs()2645     public String[] getTetherableWifiRegexs() {
2646         return mTetheringManager.getTetherableWifiRegexs();
2647     }
2648 
2649     /**
2650      * Get the list of regular expressions that define any tetherable
2651      * Bluetooth network interfaces.  If Bluetooth tethering is not supported by the
2652      * device, this list should be empty.
2653      *
2654      * @return an array of 0 or more regular expression Strings defining
2655      *        what interfaces are considered tetherable bluetooth interfaces.
2656      *
2657      * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2658      *TetheringManager.TetheringInterfaceRegexps)} instead.
2659      * {@hide}
2660      */
2661     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2662     @UnsupportedAppUsage
2663     @Deprecated
getTetherableBluetoothRegexs()2664     public String[] getTetherableBluetoothRegexs() {
2665         return mTetheringManager.getTetherableBluetoothRegexs();
2666     }
2667 
2668     /**
2669      * Attempt to both alter the mode of USB and Tethering of USB.  A
2670      * utility method to deal with some of the complexity of USB - will
2671      * attempt to switch to Rndis and subsequently tether the resulting
2672      * interface on {@code true} or turn off tethering and switch off
2673      * Rndis on {@code false}.
2674      *
2675      * <p>This method requires the caller to hold either the
2676      * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2677      * or the ability to modify system settings as determined by
2678      * {@link android.provider.Settings.System#canWrite}.</p>
2679      *
2680      * @param enable a boolean - {@code true} to enable tethering
2681      * @return error a {@code TETHER_ERROR} value indicating success or failure type
2682      * @deprecated Use {@link TetheringManager#startTethering} instead
2683      *
2684      * {@hide}
2685      */
2686     @UnsupportedAppUsage
2687     @Deprecated
setUsbTethering(boolean enable)2688     public int setUsbTethering(boolean enable) {
2689         return mTetheringManager.setUsbTethering(enable);
2690     }
2691 
2692     /**
2693      * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2694      * {@hide}
2695      */
2696     @SystemApi
2697     @Deprecated
2698     public static final int TETHER_ERROR_NO_ERROR = TetheringManager.TETHER_ERROR_NO_ERROR;
2699     /**
2700      * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2701      * {@hide}
2702      */
2703     @Deprecated
2704     public static final int TETHER_ERROR_UNKNOWN_IFACE =
2705             TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2706     /**
2707      * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2708      * {@hide}
2709      */
2710     @Deprecated
2711     public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2712             TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2713     /**
2714      * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2715      * {@hide}
2716      */
2717     @Deprecated
2718     public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2719     /**
2720      * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2721      * {@hide}
2722      */
2723     @Deprecated
2724     public static final int TETHER_ERROR_UNAVAIL_IFACE =
2725             TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2726     /**
2727      * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
2728      * {@hide}
2729      */
2730     @Deprecated
2731     public static final int TETHER_ERROR_MASTER_ERROR =
2732             TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
2733     /**
2734      * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2735      * {@hide}
2736      */
2737     @Deprecated
2738     public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2739             TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2740     /**
2741      * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2742      * {@hide}
2743      */
2744     @Deprecated
2745     public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2746             TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2747     /**
2748      * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
2749      * {@hide}
2750      */
2751     @Deprecated
2752     public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
2753             TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
2754     /**
2755      * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
2756      * {@hide}
2757      */
2758     @Deprecated
2759     public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
2760             TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
2761     /**
2762      * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2763      * {@hide}
2764      */
2765     @Deprecated
2766     public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2767             TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2768     /**
2769      * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
2770      * {@hide}
2771      */
2772     @SystemApi
2773     @Deprecated
2774     public static final int TETHER_ERROR_PROVISION_FAILED =
2775             TetheringManager.TETHER_ERROR_PROVISIONING_FAILED;
2776     /**
2777      * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2778      * {@hide}
2779      */
2780     @Deprecated
2781     public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2782             TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2783     /**
2784      * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2785      * {@hide}
2786      */
2787     @SystemApi
2788     @Deprecated
2789     public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN =
2790             TetheringManager.TETHER_ERROR_ENTITLEMENT_UNKNOWN;
2791 
2792     /**
2793      * Get a more detailed error code after a Tethering or Untethering
2794      * request asynchronously failed.
2795      *
2796      * @param iface The name of the interface of interest
2797      * @return error The error code of the last error tethering or untethering the named
2798      *               interface
2799      *
2800      * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2801      * {@hide}
2802      */
2803     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2804     @UnsupportedAppUsage
2805     @Deprecated
getLastTetherError(String iface)2806     public int getLastTetherError(String iface) {
2807         int error = mTetheringManager.getLastTetherError(iface);
2808         if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2809             // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2810             // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2811             // instead.
2812             error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2813         }
2814         return error;
2815     }
2816 
2817     /** @hide */
2818     @Retention(RetentionPolicy.SOURCE)
2819     @IntDef(value = {
2820             TETHER_ERROR_NO_ERROR,
2821             TETHER_ERROR_PROVISION_FAILED,
2822             TETHER_ERROR_ENTITLEMENT_UNKONWN,
2823     })
2824     public @interface EntitlementResultCode {
2825     }
2826 
2827     /**
2828      * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
2829      * entitlement succeeded.
2830      *
2831      * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
2832      * @hide
2833      */
2834     @SystemApi
2835     @Deprecated
2836     public interface OnTetheringEntitlementResultListener  {
2837         /**
2838          * Called to notify entitlement result.
2839          *
2840          * @param resultCode an int value of entitlement result. It may be one of
2841          *         {@link #TETHER_ERROR_NO_ERROR},
2842          *         {@link #TETHER_ERROR_PROVISION_FAILED}, or
2843          *         {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2844          */
onTetheringEntitlementResult(@ntitlementResultCode int resultCode)2845         void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
2846     }
2847 
2848     /**
2849      * Get the last value of the entitlement check on this downstream. If the cached value is
2850      * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2851      * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2852      * guaranteed that the UI-based entitlement check will complete in any specific time period
2853      * and may in fact never complete. Any successful entitlement check the platform performs for
2854      * any reason will update the cached value.
2855      *
2856      * @param type the downstream type of tethering. Must be one of
2857      *         {@link #TETHERING_WIFI},
2858      *         {@link #TETHERING_USB}, or
2859      *         {@link #TETHERING_BLUETOOTH}.
2860      * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
2861      * @param executor the executor on which callback will be invoked.
2862      * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2863      *         notify the caller of the result of entitlement check. The listener may be called zero
2864      *         or one time.
2865      * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
2866      * {@hide}
2867      */
2868     @SystemApi
2869     @Deprecated
2870     @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi, @NonNull @CallbackExecutor Executor executor, @NonNull final OnTetheringEntitlementResultListener listener)2871     public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2872             @NonNull @CallbackExecutor Executor executor,
2873             @NonNull final OnTetheringEntitlementResultListener listener) {
2874         Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2875         ResultReceiver wrappedListener = new ResultReceiver(null) {
2876             @Override
2877             protected void onReceiveResult(int resultCode, Bundle resultData) {
2878                 Binder.withCleanCallingIdentity(() ->
2879                             executor.execute(() -> {
2880                                 listener.onTetheringEntitlementResult(resultCode);
2881                             }));
2882             }
2883         };
2884 
2885         mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
2886                     showEntitlementUi);
2887     }
2888 
2889     /**
2890      * Report network connectivity status.  This is currently used only
2891      * to alter status bar UI.
2892      * <p>This method requires the caller to hold the permission
2893      * {@link android.Manifest.permission#STATUS_BAR}.
2894      *
2895      * @param networkType The type of network you want to report on
2896      * @param percentage The quality of the connection 0 is bad, 100 is good
2897      * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
2898      * {@hide}
2899      */
reportInetCondition(int networkType, int percentage)2900     public void reportInetCondition(int networkType, int percentage) {
2901         printStackTrace();
2902         try {
2903             mService.reportInetCondition(networkType, percentage);
2904         } catch (RemoteException e) {
2905             throw e.rethrowFromSystemServer();
2906         }
2907     }
2908 
2909     /**
2910      * Report a problem network to the framework.  This provides a hint to the system
2911      * that there might be connectivity problems on this network and may cause
2912      * the framework to re-evaluate network connectivity and/or switch to another
2913      * network.
2914      *
2915      * @param network The {@link Network} the application was attempting to use
2916      *                or {@code null} to indicate the current default network.
2917      * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2918      *             working and non-working connectivity.
2919      */
2920     @Deprecated
reportBadNetwork(@ullable Network network)2921     public void reportBadNetwork(@Nullable Network network) {
2922         printStackTrace();
2923         try {
2924             // One of these will be ignored because it matches system's current state.
2925             // The other will trigger the necessary reevaluation.
2926             mService.reportNetworkConnectivity(network, true);
2927             mService.reportNetworkConnectivity(network, false);
2928         } catch (RemoteException e) {
2929             throw e.rethrowFromSystemServer();
2930         }
2931     }
2932 
2933     /**
2934      * Report to the framework whether a network has working connectivity.
2935      * This provides a hint to the system that a particular network is providing
2936      * working connectivity or not.  In response the framework may re-evaluate
2937      * the network's connectivity and might take further action thereafter.
2938      *
2939      * @param network The {@link Network} the application was attempting to use
2940      *                or {@code null} to indicate the current default network.
2941      * @param hasConnectivity {@code true} if the application was able to successfully access the
2942      *                        Internet using {@code network} or {@code false} if not.
2943      */
reportNetworkConnectivity(@ullable Network network, boolean hasConnectivity)2944     public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
2945         printStackTrace();
2946         try {
2947             mService.reportNetworkConnectivity(network, hasConnectivity);
2948         } catch (RemoteException e) {
2949             throw e.rethrowFromSystemServer();
2950         }
2951     }
2952 
2953     /**
2954      * Set a network-independent global http proxy.  This is not normally what you want
2955      * for typical HTTP proxies - they are general network dependent.  However if you're
2956      * doing something unusual like general internal filtering this may be useful.  On
2957      * a private network where the proxy is not accessible, you may break HTTP using this.
2958      *
2959      * @param p A {@link ProxyInfo} object defining the new global
2960      *        HTTP proxy.  A {@code null} value will clear the global HTTP proxy.
2961      * @hide
2962      */
2963     @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
setGlobalProxy(ProxyInfo p)2964     public void setGlobalProxy(ProxyInfo p) {
2965         try {
2966             mService.setGlobalProxy(p);
2967         } catch (RemoteException e) {
2968             throw e.rethrowFromSystemServer();
2969         }
2970     }
2971 
2972     /**
2973      * Retrieve any network-independent global HTTP proxy.
2974      *
2975      * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
2976      *        if no global HTTP proxy is set.
2977      * @hide
2978      */
getGlobalProxy()2979     public ProxyInfo getGlobalProxy() {
2980         try {
2981             return mService.getGlobalProxy();
2982         } catch (RemoteException e) {
2983             throw e.rethrowFromSystemServer();
2984         }
2985     }
2986 
2987     /**
2988      * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2989      * network-specific HTTP proxy.  If {@code network} is null, the
2990      * network-specific proxy returned is the proxy of the default active
2991      * network.
2992      *
2993      * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2994      *         global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2995      *         or when {@code network} is {@code null},
2996      *         the {@code ProxyInfo} for the default active network.  Returns
2997      *         {@code null} when no proxy applies or the caller doesn't have
2998      *         permission to use {@code network}.
2999      * @hide
3000      */
getProxyForNetwork(Network network)3001     public ProxyInfo getProxyForNetwork(Network network) {
3002         try {
3003             return mService.getProxyForNetwork(network);
3004         } catch (RemoteException e) {
3005             throw e.rethrowFromSystemServer();
3006         }
3007     }
3008 
3009     /**
3010      * Get the current default HTTP proxy settings.  If a global proxy is set it will be returned,
3011      * otherwise if this process is bound to a {@link Network} using
3012      * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3013      * the default network's proxy is returned.
3014      *
3015      * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3016      *        HTTP proxy is active.
3017      */
3018     @Nullable
getDefaultProxy()3019     public ProxyInfo getDefaultProxy() {
3020         return getProxyForNetwork(getBoundNetworkForProcess());
3021     }
3022 
3023     /**
3024      * Returns true if the hardware supports the given network type
3025      * else it returns false.  This doesn't indicate we have coverage
3026      * or are authorized onto a network, just whether or not the
3027      * hardware supports it.  For example a GSM phone without a SIM
3028      * should still return {@code true} for mobile data, but a wifi only
3029      * tablet would return {@code false}.
3030      *
3031      * @param networkType The network type we'd like to check
3032      * @return {@code true} if supported, else {@code false}
3033      * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3034      * @hide
3035      */
3036     @Deprecated
3037     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3038     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
isNetworkSupported(int networkType)3039     public boolean isNetworkSupported(int networkType) {
3040         try {
3041             return mService.isNetworkSupported(networkType);
3042         } catch (RemoteException e) {
3043             throw e.rethrowFromSystemServer();
3044         }
3045     }
3046 
3047     /**
3048      * Returns if the currently active data network is metered. A network is
3049      * classified as metered when the user is sensitive to heavy data usage on
3050      * that connection due to monetary costs, data limitations or
3051      * battery/performance issues. You should check this before doing large
3052      * data transfers, and warn the user or delay the operation until another
3053      * network is available.
3054      *
3055      * @return {@code true} if large transfers should be avoided, otherwise
3056      *        {@code false}.
3057      */
3058     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
isActiveNetworkMetered()3059     public boolean isActiveNetworkMetered() {
3060         try {
3061             return mService.isActiveNetworkMetered();
3062         } catch (RemoteException e) {
3063             throw e.rethrowFromSystemServer();
3064         }
3065     }
3066 
3067     /**
3068      * If the LockdownVpn mechanism is enabled, updates the vpn
3069      * with a reload of its profile.
3070      *
3071      * @return a boolean with {@code} indicating success
3072      *
3073      * <p>This method can only be called by the system UID
3074      * {@hide}
3075      */
updateLockdownVpn()3076     public boolean updateLockdownVpn() {
3077         try {
3078             return mService.updateLockdownVpn();
3079         } catch (RemoteException e) {
3080             throw e.rethrowFromSystemServer();
3081         }
3082     }
3083 
3084     /**
3085      * Check mobile provisioning.
3086      *
3087      * @param suggestedTimeOutMs, timeout in milliseconds
3088      *
3089      * @return time out that will be used, maybe less that suggestedTimeOutMs
3090      * -1 if an error.
3091      *
3092      * {@hide}
3093      */
checkMobileProvisioning(int suggestedTimeOutMs)3094     public int checkMobileProvisioning(int suggestedTimeOutMs) {
3095         int timeOutMs = -1;
3096         try {
3097             timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
3098         } catch (RemoteException e) {
3099             throw e.rethrowFromSystemServer();
3100         }
3101         return timeOutMs;
3102     }
3103 
3104     /**
3105      * Get the mobile provisioning url.
3106      * {@hide}
3107      */
3108     @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
getMobileProvisioningUrl()3109     public String getMobileProvisioningUrl() {
3110         try {
3111             return mService.getMobileProvisioningUrl();
3112         } catch (RemoteException e) {
3113             throw e.rethrowFromSystemServer();
3114         }
3115     }
3116 
3117     /**
3118      * Set sign in error notification to visible or in visible
3119      *
3120      * {@hide}
3121      * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3122      */
3123     @Deprecated
setProvisioningNotificationVisible(boolean visible, int networkType, String action)3124     public void setProvisioningNotificationVisible(boolean visible, int networkType,
3125             String action) {
3126         try {
3127             mService.setProvisioningNotificationVisible(visible, networkType, action);
3128         } catch (RemoteException e) {
3129             throw e.rethrowFromSystemServer();
3130         }
3131     }
3132 
3133     /**
3134      * Set the value for enabling/disabling airplane mode
3135      *
3136      * @param enable whether to enable airplane mode or not
3137      *
3138      * @hide
3139      */
3140     @RequiresPermission(anyOf = {
3141             android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3142             android.Manifest.permission.NETWORK_SETTINGS,
3143             android.Manifest.permission.NETWORK_SETUP_WIZARD,
3144             android.Manifest.permission.NETWORK_STACK})
3145     @SystemApi
setAirplaneMode(boolean enable)3146     public void setAirplaneMode(boolean enable) {
3147         try {
3148             mService.setAirplaneMode(enable);
3149         } catch (RemoteException e) {
3150             throw e.rethrowFromSystemServer();
3151         }
3152     }
3153 
3154     /** {@hide} - returns the factory serial number */
3155     @UnsupportedAppUsage
3156     @RequiresPermission(anyOf = {
3157             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3158             android.Manifest.permission.NETWORK_FACTORY})
registerNetworkFactory(Messenger messenger, String name)3159     public int registerNetworkFactory(Messenger messenger, String name) {
3160         try {
3161             return mService.registerNetworkFactory(messenger, name);
3162         } catch (RemoteException e) {
3163             throw e.rethrowFromSystemServer();
3164         }
3165     }
3166 
3167     /** {@hide} */
3168     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
3169     @RequiresPermission(anyOf = {
3170             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3171             android.Manifest.permission.NETWORK_FACTORY})
unregisterNetworkFactory(Messenger messenger)3172     public void unregisterNetworkFactory(Messenger messenger) {
3173         try {
3174             mService.unregisterNetworkFactory(messenger);
3175         } catch (RemoteException e) {
3176             throw e.rethrowFromSystemServer();
3177         }
3178     }
3179 
3180     /**
3181      * Registers the specified {@link NetworkProvider}.
3182      * Each listener must only be registered once. The listener can be unregistered with
3183      * {@link #unregisterNetworkProvider}.
3184      *
3185      * @param provider the provider to register
3186      * @return the ID of the provider. This ID must be used by the provider when registering
3187      *         {@link android.net.NetworkAgent}s.
3188      * @hide
3189      */
3190     @SystemApi
3191     @RequiresPermission(anyOf = {
3192             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3193             android.Manifest.permission.NETWORK_FACTORY})
registerNetworkProvider(@onNull NetworkProvider provider)3194     public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3195         if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3196             throw new IllegalStateException("NetworkProviders can only be registered once");
3197         }
3198 
3199         try {
3200             int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3201                     provider.getName());
3202             provider.setProviderId(providerId);
3203         } catch (RemoteException e) {
3204             throw e.rethrowFromSystemServer();
3205         }
3206         return provider.getProviderId();
3207     }
3208 
3209     /**
3210      * Unregisters the specified NetworkProvider.
3211      *
3212      * @param provider the provider to unregister
3213      * @hide
3214      */
3215     @SystemApi
3216     @RequiresPermission(anyOf = {
3217             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3218             android.Manifest.permission.NETWORK_FACTORY})
unregisterNetworkProvider(@onNull NetworkProvider provider)3219     public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3220         try {
3221             mService.unregisterNetworkProvider(provider.getMessenger());
3222         } catch (RemoteException e) {
3223             throw e.rethrowFromSystemServer();
3224         }
3225         provider.setProviderId(NetworkProvider.ID_NONE);
3226     }
3227 
3228 
3229     /** @hide exposed via the NetworkProvider class. */
3230     @RequiresPermission(anyOf = {
3231             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3232             android.Manifest.permission.NETWORK_FACTORY})
declareNetworkRequestUnfulfillable(@onNull NetworkRequest request)3233     public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3234         try {
3235             mService.declareNetworkRequestUnfulfillable(request);
3236         } catch (RemoteException e) {
3237             throw e.rethrowFromSystemServer();
3238         }
3239     }
3240 
3241     // TODO : remove this method. It is a stopgap measure to help sheperding a number
3242     // of dependent changes that would conflict throughout the automerger graph. Having this
3243     // temporarily helps with the process of going through with all these dependent changes across
3244     // the entire tree.
3245     /**
3246      * @hide
3247      * Register a NetworkAgent with ConnectivityService.
3248      * @return Network corresponding to NetworkAgent.
3249      */
3250     @RequiresPermission(anyOf = {
3251             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3252             android.Manifest.permission.NETWORK_FACTORY})
registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp, NetworkCapabilities nc, int score, NetworkAgentConfig config)3253     public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
3254             NetworkCapabilities nc, int score, NetworkAgentConfig config) {
3255         return registerNetworkAgent(messenger, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
3256     }
3257 
3258     /**
3259      * @hide
3260      * Register a NetworkAgent with ConnectivityService.
3261      * @return Network corresponding to NetworkAgent.
3262      */
3263     @RequiresPermission(anyOf = {
3264             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3265             android.Manifest.permission.NETWORK_FACTORY})
registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp, NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId)3266     public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
3267             NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
3268         try {
3269             return mService.registerNetworkAgent(messenger, ni, lp, nc, score, config, providerId);
3270         } catch (RemoteException e) {
3271             throw e.rethrowFromSystemServer();
3272         }
3273     }
3274 
3275     /**
3276      * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3277      * changes. Should be extended by applications wanting notifications.
3278      *
3279      * A {@code NetworkCallback} is registered by calling
3280      * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3281      * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3282      * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3283      * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3284      * A {@code NetworkCallback} should be registered at most once at any time.
3285      * A {@code NetworkCallback} that has been unregistered can be registered again.
3286      */
3287     public static class NetworkCallback {
3288         /**
3289          * Called when the framework connects to a new network to evaluate whether it satisfies this
3290          * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3291          * callback. There is no guarantee that this new network will satisfy any requests, or that
3292          * the network will stay connected for longer than the time necessary to evaluate it.
3293          * <p>
3294          * Most applications <b>should not</b> act on this callback, and should instead use
3295          * {@link #onAvailable}. This callback is intended for use by applications that can assist
3296          * the framework in properly evaluating the network &mdash; for example, an application that
3297          * can automatically log in to a captive portal without user intervention.
3298          *
3299          * @param network The {@link Network} of the network that is being evaluated.
3300          *
3301          * @hide
3302          */
onPreCheck(@onNull Network network)3303         public void onPreCheck(@NonNull Network network) {}
3304 
3305         /**
3306          * Called when the framework connects and has declared a new network ready for use.
3307          * This callback may be called more than once if the {@link Network} that is
3308          * satisfying the request changes.
3309          *
3310          * @param network The {@link Network} of the satisfying network.
3311          * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3312          * @param linkProperties The {@link LinkProperties} of the satisfying network.
3313          * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3314          * @hide
3315          */
onAvailable(@onNull Network network, @NonNull NetworkCapabilities networkCapabilities, @NonNull LinkProperties linkProperties, boolean blocked)3316         public void onAvailable(@NonNull Network network,
3317                 @NonNull NetworkCapabilities networkCapabilities,
3318                 @NonNull LinkProperties linkProperties, boolean blocked) {
3319             // Internally only this method is called when a new network is available, and
3320             // it calls the callback in the same way and order that older versions used
3321             // to call so as not to change the behavior.
3322             onAvailable(network);
3323             if (!networkCapabilities.hasCapability(
3324                     NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3325                 onNetworkSuspended(network);
3326             }
3327             onCapabilitiesChanged(network, networkCapabilities);
3328             onLinkPropertiesChanged(network, linkProperties);
3329             onBlockedStatusChanged(network, blocked);
3330         }
3331 
3332         /**
3333          * Called when the framework connects and has declared a new network ready for use.
3334          *
3335          * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3336          * be available at the same time, and onAvailable will be called for each of these as they
3337          * appear.
3338          *
3339          * <p>For callbacks registered with {@link #requestNetwork} and
3340          * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3341          * is the new best network for this request and is now tracked by this callback ; this
3342          * callback will no longer receive method calls about other networks that may have been
3343          * passed to this method previously. The previously-best network may have disconnected, or
3344          * it may still be around and the newly-best network may simply be better.
3345          *
3346          * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3347          * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3348          * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3349          * to {@link #onBlockedStatusChanged(Network, boolean)}.
3350          *
3351          * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3352          * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3353          * this callback as this is prone to race conditions (there is no guarantee the objects
3354          * returned by these methods will be current). Instead, wait for a call to
3355          * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3356          * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3357          * to be well-ordered with respect to other callbacks.
3358          *
3359          * @param network The {@link Network} of the satisfying network.
3360          */
onAvailable(@onNull Network network)3361         public void onAvailable(@NonNull Network network) {}
3362 
3363         /**
3364          * Called when the network is about to be lost, typically because there are no outstanding
3365          * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3366          * with the new replacement network for graceful handover. This method is not guaranteed
3367          * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3368          * network is suddenly disconnected.
3369          *
3370          * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3371          * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3372          * this callback as this is prone to race conditions ; calling these methods while in a
3373          * callback may return an outdated or even a null object.
3374          *
3375          * @param network The {@link Network} that is about to be lost.
3376          * @param maxMsToLive The time in milliseconds the system intends to keep the network
3377          *                    connected for graceful handover; note that the network may still
3378          *                    suffer a hard loss at any time.
3379          */
onLosing(@onNull Network network, int maxMsToLive)3380         public void onLosing(@NonNull Network network, int maxMsToLive) {}
3381 
3382         /**
3383          * Called when a network disconnects or otherwise no longer satisfies this request or
3384          * callback.
3385          *
3386          * <p>If the callback was registered with requestNetwork() or
3387          * registerDefaultNetworkCallback(), it will only be invoked against the last network
3388          * returned by onAvailable() when that network is lost and no other network satisfies
3389          * the criteria of the request.
3390          *
3391          * <p>If the callback was registered with registerNetworkCallback() it will be called for
3392          * each network which no longer satisfies the criteria of the callback.
3393          *
3394          * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3395          * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3396          * this callback as this is prone to race conditions ; calling these methods while in a
3397          * callback may return an outdated or even a null object.
3398          *
3399          * @param network The {@link Network} lost.
3400          */
onLost(@onNull Network network)3401         public void onLost(@NonNull Network network) {}
3402 
3403         /**
3404          * Called if no network is found within the timeout time specified in
3405          * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3406          * requested network request cannot be fulfilled (whether or not a timeout was
3407          * specified). When this callback is invoked the associated
3408          * {@link NetworkRequest} will have already been removed and released, as if
3409          * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3410          */
onUnavailable()3411         public void onUnavailable() {}
3412 
3413         /**
3414          * Called when the network corresponding to this request changes capabilities but still
3415          * satisfies the requested criteria.
3416          *
3417          * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3418          * to be called immediately after {@link #onAvailable}.
3419          *
3420          * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3421          * ConnectivityManager methods in this callback as this is prone to race conditions :
3422          * calling these methods while in a callback may return an outdated or even a null object.
3423          *
3424          * @param network The {@link Network} whose capabilities have changed.
3425          * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3426          *                            network.
3427          */
onCapabilitiesChanged(@onNull Network network, @NonNull NetworkCapabilities networkCapabilities)3428         public void onCapabilitiesChanged(@NonNull Network network,
3429                 @NonNull NetworkCapabilities networkCapabilities) {}
3430 
3431         /**
3432          * Called when the network corresponding to this request changes {@link LinkProperties}.
3433          *
3434          * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3435          * to be called immediately after {@link #onAvailable}.
3436          *
3437          * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3438          * ConnectivityManager methods in this callback as this is prone to race conditions :
3439          * calling these methods while in a callback may return an outdated or even a null object.
3440          *
3441          * @param network The {@link Network} whose link properties have changed.
3442          * @param linkProperties The new {@link LinkProperties} for this network.
3443          */
onLinkPropertiesChanged(@onNull Network network, @NonNull LinkProperties linkProperties)3444         public void onLinkPropertiesChanged(@NonNull Network network,
3445                 @NonNull LinkProperties linkProperties) {}
3446 
3447         /**
3448          * Called when the network the framework connected to for this request suspends data
3449          * transmission temporarily.
3450          *
3451          * <p>This generally means that while the TCP connections are still live temporarily
3452          * network data fails to transfer. To give a specific example, this is used on cellular
3453          * networks to mask temporary outages when driving through a tunnel, etc. In general this
3454          * means read operations on sockets on this network will block once the buffers are
3455          * drained, and write operations will block once the buffers are full.
3456          *
3457          * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3458          * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3459          * this callback as this is prone to race conditions (there is no guarantee the objects
3460          * returned by these methods will be current).
3461          *
3462          * @hide
3463          */
onNetworkSuspended(@onNull Network network)3464         public void onNetworkSuspended(@NonNull Network network) {}
3465 
3466         /**
3467          * Called when the network the framework connected to for this request
3468          * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3469          * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3470 
3471          * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3472          * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3473          * this callback as this is prone to race conditions : calling these methods while in a
3474          * callback may return an outdated or even a null object.
3475          *
3476          * @hide
3477          */
onNetworkResumed(@onNull Network network)3478         public void onNetworkResumed(@NonNull Network network) {}
3479 
3480         /**
3481          * Called when access to the specified network is blocked or unblocked.
3482          *
3483          * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3484          * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3485          * this callback as this is prone to race conditions : calling these methods while in a
3486          * callback may return an outdated or even a null object.
3487          *
3488          * @param network The {@link Network} whose blocked status has changed.
3489          * @param blocked The blocked status of this {@link Network}.
3490          */
onBlockedStatusChanged(@onNull Network network, boolean blocked)3491         public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3492 
3493         private NetworkRequest networkRequest;
3494     }
3495 
3496     /**
3497      * Constant error codes used by ConnectivityService to communicate about failures and errors
3498      * across a Binder boundary.
3499      * @hide
3500      */
3501     public interface Errors {
3502         int TOO_MANY_REQUESTS = 1;
3503     }
3504 
3505     /** @hide */
3506     public static class TooManyRequestsException extends RuntimeException {}
3507 
convertServiceException(ServiceSpecificException e)3508     private static RuntimeException convertServiceException(ServiceSpecificException e) {
3509         switch (e.errorCode) {
3510             case Errors.TOO_MANY_REQUESTS:
3511                 return new TooManyRequestsException();
3512             default:
3513                 Log.w(TAG, "Unknown service error code " + e.errorCode);
3514                 return new RuntimeException(e);
3515         }
3516     }
3517 
3518     private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
3519     /** @hide */
3520     public static final int CALLBACK_PRECHECK            = BASE + 1;
3521     /** @hide */
3522     public static final int CALLBACK_AVAILABLE           = BASE + 2;
3523     /** @hide arg1 = TTL */
3524     public static final int CALLBACK_LOSING              = BASE + 3;
3525     /** @hide */
3526     public static final int CALLBACK_LOST                = BASE + 4;
3527     /** @hide */
3528     public static final int CALLBACK_UNAVAIL             = BASE + 5;
3529     /** @hide */
3530     public static final int CALLBACK_CAP_CHANGED         = BASE + 6;
3531     /** @hide */
3532     public static final int CALLBACK_IP_CHANGED          = BASE + 7;
3533     /** @hide obj = NetworkCapabilities, arg1 = seq number */
3534     private static final int EXPIRE_LEGACY_REQUEST       = BASE + 8;
3535     /** @hide */
3536     public static final int CALLBACK_SUSPENDED           = BASE + 9;
3537     /** @hide */
3538     public static final int CALLBACK_RESUMED             = BASE + 10;
3539     /** @hide */
3540     public static final int CALLBACK_BLK_CHANGED         = BASE + 11;
3541 
3542     /** @hide */
getCallbackName(int whichCallback)3543     public static String getCallbackName(int whichCallback) {
3544         switch (whichCallback) {
3545             case CALLBACK_PRECHECK:     return "CALLBACK_PRECHECK";
3546             case CALLBACK_AVAILABLE:    return "CALLBACK_AVAILABLE";
3547             case CALLBACK_LOSING:       return "CALLBACK_LOSING";
3548             case CALLBACK_LOST:         return "CALLBACK_LOST";
3549             case CALLBACK_UNAVAIL:      return "CALLBACK_UNAVAIL";
3550             case CALLBACK_CAP_CHANGED:  return "CALLBACK_CAP_CHANGED";
3551             case CALLBACK_IP_CHANGED:   return "CALLBACK_IP_CHANGED";
3552             case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3553             case CALLBACK_SUSPENDED:    return "CALLBACK_SUSPENDED";
3554             case CALLBACK_RESUMED:      return "CALLBACK_RESUMED";
3555             case CALLBACK_BLK_CHANGED:  return "CALLBACK_BLK_CHANGED";
3556             default:
3557                 return Integer.toString(whichCallback);
3558         }
3559     }
3560 
3561     private class CallbackHandler extends Handler {
3562         private static final String TAG = "ConnectivityManager.CallbackHandler";
3563         private static final boolean DBG = false;
3564 
CallbackHandler(Looper looper)3565         CallbackHandler(Looper looper) {
3566             super(looper);
3567         }
3568 
CallbackHandler(Handler handler)3569         CallbackHandler(Handler handler) {
3570             this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
3571         }
3572 
3573         @Override
handleMessage(Message message)3574         public void handleMessage(Message message) {
3575             if (message.what == EXPIRE_LEGACY_REQUEST) {
3576                 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3577                 return;
3578             }
3579 
3580             final NetworkRequest request = getObject(message, NetworkRequest.class);
3581             final Network network = getObject(message, Network.class);
3582             final NetworkCallback callback;
3583             synchronized (sCallbacks) {
3584                 callback = sCallbacks.get(request);
3585                 if (callback == null) {
3586                     Log.w(TAG,
3587                             "callback not found for " + getCallbackName(message.what) + " message");
3588                     return;
3589                 }
3590                 if (message.what == CALLBACK_UNAVAIL) {
3591                     sCallbacks.remove(request);
3592                     callback.networkRequest = ALREADY_UNREGISTERED;
3593                 }
3594             }
3595             if (DBG) {
3596                 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
3597             }
3598 
3599             switch (message.what) {
3600                 case CALLBACK_PRECHECK: {
3601                     callback.onPreCheck(network);
3602                     break;
3603                 }
3604                 case CALLBACK_AVAILABLE: {
3605                     NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3606                     LinkProperties lp = getObject(message, LinkProperties.class);
3607                     callback.onAvailable(network, cap, lp, message.arg1 != 0);
3608                     break;
3609                 }
3610                 case CALLBACK_LOSING: {
3611                     callback.onLosing(network, message.arg1);
3612                     break;
3613                 }
3614                 case CALLBACK_LOST: {
3615                     callback.onLost(network);
3616                     break;
3617                 }
3618                 case CALLBACK_UNAVAIL: {
3619                     callback.onUnavailable();
3620                     break;
3621                 }
3622                 case CALLBACK_CAP_CHANGED: {
3623                     NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3624                     callback.onCapabilitiesChanged(network, cap);
3625                     break;
3626                 }
3627                 case CALLBACK_IP_CHANGED: {
3628                     LinkProperties lp = getObject(message, LinkProperties.class);
3629                     callback.onLinkPropertiesChanged(network, lp);
3630                     break;
3631                 }
3632                 case CALLBACK_SUSPENDED: {
3633                     callback.onNetworkSuspended(network);
3634                     break;
3635                 }
3636                 case CALLBACK_RESUMED: {
3637                     callback.onNetworkResumed(network);
3638                     break;
3639                 }
3640                 case CALLBACK_BLK_CHANGED: {
3641                     boolean blocked = message.arg1 != 0;
3642                     callback.onBlockedStatusChanged(network, blocked);
3643                 }
3644             }
3645         }
3646 
getObject(Message msg, Class<T> c)3647         private <T> T getObject(Message msg, Class<T> c) {
3648             return (T) msg.getData().getParcelable(c.getSimpleName());
3649         }
3650     }
3651 
getDefaultHandler()3652     private CallbackHandler getDefaultHandler() {
3653         synchronized (sCallbacks) {
3654             if (sCallbackHandler == null) {
3655                 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
3656             }
3657             return sCallbackHandler;
3658         }
3659     }
3660 
3661     private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3662     private static CallbackHandler sCallbackHandler;
3663 
3664     private static final int LISTEN  = 1;
3665     private static final int REQUEST = 2;
3666 
sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback, int timeoutMs, int action, int legacyType, CallbackHandler handler)3667     private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3668             int timeoutMs, int action, int legacyType, CallbackHandler handler) {
3669         printStackTrace();
3670         checkCallbackNotNull(callback);
3671         Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
3672         final NetworkRequest request;
3673         final String callingPackageName = mContext.getOpPackageName();
3674         try {
3675             synchronized(sCallbacks) {
3676                 if (callback.networkRequest != null
3677                         && callback.networkRequest != ALREADY_UNREGISTERED) {
3678                     // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3679                     // and requests (http://b/20701525).
3680                     Log.e(TAG, "NetworkCallback was already registered");
3681                 }
3682                 Messenger messenger = new Messenger(handler);
3683                 Binder binder = new Binder();
3684                 if (action == LISTEN) {
3685                     request = mService.listenForNetwork(
3686                             need, messenger, binder, callingPackageName);
3687                 } else {
3688                     request = mService.requestNetwork(
3689                             need, messenger, timeoutMs, binder, legacyType, callingPackageName);
3690                 }
3691                 if (request != null) {
3692                     sCallbacks.put(request, callback);
3693                 }
3694                 callback.networkRequest = request;
3695             }
3696         } catch (RemoteException e) {
3697             throw e.rethrowFromSystemServer();
3698         } catch (ServiceSpecificException e) {
3699             throw convertServiceException(e);
3700         }
3701         return request;
3702     }
3703 
3704     /**
3705      * Helper function to request a network with a particular legacy type.
3706      *
3707      * This API is only for use in internal system code that requests networks with legacy type and
3708      * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
3709      * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
3710      *
3711      * @param request {@link NetworkRequest} describing this request.
3712      * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3713      *                  before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3714      *                  be a positive value (i.e. >0).
3715      * @param legacyType to specify the network type(#TYPE_*).
3716      * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3717      * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3718      *                        the callback must not be shared - it uniquely specifies this request.
3719      *
3720      * @hide
3721      */
3722     @SystemApi
3723     @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
requestNetwork(@onNull NetworkRequest request, int timeoutMs, int legacyType, @NonNull Handler handler, @NonNull NetworkCallback networkCallback)3724     public void requestNetwork(@NonNull NetworkRequest request,
3725             int timeoutMs, int legacyType, @NonNull Handler handler,
3726             @NonNull NetworkCallback networkCallback) {
3727         if (legacyType == TYPE_NONE) {
3728             throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3729         }
3730         CallbackHandler cbHandler = new CallbackHandler(handler);
3731         NetworkCapabilities nc = request.networkCapabilities;
3732         sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
3733     }
3734 
3735     /**
3736      * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3737      *
3738      * <p>This method will attempt to find the best network that matches the passed
3739      * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3740      * criteria. The platform will evaluate which network is the best at its own discretion.
3741      * Throughput, latency, cost per byte, policy, user preference and other considerations
3742      * may be factored in the decision of what is considered the best network.
3743      *
3744      * <p>As long as this request is outstanding, the platform will try to maintain the best network
3745      * matching this request, while always attempting to match the request to a better network if
3746      * possible. If a better match is found, the platform will switch this request to the now-best
3747      * network and inform the app of the newly best network by invoking
3748      * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3749      * will not try to maintain any other network than the best one currently matching the request:
3750      * a network not matching any network request may be disconnected at any time.
3751      *
3752      * <p>For example, an application could use this method to obtain a connected cellular network
3753      * even if the device currently has a data connection over Ethernet. This may cause the cellular
3754      * radio to consume additional power. Or, an application could inform the system that it wants
3755      * a network supporting sending MMSes and have the system let it know about the currently best
3756      * MMS-supporting network through the provided {@link NetworkCallback}.
3757      *
3758      * <p>The status of the request can be followed by listening to the various callbacks described
3759      * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3760      * used to direct traffic to the network (although accessing some networks may be subject to
3761      * holding specific permissions). Callers will learn about the specific characteristics of the
3762      * network through
3763      * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3764      * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3765      * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3766      * matching the request at any given time; therefore when a better network matching the request
3767      * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3768      * with the new network after which no further updates are given about the previously-best
3769      * network, unless it becomes the best again at some later time. All callbacks are invoked
3770      * in order on the same thread, which by default is a thread created by the framework running
3771      * in the app.
3772      * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3773      * callbacks are invoked.
3774      *
3775      * <p>This{@link NetworkRequest} will live until released via
3776      * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3777      * which point the system may let go of the network at any time.
3778      *
3779      * <p>A version of this method which takes a timeout is
3780      * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3781      * wait for a limited amount of time for the network to become unavailable.
3782      *
3783      * <p>It is presently unsupported to request a network with mutable
3784      * {@link NetworkCapabilities} such as
3785      * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3786      * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3787      * as these {@code NetworkCapabilities} represent states that a particular
3788      * network may never attain, and whether a network will attain these states
3789      * is unknown prior to bringing up the network so the framework does not
3790      * know how to go about satisfying a request with these capabilities.
3791      *
3792      * <p>This method requires the caller to hold either the
3793      * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3794      * or the ability to modify system settings as determined by
3795      * {@link android.provider.Settings.System#canWrite}.</p>
3796      *
3797      * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3798      * number of outstanding requests to 100 per app (identified by their UID), shared with
3799      * all variants of this method, of {@link #registerNetworkCallback} as well as
3800      * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3801      * Requesting a network with this method will count toward this limit. If this limit is
3802      * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3803      * make sure to unregister the callbacks with
3804      * {@link #unregisterNetworkCallback(NetworkCallback)}.
3805      *
3806      * @param request {@link NetworkRequest} describing this request.
3807      * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3808      *                        the callback must not be shared - it uniquely specifies this request.
3809      *                        The callback is invoked on the default internal Handler.
3810      * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3811      * @throws SecurityException if missing the appropriate permissions.
3812      * @throws RuntimeException if the app already has too many callbacks registered.
3813      */
requestNetwork(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback)3814     public void requestNetwork(@NonNull NetworkRequest request,
3815             @NonNull NetworkCallback networkCallback) {
3816         requestNetwork(request, networkCallback, getDefaultHandler());
3817     }
3818 
3819     /**
3820      * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3821      *
3822      * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3823      * but runs all the callbacks on the passed Handler.
3824      *
3825      * <p>This method has the same permission requirements as
3826      * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3827      * and throws the same exceptions in the same conditions.
3828      *
3829      * @param request {@link NetworkRequest} describing this request.
3830      * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3831      *                        the callback must not be shared - it uniquely specifies this request.
3832      * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3833      */
requestNetwork(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback, @NonNull Handler handler)3834     public void requestNetwork(@NonNull NetworkRequest request,
3835             @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
3836         CallbackHandler cbHandler = new CallbackHandler(handler);
3837         NetworkCapabilities nc = request.networkCapabilities;
3838         sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
3839     }
3840 
3841     /**
3842      * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3843      * by a timeout.
3844      *
3845      * This function behaves identically to the non-timed-out version
3846      * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3847      * is not found within the given time (in milliseconds) the
3848      * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3849      * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3850      * not have to be released if timed-out (it is automatically released). Unregistering a
3851      * request that timed out is not an error.
3852      *
3853      * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3854      * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3855      * for that purpose. Calling this method will attempt to bring up the requested network.
3856      *
3857      * <p>This method has the same permission requirements as
3858      * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3859      * and throws the same exceptions in the same conditions.
3860      *
3861      * @param request {@link NetworkRequest} describing this request.
3862      * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3863      *                        the callback must not be shared - it uniquely specifies this request.
3864      * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3865      *                  before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3866      *                  be a positive value (i.e. >0).
3867      */
requestNetwork(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback, int timeoutMs)3868     public void requestNetwork(@NonNull NetworkRequest request,
3869             @NonNull NetworkCallback networkCallback, int timeoutMs) {
3870         checkTimeout(timeoutMs);
3871         NetworkCapabilities nc = request.networkCapabilities;
3872         sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3873                 getDefaultHandler());
3874     }
3875 
3876     /**
3877      * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3878      * by a timeout.
3879      *
3880      * This method behaves identically to
3881      * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3882      * on the passed Handler.
3883      *
3884      * <p>This method has the same permission requirements as
3885      * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3886      * and throws the same exceptions in the same conditions.
3887      *
3888      * @param request {@link NetworkRequest} describing this request.
3889      * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3890      *                        the callback must not be shared - it uniquely specifies this request.
3891      * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3892      * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3893      *                  before {@link NetworkCallback#onUnavailable} is called.
3894      */
requestNetwork(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs)3895     public void requestNetwork(@NonNull NetworkRequest request,
3896             @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
3897         checkTimeout(timeoutMs);
3898         CallbackHandler cbHandler = new CallbackHandler(handler);
3899         NetworkCapabilities nc = request.networkCapabilities;
3900         sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
3901     }
3902 
3903     /**
3904      * The lookup key for a {@link Network} object included with the intent after
3905      * successfully finding a network for the applications request.  Retrieve it with
3906      * {@link android.content.Intent#getParcelableExtra(String)}.
3907      * <p>
3908      * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3909      * then you must get a ConnectivityManager instance before doing so.
3910      */
3911     public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
3912 
3913     /**
3914      * The lookup key for a {@link NetworkRequest} object included with the intent after
3915      * successfully finding a network for the applications request.  Retrieve it with
3916      * {@link android.content.Intent#getParcelableExtra(String)}.
3917      */
3918     public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
3919 
3920 
3921     /**
3922      * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3923      *
3924      * This function behaves identically to the version that takes a NetworkCallback, but instead
3925      * of {@link NetworkCallback} a {@link PendingIntent} is used.  This means
3926      * the request may outlive the calling application and get called back when a suitable
3927      * network is found.
3928      * <p>
3929      * The operation is an Intent broadcast that goes to a broadcast receiver that
3930      * you registered with {@link Context#registerReceiver} or through the
3931      * &lt;receiver&gt; tag in an AndroidManifest.xml file
3932      * <p>
3933      * The operation Intent is delivered with two extras, a {@link Network} typed
3934      * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3935      * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3936      * the original requests parameters.  It is important to create a new,
3937      * {@link NetworkCallback} based request before completing the processing of the
3938      * Intent to reserve the network or it will be released shortly after the Intent
3939      * is processed.
3940      * <p>
3941      * If there is already a request for this Intent registered (with the equality of
3942      * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3943      * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3944      * <p>
3945      * The request may be released normally by calling
3946      * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
3947      * <p>It is presently unsupported to request a network with either
3948      * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3949      * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3950      * as these {@code NetworkCapabilities} represent states that a particular
3951      * network may never attain, and whether a network will attain these states
3952      * is unknown prior to bringing up the network so the framework does not
3953      * know how to go about satisfying a request with these capabilities.
3954      *
3955      * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3956      * number of outstanding requests to 100 per app (identified by their UID), shared with
3957      * all variants of this method, of {@link #registerNetworkCallback} as well as
3958      * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3959      * Requesting a network with this method will count toward this limit. If this limit is
3960      * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3961      * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3962      * or {@link #releaseNetworkRequest(PendingIntent)}.
3963      *
3964      * <p>This method requires the caller to hold either the
3965      * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3966      * or the ability to modify system settings as determined by
3967      * {@link android.provider.Settings.System#canWrite}.</p>
3968      *
3969      * @param request {@link NetworkRequest} describing this request.
3970      * @param operation Action to perform when the network is available (corresponds
3971      *                  to the {@link NetworkCallback#onAvailable} call.  Typically
3972      *                  comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3973      * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3974      * @throws SecurityException if missing the appropriate permissions.
3975      * @throws RuntimeException if the app already has too many callbacks registered.
3976      */
requestNetwork(@onNull NetworkRequest request, @NonNull PendingIntent operation)3977     public void requestNetwork(@NonNull NetworkRequest request,
3978             @NonNull PendingIntent operation) {
3979         printStackTrace();
3980         checkPendingIntentNotNull(operation);
3981         try {
3982             mService.pendingRequestForNetwork(
3983                     request.networkCapabilities, operation, mContext.getOpPackageName());
3984         } catch (RemoteException e) {
3985             throw e.rethrowFromSystemServer();
3986         } catch (ServiceSpecificException e) {
3987             throw convertServiceException(e);
3988         }
3989     }
3990 
3991     /**
3992      * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3993      * <p>
3994      * This method has the same behavior as
3995      * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
3996      * releasing network resources and disconnecting.
3997      *
3998      * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3999      *                  PendingIntent passed to
4000      *                  {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4001      *                  corresponding NetworkRequest you'd like to remove. Cannot be null.
4002      */
releaseNetworkRequest(@onNull PendingIntent operation)4003     public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4004         printStackTrace();
4005         checkPendingIntentNotNull(operation);
4006         try {
4007             mService.releasePendingNetworkRequest(operation);
4008         } catch (RemoteException e) {
4009             throw e.rethrowFromSystemServer();
4010         }
4011     }
4012 
checkPendingIntentNotNull(PendingIntent intent)4013     private static void checkPendingIntentNotNull(PendingIntent intent) {
4014         Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4015     }
4016 
checkCallbackNotNull(NetworkCallback callback)4017     private static void checkCallbackNotNull(NetworkCallback callback) {
4018         Preconditions.checkNotNull(callback, "null NetworkCallback");
4019     }
4020 
checkTimeout(int timeoutMs)4021     private static void checkTimeout(int timeoutMs) {
4022         Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
4023     }
4024 
4025     /**
4026      * Registers to receive notifications about all networks which satisfy the given
4027      * {@link NetworkRequest}.  The callbacks will continue to be called until
4028      * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4029      * called.
4030      *
4031      * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4032      * number of outstanding requests to 100 per app (identified by their UID), shared with
4033      * all variants of this method, of {@link #requestNetwork} as well as
4034      * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4035      * Requesting a network with this method will count toward this limit. If this limit is
4036      * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4037      * make sure to unregister the callbacks with
4038      * {@link #unregisterNetworkCallback(NetworkCallback)}.
4039      *
4040      * @param request {@link NetworkRequest} describing this request.
4041      * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4042      *                        networks change state.
4043      *                        The callback is invoked on the default internal Handler.
4044      * @throws RuntimeException if the app already has too many callbacks registered.
4045      */
4046     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
registerNetworkCallback(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback)4047     public void registerNetworkCallback(@NonNull NetworkRequest request,
4048             @NonNull NetworkCallback networkCallback) {
4049         registerNetworkCallback(request, networkCallback, getDefaultHandler());
4050     }
4051 
4052     /**
4053      * Registers to receive notifications about all networks which satisfy the given
4054      * {@link NetworkRequest}.  The callbacks will continue to be called until
4055      * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4056      * called.
4057      *
4058      * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4059      * number of outstanding requests to 100 per app (identified by their UID), shared with
4060      * all variants of this method, of {@link #requestNetwork} as well as
4061      * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4062      * Requesting a network with this method will count toward this limit. If this limit is
4063      * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4064      * make sure to unregister the callbacks with
4065      * {@link #unregisterNetworkCallback(NetworkCallback)}.
4066      *
4067      *
4068      * @param request {@link NetworkRequest} describing this request.
4069      * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4070      *                        networks change state.
4071      * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4072      * @throws RuntimeException if the app already has too many callbacks registered.
4073      */
4074     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
registerNetworkCallback(@onNull NetworkRequest request, @NonNull NetworkCallback networkCallback, @NonNull Handler handler)4075     public void registerNetworkCallback(@NonNull NetworkRequest request,
4076             @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4077         CallbackHandler cbHandler = new CallbackHandler(handler);
4078         NetworkCapabilities nc = request.networkCapabilities;
4079         sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4080     }
4081 
4082     /**
4083      * Registers a PendingIntent to be sent when a network is available which satisfies the given
4084      * {@link NetworkRequest}.
4085      *
4086      * This function behaves identically to the version that takes a NetworkCallback, but instead
4087      * of {@link NetworkCallback} a {@link PendingIntent} is used.  This means
4088      * the request may outlive the calling application and get called back when a suitable
4089      * network is found.
4090      * <p>
4091      * The operation is an Intent broadcast that goes to a broadcast receiver that
4092      * you registered with {@link Context#registerReceiver} or through the
4093      * &lt;receiver&gt; tag in an AndroidManifest.xml file
4094      * <p>
4095      * The operation Intent is delivered with two extras, a {@link Network} typed
4096      * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4097      * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4098      * the original requests parameters.
4099      * <p>
4100      * If there is already a request for this Intent registered (with the equality of
4101      * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4102      * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4103      * <p>
4104      * The request may be released normally by calling
4105      * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4106      *
4107      * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4108      * number of outstanding requests to 100 per app (identified by their UID), shared with
4109      * all variants of this method, of {@link #requestNetwork} as well as
4110      * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4111      * Requesting a network with this method will count toward this limit. If this limit is
4112      * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4113      * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4114      * or {@link #releaseNetworkRequest(PendingIntent)}.
4115      *
4116      * @param request {@link NetworkRequest} describing this request.
4117      * @param operation Action to perform when the network is available (corresponds
4118      *                  to the {@link NetworkCallback#onAvailable} call.  Typically
4119      *                  comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4120      * @throws RuntimeException if the app already has too many callbacks registered.
4121      */
4122     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
registerNetworkCallback(@onNull NetworkRequest request, @NonNull PendingIntent operation)4123     public void registerNetworkCallback(@NonNull NetworkRequest request,
4124             @NonNull PendingIntent operation) {
4125         printStackTrace();
4126         checkPendingIntentNotNull(operation);
4127         try {
4128             mService.pendingListenForNetwork(
4129                     request.networkCapabilities, operation, mContext.getOpPackageName());
4130         } catch (RemoteException e) {
4131             throw e.rethrowFromSystemServer();
4132         } catch (ServiceSpecificException e) {
4133             throw convertServiceException(e);
4134         }
4135     }
4136 
4137     /**
4138      * Registers to receive notifications about changes in the system default network. The callbacks
4139      * will continue to be called until either the application exits or
4140      * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4141      *
4142      * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4143      * number of outstanding requests to 100 per app (identified by their UID), shared with
4144      * all variants of this method, of {@link #requestNetwork} as well as
4145      * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4146      * Requesting a network with this method will count toward this limit. If this limit is
4147      * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4148      * make sure to unregister the callbacks with
4149      * {@link #unregisterNetworkCallback(NetworkCallback)}.
4150      *
4151      * @param networkCallback The {@link NetworkCallback} that the system will call as the
4152      *                        system default network changes.
4153      *                        The callback is invoked on the default internal Handler.
4154      * @throws RuntimeException if the app already has too many callbacks registered.
4155      */
4156     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
registerDefaultNetworkCallback(@onNull NetworkCallback networkCallback)4157     public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4158         registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4159     }
4160 
4161     /**
4162      * Registers to receive notifications about changes in the system default network. The callbacks
4163      * will continue to be called until either the application exits or
4164      * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4165      *
4166      * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4167      * number of outstanding requests to 100 per app (identified by their UID), shared with
4168      * all variants of this method, of {@link #requestNetwork} as well as
4169      * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4170      * Requesting a network with this method will count toward this limit. If this limit is
4171      * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4172      * make sure to unregister the callbacks with
4173      * {@link #unregisterNetworkCallback(NetworkCallback)}.
4174      *
4175      * @param networkCallback The {@link NetworkCallback} that the system will call as the
4176      *                        system default network changes.
4177      * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4178      * @throws RuntimeException if the app already has too many callbacks registered.
4179      */
4180     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
registerDefaultNetworkCallback(@onNull NetworkCallback networkCallback, @NonNull Handler handler)4181     public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4182             @NonNull Handler handler) {
4183         // This works because if the NetworkCapabilities are null,
4184         // ConnectivityService takes them from the default request.
4185         //
4186         // Since the capabilities are exactly the same as the default request's
4187         // capabilities, this request is guaranteed, at all times, to be
4188         // satisfied by the same network, if any, that satisfies the default
4189         // request, i.e., the system default network.
4190         CallbackHandler cbHandler = new CallbackHandler(handler);
4191         sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4192                 REQUEST, TYPE_NONE, cbHandler);
4193     }
4194 
4195     /**
4196      * Requests bandwidth update for a given {@link Network} and returns whether the update request
4197      * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4198      * network connection for updated bandwidth information. The caller will be notified via
4199      * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4200      * method assumes that the caller has previously called
4201      * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4202      * changes.
4203      *
4204      * @param network {@link Network} specifying which network you're interested.
4205      * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4206      */
requestBandwidthUpdate(@onNull Network network)4207     public boolean requestBandwidthUpdate(@NonNull Network network) {
4208         try {
4209             return mService.requestBandwidthUpdate(network);
4210         } catch (RemoteException e) {
4211             throw e.rethrowFromSystemServer();
4212         }
4213     }
4214 
4215     /**
4216      * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4217      * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4218      * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4219      * If the given {@code NetworkCallback} had previously been used with
4220      * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4221      * will be disconnected.
4222      *
4223      * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4224      * triggering it as soon as this call returns.
4225      *
4226      * @param networkCallback The {@link NetworkCallback} used when making the request.
4227      */
unregisterNetworkCallback(@onNull NetworkCallback networkCallback)4228     public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4229         printStackTrace();
4230         checkCallbackNotNull(networkCallback);
4231         final List<NetworkRequest> reqs = new ArrayList<>();
4232         // Find all requests associated to this callback and stop callback triggers immediately.
4233         // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4234         synchronized (sCallbacks) {
4235             Preconditions.checkArgument(networkCallback.networkRequest != null,
4236                     "NetworkCallback was not registered");
4237             if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4238                 Log.d(TAG, "NetworkCallback was already unregistered");
4239                 return;
4240             }
4241             for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4242                 if (e.getValue() == networkCallback) {
4243                     reqs.add(e.getKey());
4244                 }
4245             }
4246             // TODO: throw exception if callback was registered more than once (http://b/20701525).
4247             for (NetworkRequest r : reqs) {
4248                 try {
4249                     mService.releaseNetworkRequest(r);
4250                 } catch (RemoteException e) {
4251                     throw e.rethrowFromSystemServer();
4252                 }
4253                 // Only remove mapping if rpc was successful.
4254                 sCallbacks.remove(r);
4255             }
4256             networkCallback.networkRequest = ALREADY_UNREGISTERED;
4257         }
4258     }
4259 
4260     /**
4261      * Unregisters a callback previously registered via
4262      * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4263      *
4264      * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4265      *                  PendingIntent passed to
4266      *                  {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4267      *                  Cannot be null.
4268      */
unregisterNetworkCallback(@onNull PendingIntent operation)4269     public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4270         releaseNetworkRequest(operation);
4271     }
4272 
4273     /**
4274      * Informs the system whether it should switch to {@code network} regardless of whether it is
4275      * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4276      * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4277      * the system default network regardless of any other network that's currently connected. If
4278      * {@code always} is true, then the choice is remembered, so that the next time the user
4279      * connects to this network, the system will switch to it.
4280      *
4281      * @param network The network to accept.
4282      * @param accept Whether to accept the network even if unvalidated.
4283      * @param always Whether to remember this choice in the future.
4284      *
4285      * @hide
4286      */
4287     @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
setAcceptUnvalidated(Network network, boolean accept, boolean always)4288     public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4289         try {
4290             mService.setAcceptUnvalidated(network, accept, always);
4291         } catch (RemoteException e) {
4292             throw e.rethrowFromSystemServer();
4293         }
4294     }
4295 
4296     /**
4297      * Informs the system whether it should consider the network as validated even if it only has
4298      * partial connectivity. If {@code accept} is true, then the network will be considered as
4299      * validated even if connectivity is only partial. If {@code always} is true, then the choice
4300      * is remembered, so that the next time the user connects to this network, the system will
4301      * switch to it.
4302      *
4303      * @param network The network to accept.
4304      * @param accept Whether to consider the network as validated even if it has partial
4305      *               connectivity.
4306      * @param always Whether to remember this choice in the future.
4307      *
4308      * @hide
4309      */
4310     @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
setAcceptPartialConnectivity(Network network, boolean accept, boolean always)4311     public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4312         try {
4313             mService.setAcceptPartialConnectivity(network, accept, always);
4314         } catch (RemoteException e) {
4315             throw e.rethrowFromSystemServer();
4316         }
4317     }
4318 
4319     /**
4320      * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4321      * only meaningful if the system is configured not to penalize such networks, e.g., if the
4322      * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4323      * NETWORK_AVOID_BAD_WIFI setting is unset}.
4324      *
4325      * @param network The network to accept.
4326      *
4327      * @hide
4328      */
4329     @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
setAvoidUnvalidated(Network network)4330     public void setAvoidUnvalidated(Network network) {
4331         try {
4332             mService.setAvoidUnvalidated(network);
4333         } catch (RemoteException e) {
4334             throw e.rethrowFromSystemServer();
4335         }
4336     }
4337 
4338     /**
4339      * Requests that the system open the captive portal app on the specified network.
4340      *
4341      * @param network The network to log into.
4342      *
4343      * @hide
4344      */
4345     @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
startCaptivePortalApp(Network network)4346     public void startCaptivePortalApp(Network network) {
4347         try {
4348             mService.startCaptivePortalApp(network);
4349         } catch (RemoteException e) {
4350             throw e.rethrowFromSystemServer();
4351         }
4352     }
4353 
4354     /**
4355      * Requests that the system open the captive portal app with the specified extras.
4356      *
4357      * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4358      * corresponding permission.
4359      * @param network Network on which the captive portal was detected.
4360      * @param appExtras Extras to include in the app start intent.
4361      * @hide
4362      */
4363     @SystemApi
4364     @TestApi
4365     @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
startCaptivePortalApp(@onNull Network network, @NonNull Bundle appExtras)4366     public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4367         try {
4368             mService.startCaptivePortalAppInternal(network, appExtras);
4369         } catch (RemoteException e) {
4370             throw e.rethrowFromSystemServer();
4371         }
4372     }
4373 
4374     /**
4375      * Determine whether the device is configured to avoid bad wifi.
4376      * @hide
4377      */
4378     @SystemApi
4379     @RequiresPermission(anyOf = {
4380             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4381             android.Manifest.permission.NETWORK_STACK})
shouldAvoidBadWifi()4382     public boolean shouldAvoidBadWifi() {
4383         try {
4384             return mService.shouldAvoidBadWifi();
4385         } catch (RemoteException e) {
4386             throw e.rethrowFromSystemServer();
4387         }
4388     }
4389 
4390     /**
4391      * It is acceptable to briefly use multipath data to provide seamless connectivity for
4392      * time-sensitive user-facing operations when the system default network is temporarily
4393      * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4394      * this method), and the operation should be infrequent to ensure that data usage is limited.
4395      *
4396      * An example of such an operation might be a time-sensitive foreground activity, such as a
4397      * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4398      */
4399     public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4400 
4401     /**
4402      * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4403      * a backup channel for traffic that is primarily going over another network.
4404      *
4405      * An example might be maintaining backup connections to peers or servers for the purpose of
4406      * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4407      * on backup paths should be negligible compared to the traffic on the main path.
4408      */
4409     public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4410 
4411     /**
4412      * It is acceptable to use metered data to improve network latency and performance.
4413      */
4414     public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4415 
4416     /**
4417      * Return value to use for unmetered networks. On such networks we currently set all the flags
4418      * to true.
4419      * @hide
4420      */
4421     public static final int MULTIPATH_PREFERENCE_UNMETERED =
4422             MULTIPATH_PREFERENCE_HANDOVER |
4423             MULTIPATH_PREFERENCE_RELIABILITY |
4424             MULTIPATH_PREFERENCE_PERFORMANCE;
4425 
4426     /** @hide */
4427     @Retention(RetentionPolicy.SOURCE)
4428     @IntDef(flag = true, value = {
4429             MULTIPATH_PREFERENCE_HANDOVER,
4430             MULTIPATH_PREFERENCE_RELIABILITY,
4431             MULTIPATH_PREFERENCE_PERFORMANCE,
4432     })
4433     public @interface MultipathPreference {
4434     }
4435 
4436     /**
4437      * Provides a hint to the calling application on whether it is desirable to use the
4438      * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4439      * for multipath data transfer on this network when it is not the system default network.
4440      * Applications desiring to use multipath network protocols should call this method before
4441      * each such operation.
4442      *
4443      * @param network The network on which the application desires to use multipath data.
4444      *                If {@code null}, this method will return the a preference that will generally
4445      *                apply to metered networks.
4446      * @return a bitwise OR of zero or more of the  {@code MULTIPATH_PREFERENCE_*} constants.
4447      */
4448     @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
getMultipathPreference(@ullable Network network)4449     public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
4450         try {
4451             return mService.getMultipathPreference(network);
4452         } catch (RemoteException e) {
4453             throw e.rethrowFromSystemServer();
4454         }
4455     }
4456 
4457     /**
4458      * Resets all connectivity manager settings back to factory defaults.
4459      * @hide
4460      */
4461     @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
factoryReset()4462     public void factoryReset() {
4463         try {
4464             mService.factoryReset();
4465             mTetheringManager.stopAllTethering();
4466         } catch (RemoteException e) {
4467             throw e.rethrowFromSystemServer();
4468         }
4469     }
4470 
4471     /**
4472      * Binds the current process to {@code network}.  All Sockets created in the future
4473      * (and not explicitly bound via a bound SocketFactory from
4474      * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4475      * {@code network}.  All host name resolutions will be limited to {@code network} as well.
4476      * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4477      * work and all host name resolutions will fail.  This is by design so an application doesn't
4478      * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4479      * To clear binding pass {@code null} for {@code network}.  Using individually bound
4480      * Sockets created by Network.getSocketFactory().createSocket() and
4481      * performing network-specific host name resolutions via
4482      * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4483      * {@code bindProcessToNetwork}.
4484      *
4485      * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4486      *                the current binding.
4487      * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4488      */
bindProcessToNetwork(@ullable Network network)4489     public boolean bindProcessToNetwork(@Nullable Network network) {
4490         // Forcing callers to call through non-static function ensures ConnectivityManager
4491         // instantiated.
4492         return setProcessDefaultNetwork(network);
4493     }
4494 
4495     /**
4496      * Binds the current process to {@code network}.  All Sockets created in the future
4497      * (and not explicitly bound via a bound SocketFactory from
4498      * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4499      * {@code network}.  All host name resolutions will be limited to {@code network} as well.
4500      * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4501      * work and all host name resolutions will fail.  This is by design so an application doesn't
4502      * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4503      * To clear binding pass {@code null} for {@code network}.  Using individually bound
4504      * Sockets created by Network.getSocketFactory().createSocket() and
4505      * performing network-specific host name resolutions via
4506      * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4507      * {@code setProcessDefaultNetwork}.
4508      *
4509      * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4510      *                the current binding.
4511      * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4512      * @deprecated This function can throw {@link IllegalStateException}.  Use
4513      *             {@link #bindProcessToNetwork} instead.  {@code bindProcessToNetwork}
4514      *             is a direct replacement.
4515      */
4516     @Deprecated
setProcessDefaultNetwork(@ullable Network network)4517     public static boolean setProcessDefaultNetwork(@Nullable Network network) {
4518         int netId = (network == null) ? NETID_UNSET : network.netId;
4519         boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4520 
4521         if (netId != NETID_UNSET) {
4522             netId = network.getNetIdForResolv();
4523         }
4524 
4525         if (!NetworkUtils.bindProcessToNetwork(netId)) {
4526             return false;
4527         }
4528 
4529         if (!isSameNetId) {
4530             // Set HTTP proxy system properties to match network.
4531             // TODO: Deprecate this static method and replace it with a non-static version.
4532             try {
4533                 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4534             } catch (SecurityException e) {
4535                 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4536                 Log.e(TAG, "Can't set proxy properties", e);
4537             }
4538             // Must flush DNS cache as new network may have different DNS resolutions.
4539             InetAddress.clearDnsCache();
4540             // Must flush socket pool as idle sockets will be bound to previous network and may
4541             // cause subsequent fetches to be performed on old network.
4542             NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
4543         }
4544 
4545         return true;
4546     }
4547 
4548     /**
4549      * Returns the {@link Network} currently bound to this process via
4550      * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4551      *
4552      * @return {@code Network} to which this process is bound, or {@code null}.
4553      */
4554     @Nullable
getBoundNetworkForProcess()4555     public Network getBoundNetworkForProcess() {
4556         // Forcing callers to call thru non-static function ensures ConnectivityManager
4557         // instantiated.
4558         return getProcessDefaultNetwork();
4559     }
4560 
4561     /**
4562      * Returns the {@link Network} currently bound to this process via
4563      * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4564      *
4565      * @return {@code Network} to which this process is bound, or {@code null}.
4566      * @deprecated Using this function can lead to other functions throwing
4567      *             {@link IllegalStateException}.  Use {@link #getBoundNetworkForProcess} instead.
4568      *             {@code getBoundNetworkForProcess} is a direct replacement.
4569      */
4570     @Deprecated
4571     @Nullable
getProcessDefaultNetwork()4572     public static Network getProcessDefaultNetwork() {
4573         int netId = NetworkUtils.getBoundNetworkForProcess();
4574         if (netId == NETID_UNSET) return null;
4575         return new Network(netId);
4576     }
4577 
unsupportedStartingFrom(int version)4578     private void unsupportedStartingFrom(int version) {
4579         if (Process.myUid() == Process.SYSTEM_UID) {
4580             // The getApplicationInfo() call we make below is not supported in system context. Let
4581             // the call through here, and rely on the fact that ConnectivityService will refuse to
4582             // allow the system to use these APIs anyway.
4583             return;
4584         }
4585 
4586         if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4587             throw new UnsupportedOperationException(
4588                     "This method is not supported in target SDK version " + version + " and above");
4589         }
4590     }
4591 
4592     // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4593     // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
4594     // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
4595     // remove these exemptions. Note that this check is not secure, and apps can still access these
4596     // functions by accessing ConnectivityService directly. However, it should be clear that doing
4597     // so is unsupported and may break in the future. http://b/22728205
checkLegacyRoutingApiAccess()4598     private void checkLegacyRoutingApiAccess() {
4599         unsupportedStartingFrom(VERSION_CODES.M);
4600     }
4601 
4602     /**
4603      * Binds host resolutions performed by this process to {@code network}.
4604      * {@link #bindProcessToNetwork} takes precedence over this setting.
4605      *
4606      * @param network The {@link Network} to bind host resolutions from the current process to, or
4607      *                {@code null} to clear the current binding.
4608      * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4609      * @hide
4610      * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4611      */
4612     @Deprecated
4613     @UnsupportedAppUsage
setProcessDefaultNetworkForHostResolution(Network network)4614     public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
4615         return NetworkUtils.bindProcessToNetworkForHostResolution(
4616                 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
4617     }
4618 
4619     /**
4620      * Device is not restricting metered network activity while application is running on
4621      * background.
4622      */
4623     public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4624 
4625     /**
4626      * Device is restricting metered network activity while application is running on background,
4627      * but application is allowed to bypass it.
4628      * <p>
4629      * In this state, application should take action to mitigate metered network access.
4630      * For example, a music streaming application should switch to a low-bandwidth bitrate.
4631      */
4632     public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4633 
4634     /**
4635      * Device is restricting metered network activity while application is running on background.
4636      * <p>
4637      * In this state, application should not try to use the network while running on background,
4638      * because it would be denied.
4639      */
4640     public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4641 
4642     /**
4643      * A change in the background metered network activity restriction has occurred.
4644      * <p>
4645      * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4646      * applies to them.
4647      * <p>
4648      * This is only sent to registered receivers, not manifest receivers.
4649      */
4650     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4651     public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4652             "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4653 
4654     /** @hide */
4655     @Retention(RetentionPolicy.SOURCE)
4656     @IntDef(flag = false, value = {
4657             RESTRICT_BACKGROUND_STATUS_DISABLED,
4658             RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4659             RESTRICT_BACKGROUND_STATUS_ENABLED,
4660     })
4661     public @interface RestrictBackgroundStatus {
4662     }
4663 
getNetworkPolicyManager()4664     private INetworkPolicyManager getNetworkPolicyManager() {
4665         synchronized (this) {
4666             if (mNPManager != null) {
4667                 return mNPManager;
4668             }
4669             mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4670                     .getService(Context.NETWORK_POLICY_SERVICE));
4671             return mNPManager;
4672         }
4673     }
4674 
4675     /**
4676      * Determines if the calling application is subject to metered network restrictions while
4677      * running on background.
4678      *
4679      * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4680      * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4681      * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
4682      */
getRestrictBackgroundStatus()4683     public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4684         try {
4685             return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4686         } catch (RemoteException e) {
4687             throw e.rethrowFromSystemServer();
4688         }
4689     }
4690 
4691     /**
4692      * The network watchlist is a list of domains and IP addresses that are associated with
4693      * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4694      * currently used by the system for validation purposes.
4695      *
4696      * @return Hash of network watchlist config file. Null if config does not exist.
4697      */
4698     @Nullable
getNetworkWatchlistConfigHash()4699     public byte[] getNetworkWatchlistConfigHash() {
4700         try {
4701             return mService.getNetworkWatchlistConfigHash();
4702         } catch (RemoteException e) {
4703             Log.e(TAG, "Unable to get watchlist config hash");
4704             throw e.rethrowFromSystemServer();
4705         }
4706     }
4707 
4708     /**
4709      * Returns the {@code uid} of the owner of a network connection.
4710      *
4711      * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4712      *     IPPROTO_UDP} currently supported.
4713      * @param local The local {@link InetSocketAddress} of a connection.
4714      * @param remote The remote {@link InetSocketAddress} of a connection.
4715      * @return {@code uid} if the connection is found and the app has permission to observe it
4716      *     (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4717      *     android.os.Process#INVALID_UID} if the connection is not found.
4718      * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4719      *     user.
4720      * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
4721      */
getConnectionOwnerUid( int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote)4722     public int getConnectionOwnerUid(
4723             int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
4724         ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4725         try {
4726             return mService.getConnectionOwnerUid(connectionInfo);
4727         } catch (RemoteException e) {
4728             throw e.rethrowFromSystemServer();
4729         }
4730     }
4731 
printStackTrace()4732     private void printStackTrace() {
4733         if (DEBUG) {
4734             final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4735             final StringBuffer sb = new StringBuffer();
4736             for (int i = 3; i < callStack.length; i++) {
4737                 final String stackTrace = callStack[i].toString();
4738                 if (stackTrace == null || stackTrace.contains("android.os")) {
4739                     break;
4740                 }
4741                 sb.append(" [").append(stackTrace).append("]");
4742             }
4743             Log.d(TAG, "StackLog:" + sb.toString());
4744         }
4745     }
4746 
4747     /**
4748      * Simulates a Data Stall for the specified Network.
4749      *
4750      * <p>The caller must be the owner of the specified Network.
4751      *
4752      * @param detectionMethod The detection method used to identify the Data Stall.
4753      * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4754      * @param network The Network for which a Data Stall is being simluated.
4755      * @param extras The PersistableBundle of extras included in the Data Stall notification.
4756      * @throws SecurityException if the caller is not the owner of the given network.
4757      * @hide
4758      */
4759     @TestApi
4760     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4761             android.Manifest.permission.NETWORK_STACK})
simulateDataStall(int detectionMethod, long timestampMillis, @NonNull Network network, @NonNull PersistableBundle extras)4762     public void simulateDataStall(int detectionMethod, long timestampMillis,
4763             @NonNull Network network, @NonNull PersistableBundle extras) {
4764         try {
4765             mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4766         } catch (RemoteException e) {
4767             e.rethrowFromSystemServer();
4768         }
4769     }
4770 }
4771