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