blob: 987dcc4898b59a3f14b9e5b8b824b9709d46e593 [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
3234 /** {@hide} - returns the factory serial number */
3235 @UnsupportedAppUsage
3236 @RequiresPermission(anyOf = {
3237 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3238 android.Manifest.permission.NETWORK_FACTORY})
3239 public int registerNetworkFactory(Messenger messenger, String name) {
3240 try {
3241 return mService.registerNetworkFactory(messenger, name);
3242 } catch (RemoteException e) {
3243 throw e.rethrowFromSystemServer();
3244 }
3245 }
3246
3247 /** {@hide} */
3248 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
3249 @RequiresPermission(anyOf = {
3250 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3251 android.Manifest.permission.NETWORK_FACTORY})
3252 public void unregisterNetworkFactory(Messenger messenger) {
3253 try {
3254 mService.unregisterNetworkFactory(messenger);
3255 } catch (RemoteException e) {
3256 throw e.rethrowFromSystemServer();
3257 }
3258 }
3259
3260 /**
3261 * Registers the specified {@link NetworkProvider}.
3262 * Each listener must only be registered once. The listener can be unregistered with
3263 * {@link #unregisterNetworkProvider}.
3264 *
3265 * @param provider the provider to register
3266 * @return the ID of the provider. This ID must be used by the provider when registering
3267 * {@link android.net.NetworkAgent}s.
3268 * @hide
3269 */
3270 @SystemApi
3271 @RequiresPermission(anyOf = {
3272 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3273 android.Manifest.permission.NETWORK_FACTORY})
3274 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3275 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3276 throw new IllegalStateException("NetworkProviders can only be registered once");
3277 }
3278
3279 try {
3280 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3281 provider.getName());
3282 provider.setProviderId(providerId);
3283 } catch (RemoteException e) {
3284 throw e.rethrowFromSystemServer();
3285 }
3286 return provider.getProviderId();
3287 }
3288
3289 /**
3290 * Unregisters the specified NetworkProvider.
3291 *
3292 * @param provider the provider to unregister
3293 * @hide
3294 */
3295 @SystemApi
3296 @RequiresPermission(anyOf = {
3297 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3298 android.Manifest.permission.NETWORK_FACTORY})
3299 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3300 try {
3301 mService.unregisterNetworkProvider(provider.getMessenger());
3302 } catch (RemoteException e) {
3303 throw e.rethrowFromSystemServer();
3304 }
3305 provider.setProviderId(NetworkProvider.ID_NONE);
3306 }
3307
3308
3309 /** @hide exposed via the NetworkProvider class. */
3310 @RequiresPermission(anyOf = {
3311 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3312 android.Manifest.permission.NETWORK_FACTORY})
3313 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3314 try {
3315 mService.declareNetworkRequestUnfulfillable(request);
3316 } catch (RemoteException e) {
3317 throw e.rethrowFromSystemServer();
3318 }
3319 }
3320
3321 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3322 // of dependent changes that would conflict throughout the automerger graph. Having this
3323 // temporarily helps with the process of going through with all these dependent changes across
3324 // the entire tree.
3325 /**
3326 * @hide
3327 * Register a NetworkAgent with ConnectivityService.
3328 * @return Network corresponding to NetworkAgent.
3329 */
3330 @RequiresPermission(anyOf = {
3331 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3332 android.Manifest.permission.NETWORK_FACTORY})
3333 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
3334 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
3335 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
3336 }
3337
3338 /**
3339 * @hide
3340 * Register a NetworkAgent with ConnectivityService.
3341 * @return Network corresponding to NetworkAgent.
3342 */
3343 @RequiresPermission(anyOf = {
3344 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3345 android.Manifest.permission.NETWORK_FACTORY})
3346 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
3347 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
3348 try {
3349 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3350 } catch (RemoteException e) {
3351 throw e.rethrowFromSystemServer();
3352 }
3353 }
3354
3355 /**
3356 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3357 * changes. Should be extended by applications wanting notifications.
3358 *
3359 * A {@code NetworkCallback} is registered by calling
3360 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3361 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3362 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3363 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3364 * A {@code NetworkCallback} should be registered at most once at any time.
3365 * A {@code NetworkCallback} that has been unregistered can be registered again.
3366 */
3367 public static class NetworkCallback {
3368 /**
3369 * Called when the framework connects to a new network to evaluate whether it satisfies this
3370 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3371 * callback. There is no guarantee that this new network will satisfy any requests, or that
3372 * the network will stay connected for longer than the time necessary to evaluate it.
3373 * <p>
3374 * Most applications <b>should not</b> act on this callback, and should instead use
3375 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3376 * the framework in properly evaluating the network &mdash; for example, an application that
3377 * can automatically log in to a captive portal without user intervention.
3378 *
3379 * @param network The {@link Network} of the network that is being evaluated.
3380 *
3381 * @hide
3382 */
3383 public void onPreCheck(@NonNull Network network) {}
3384
3385 /**
3386 * Called when the framework connects and has declared a new network ready for use.
3387 * This callback may be called more than once if the {@link Network} that is
3388 * satisfying the request changes.
3389 *
3390 * @param network The {@link Network} of the satisfying network.
3391 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3392 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3393 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3394 * @hide
3395 */
3396 public void onAvailable(@NonNull Network network,
3397 @NonNull NetworkCapabilities networkCapabilities,
3398 @NonNull LinkProperties linkProperties, boolean blocked) {
3399 // Internally only this method is called when a new network is available, and
3400 // it calls the callback in the same way and order that older versions used
3401 // to call so as not to change the behavior.
3402 onAvailable(network);
3403 if (!networkCapabilities.hasCapability(
3404 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3405 onNetworkSuspended(network);
3406 }
3407 onCapabilitiesChanged(network, networkCapabilities);
3408 onLinkPropertiesChanged(network, linkProperties);
3409 onBlockedStatusChanged(network, blocked);
3410 }
3411
3412 /**
3413 * Called when the framework connects and has declared a new network ready for use.
3414 *
3415 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3416 * be available at the same time, and onAvailable will be called for each of these as they
3417 * appear.
3418 *
3419 * <p>For callbacks registered with {@link #requestNetwork} and
3420 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3421 * is the new best network for this request and is now tracked by this callback ; this
3422 * callback will no longer receive method calls about other networks that may have been
3423 * passed to this method previously. The previously-best network may have disconnected, or
3424 * it may still be around and the newly-best network may simply be better.
3425 *
3426 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3427 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3428 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3429 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3430 *
3431 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3432 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3433 * this callback as this is prone to race conditions (there is no guarantee the objects
3434 * returned by these methods will be current). Instead, wait for a call to
3435 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3436 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3437 * to be well-ordered with respect to other callbacks.
3438 *
3439 * @param network The {@link Network} of the satisfying network.
3440 */
3441 public void onAvailable(@NonNull Network network) {}
3442
3443 /**
3444 * Called when the network is about to be lost, typically because there are no outstanding
3445 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3446 * with the new replacement network for graceful handover. This method is not guaranteed
3447 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3448 * network is suddenly disconnected.
3449 *
3450 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3451 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3452 * this callback as this is prone to race conditions ; calling these methods while in a
3453 * callback may return an outdated or even a null object.
3454 *
3455 * @param network The {@link Network} that is about to be lost.
3456 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3457 * connected for graceful handover; note that the network may still
3458 * suffer a hard loss at any time.
3459 */
3460 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3461
3462 /**
3463 * Called when a network disconnects or otherwise no longer satisfies this request or
3464 * callback.
3465 *
3466 * <p>If the callback was registered with requestNetwork() or
3467 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3468 * returned by onAvailable() when that network is lost and no other network satisfies
3469 * the criteria of the request.
3470 *
3471 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3472 * each network which no longer satisfies the criteria of the callback.
3473 *
3474 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3475 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3476 * this callback as this is prone to race conditions ; calling these methods while in a
3477 * callback may return an outdated or even a null object.
3478 *
3479 * @param network The {@link Network} lost.
3480 */
3481 public void onLost(@NonNull Network network) {}
3482
3483 /**
3484 * Called if no network is found within the timeout time specified in
3485 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3486 * requested network request cannot be fulfilled (whether or not a timeout was
3487 * specified). When this callback is invoked the associated
3488 * {@link NetworkRequest} will have already been removed and released, as if
3489 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3490 */
3491 public void onUnavailable() {}
3492
3493 /**
3494 * Called when the network corresponding to this request changes capabilities but still
3495 * satisfies the requested criteria.
3496 *
3497 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3498 * to be called immediately after {@link #onAvailable}.
3499 *
3500 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3501 * ConnectivityManager methods in this callback as this is prone to race conditions :
3502 * calling these methods while in a callback may return an outdated or even a null object.
3503 *
3504 * @param network The {@link Network} whose capabilities have changed.
3505 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3506 * network.
3507 */
3508 public void onCapabilitiesChanged(@NonNull Network network,
3509 @NonNull NetworkCapabilities networkCapabilities) {}
3510
3511 /**
3512 * Called when the network corresponding to this request changes {@link LinkProperties}.
3513 *
3514 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3515 * to be called immediately after {@link #onAvailable}.
3516 *
3517 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3518 * ConnectivityManager methods in this callback as this is prone to race conditions :
3519 * calling these methods while in a callback may return an outdated or even a null object.
3520 *
3521 * @param network The {@link Network} whose link properties have changed.
3522 * @param linkProperties The new {@link LinkProperties} for this network.
3523 */
3524 public void onLinkPropertiesChanged(@NonNull Network network,
3525 @NonNull LinkProperties linkProperties) {}
3526
3527 /**
3528 * Called when the network the framework connected to for this request suspends data
3529 * transmission temporarily.
3530 *
3531 * <p>This generally means that while the TCP connections are still live temporarily
3532 * network data fails to transfer. To give a specific example, this is used on cellular
3533 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3534 * means read operations on sockets on this network will block once the buffers are
3535 * drained, and write operations will block once the buffers are full.
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 (there is no guarantee the objects
3540 * returned by these methods will be current).
3541 *
3542 * @hide
3543 */
3544 public void onNetworkSuspended(@NonNull Network network) {}
3545
3546 /**
3547 * Called when the network the framework connected to for this request
3548 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3549 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3550
3551 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3552 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3553 * this callback as this is prone to race conditions : calling these methods while in a
3554 * callback may return an outdated or even a null object.
3555 *
3556 * @hide
3557 */
3558 public void onNetworkResumed(@NonNull Network network) {}
3559
3560 /**
3561 * Called when access to the specified network is blocked or unblocked.
3562 *
3563 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3564 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3565 * this callback as this is prone to race conditions : calling these methods while in a
3566 * callback may return an outdated or even a null object.
3567 *
3568 * @param network The {@link Network} whose blocked status has changed.
3569 * @param blocked The blocked status of this {@link Network}.
3570 */
3571 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3572
3573 private NetworkRequest networkRequest;
3574 }
3575
3576 /**
3577 * Constant error codes used by ConnectivityService to communicate about failures and errors
3578 * across a Binder boundary.
3579 * @hide
3580 */
3581 public interface Errors {
3582 int TOO_MANY_REQUESTS = 1;
3583 }
3584
3585 /** @hide */
3586 public static class TooManyRequestsException extends RuntimeException {}
3587
3588 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3589 switch (e.errorCode) {
3590 case Errors.TOO_MANY_REQUESTS:
3591 return new TooManyRequestsException();
3592 default:
3593 Log.w(TAG, "Unknown service error code " + e.errorCode);
3594 return new RuntimeException(e);
3595 }
3596 }
3597
3598 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
3599 /** @hide */
3600 public static final int CALLBACK_PRECHECK = BASE + 1;
3601 /** @hide */
3602 public static final int CALLBACK_AVAILABLE = BASE + 2;
3603 /** @hide arg1 = TTL */
3604 public static final int CALLBACK_LOSING = BASE + 3;
3605 /** @hide */
3606 public static final int CALLBACK_LOST = BASE + 4;
3607 /** @hide */
3608 public static final int CALLBACK_UNAVAIL = BASE + 5;
3609 /** @hide */
3610 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3611 /** @hide */
3612 public static final int CALLBACK_IP_CHANGED = BASE + 7;
3613 /** @hide obj = NetworkCapabilities, arg1 = seq number */
3614 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
3615 /** @hide */
3616 public static final int CALLBACK_SUSPENDED = BASE + 9;
3617 /** @hide */
3618 public static final int CALLBACK_RESUMED = BASE + 10;
3619 /** @hide */
3620 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
3621
3622 /** @hide */
3623 public static String getCallbackName(int whichCallback) {
3624 switch (whichCallback) {
3625 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3626 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3627 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3628 case CALLBACK_LOST: return "CALLBACK_LOST";
3629 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3630 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3631 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
3632 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3633 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3634 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
3635 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
3636 default:
3637 return Integer.toString(whichCallback);
3638 }
3639 }
3640
3641 private class CallbackHandler extends Handler {
3642 private static final String TAG = "ConnectivityManager.CallbackHandler";
3643 private static final boolean DBG = false;
3644
3645 CallbackHandler(Looper looper) {
3646 super(looper);
3647 }
3648
3649 CallbackHandler(Handler handler) {
3650 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
3651 }
3652
3653 @Override
3654 public void handleMessage(Message message) {
3655 if (message.what == EXPIRE_LEGACY_REQUEST) {
3656 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3657 return;
3658 }
3659
3660 final NetworkRequest request = getObject(message, NetworkRequest.class);
3661 final Network network = getObject(message, Network.class);
3662 final NetworkCallback callback;
3663 synchronized (sCallbacks) {
3664 callback = sCallbacks.get(request);
3665 if (callback == null) {
3666 Log.w(TAG,
3667 "callback not found for " + getCallbackName(message.what) + " message");
3668 return;
3669 }
3670 if (message.what == CALLBACK_UNAVAIL) {
3671 sCallbacks.remove(request);
3672 callback.networkRequest = ALREADY_UNREGISTERED;
3673 }
3674 }
3675 if (DBG) {
3676 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
3677 }
3678
3679 switch (message.what) {
3680 case CALLBACK_PRECHECK: {
3681 callback.onPreCheck(network);
3682 break;
3683 }
3684 case CALLBACK_AVAILABLE: {
3685 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3686 LinkProperties lp = getObject(message, LinkProperties.class);
3687 callback.onAvailable(network, cap, lp, message.arg1 != 0);
3688 break;
3689 }
3690 case CALLBACK_LOSING: {
3691 callback.onLosing(network, message.arg1);
3692 break;
3693 }
3694 case CALLBACK_LOST: {
3695 callback.onLost(network);
3696 break;
3697 }
3698 case CALLBACK_UNAVAIL: {
3699 callback.onUnavailable();
3700 break;
3701 }
3702 case CALLBACK_CAP_CHANGED: {
3703 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3704 callback.onCapabilitiesChanged(network, cap);
3705 break;
3706 }
3707 case CALLBACK_IP_CHANGED: {
3708 LinkProperties lp = getObject(message, LinkProperties.class);
3709 callback.onLinkPropertiesChanged(network, lp);
3710 break;
3711 }
3712 case CALLBACK_SUSPENDED: {
3713 callback.onNetworkSuspended(network);
3714 break;
3715 }
3716 case CALLBACK_RESUMED: {
3717 callback.onNetworkResumed(network);
3718 break;
3719 }
3720 case CALLBACK_BLK_CHANGED: {
3721 boolean blocked = message.arg1 != 0;
3722 callback.onBlockedStatusChanged(network, blocked);
3723 }
3724 }
3725 }
3726
3727 private <T> T getObject(Message msg, Class<T> c) {
3728 return (T) msg.getData().getParcelable(c.getSimpleName());
3729 }
3730 }
3731
3732 private CallbackHandler getDefaultHandler() {
3733 synchronized (sCallbacks) {
3734 if (sCallbackHandler == null) {
3735 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
3736 }
3737 return sCallbackHandler;
3738 }
3739 }
3740
3741 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3742 private static CallbackHandler sCallbackHandler;
3743
3744 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3745 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3746 printStackTrace();
3747 checkCallbackNotNull(callback);
3748 Preconditions.checkArgument(
3749 reqType == TRACK_DEFAULT || need != null, "null NetworkCapabilities");
3750 final NetworkRequest request;
3751 final String callingPackageName = mContext.getOpPackageName();
3752 try {
3753 synchronized(sCallbacks) {
3754 if (callback.networkRequest != null
3755 && callback.networkRequest != ALREADY_UNREGISTERED) {
3756 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3757 // and requests (http://b/20701525).
3758 Log.e(TAG, "NetworkCallback was already registered");
3759 }
3760 Messenger messenger = new Messenger(handler);
3761 Binder binder = new Binder();
3762 if (reqType == LISTEN) {
3763 request = mService.listenForNetwork(
3764 need, messenger, binder, callingPackageName);
3765 } else {
3766 request = mService.requestNetwork(
3767 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3768 callingPackageName, getAttributionTag());
3769 }
3770 if (request != null) {
3771 sCallbacks.put(request, callback);
3772 }
3773 callback.networkRequest = request;
3774 }
3775 } catch (RemoteException e) {
3776 throw e.rethrowFromSystemServer();
3777 } catch (ServiceSpecificException e) {
3778 throw convertServiceException(e);
3779 }
3780 return request;
3781 }
3782
3783 /**
3784 * Helper function to request a network with a particular legacy type.
3785 *
3786 * This API is only for use in internal system code that requests networks with legacy type and
3787 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
3788 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
3789 *
3790 * @param request {@link NetworkRequest} describing this request.
3791 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3792 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3793 * be a positive value (i.e. >0).
3794 * @param legacyType to specify the network type(#TYPE_*).
3795 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3796 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3797 * the callback must not be shared - it uniquely specifies this request.
3798 *
3799 * @hide
3800 */
3801 @SystemApi
3802 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
3803 public void requestNetwork(@NonNull NetworkRequest request,
3804 int timeoutMs, int legacyType, @NonNull Handler handler,
3805 @NonNull NetworkCallback networkCallback) {
3806 if (legacyType == TYPE_NONE) {
3807 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3808 }
3809 CallbackHandler cbHandler = new CallbackHandler(handler);
3810 NetworkCapabilities nc = request.networkCapabilities;
3811 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
3812 }
3813
3814 /**
3815 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3816 *
3817 * <p>This method will attempt to find the best network that matches the passed
3818 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3819 * criteria. The platform will evaluate which network is the best at its own discretion.
3820 * Throughput, latency, cost per byte, policy, user preference and other considerations
3821 * may be factored in the decision of what is considered the best network.
3822 *
3823 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3824 * matching this request, while always attempting to match the request to a better network if
3825 * possible. If a better match is found, the platform will switch this request to the now-best
3826 * network and inform the app of the newly best network by invoking
3827 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3828 * will not try to maintain any other network than the best one currently matching the request:
3829 * a network not matching any network request may be disconnected at any time.
3830 *
3831 * <p>For example, an application could use this method to obtain a connected cellular network
3832 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3833 * radio to consume additional power. Or, an application could inform the system that it wants
3834 * a network supporting sending MMSes and have the system let it know about the currently best
3835 * MMS-supporting network through the provided {@link NetworkCallback}.
3836 *
3837 * <p>The status of the request can be followed by listening to the various callbacks described
3838 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3839 * used to direct traffic to the network (although accessing some networks may be subject to
3840 * holding specific permissions). Callers will learn about the specific characteristics of the
3841 * network through
3842 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3843 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3844 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3845 * matching the request at any given time; therefore when a better network matching the request
3846 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3847 * with the new network after which no further updates are given about the previously-best
3848 * network, unless it becomes the best again at some later time. All callbacks are invoked
3849 * in order on the same thread, which by default is a thread created by the framework running
3850 * in the app.
3851 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3852 * callbacks are invoked.
3853 *
3854 * <p>This{@link NetworkRequest} will live until released via
3855 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3856 * which point the system may let go of the network at any time.
3857 *
3858 * <p>A version of this method which takes a timeout is
3859 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3860 * wait for a limited amount of time for the network to become unavailable.
3861 *
3862 * <p>It is presently unsupported to request a network with mutable
3863 * {@link NetworkCapabilities} such as
3864 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3865 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3866 * as these {@code NetworkCapabilities} represent states that a particular
3867 * network may never attain, and whether a network will attain these states
3868 * is unknown prior to bringing up the network so the framework does not
3869 * know how to go about satisfying a request with these capabilities.
3870 *
3871 * <p>This method requires the caller to hold either the
3872 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3873 * or the ability to modify system settings as determined by
3874 * {@link android.provider.Settings.System#canWrite}.</p>
3875 *
3876 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3877 * number of outstanding requests to 100 per app (identified by their UID), shared with
3878 * all variants of this method, of {@link #registerNetworkCallback} as well as
3879 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3880 * Requesting a network with this method will count toward this limit. If this limit is
3881 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3882 * make sure to unregister the callbacks with
3883 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3884 *
3885 * @param request {@link NetworkRequest} describing this request.
3886 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3887 * the callback must not be shared - it uniquely specifies this request.
3888 * The callback is invoked on the default internal Handler.
3889 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3890 * @throws SecurityException if missing the appropriate permissions.
3891 * @throws RuntimeException if the app already has too many callbacks registered.
3892 */
3893 public void requestNetwork(@NonNull NetworkRequest request,
3894 @NonNull NetworkCallback networkCallback) {
3895 requestNetwork(request, networkCallback, getDefaultHandler());
3896 }
3897
3898 /**
3899 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3900 *
3901 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3902 * but runs all the callbacks on the passed Handler.
3903 *
3904 * <p>This method has the same permission requirements as
3905 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3906 * and throws the same exceptions in the same conditions.
3907 *
3908 * @param request {@link NetworkRequest} describing this request.
3909 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3910 * the callback must not be shared - it uniquely specifies this request.
3911 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3912 */
3913 public void requestNetwork(@NonNull NetworkRequest request,
3914 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
3915 CallbackHandler cbHandler = new CallbackHandler(handler);
3916 NetworkCapabilities nc = request.networkCapabilities;
3917 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
3918 }
3919
3920 /**
3921 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3922 * by a timeout.
3923 *
3924 * This function behaves identically to the non-timed-out version
3925 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3926 * is not found within the given time (in milliseconds) the
3927 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3928 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3929 * not have to be released if timed-out (it is automatically released). Unregistering a
3930 * request that timed out is not an error.
3931 *
3932 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3933 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3934 * for that purpose. Calling this method will attempt to bring up the requested network.
3935 *
3936 * <p>This method has the same permission requirements as
3937 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3938 * and throws the same exceptions in the same conditions.
3939 *
3940 * @param request {@link NetworkRequest} describing this request.
3941 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3942 * the callback must not be shared - it uniquely specifies this request.
3943 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3944 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3945 * be a positive value (i.e. >0).
3946 */
3947 public void requestNetwork(@NonNull NetworkRequest request,
3948 @NonNull NetworkCallback networkCallback, int timeoutMs) {
3949 checkTimeout(timeoutMs);
3950 NetworkCapabilities nc = request.networkCapabilities;
3951 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3952 getDefaultHandler());
3953 }
3954
3955 /**
3956 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3957 * by a timeout.
3958 *
3959 * This method behaves identically to
3960 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3961 * on the passed Handler.
3962 *
3963 * <p>This method has the same permission requirements as
3964 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3965 * and throws the same exceptions in the same conditions.
3966 *
3967 * @param request {@link NetworkRequest} describing this request.
3968 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3969 * the callback must not be shared - it uniquely specifies this request.
3970 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3971 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3972 * before {@link NetworkCallback#onUnavailable} is called.
3973 */
3974 public void requestNetwork(@NonNull NetworkRequest request,
3975 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
3976 checkTimeout(timeoutMs);
3977 CallbackHandler cbHandler = new CallbackHandler(handler);
3978 NetworkCapabilities nc = request.networkCapabilities;
3979 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
3980 }
3981
3982 /**
3983 * The lookup key for a {@link Network} object included with the intent after
3984 * successfully finding a network for the applications request. Retrieve it with
3985 * {@link android.content.Intent#getParcelableExtra(String)}.
3986 * <p>
3987 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3988 * then you must get a ConnectivityManager instance before doing so.
3989 */
3990 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
3991
3992 /**
3993 * The lookup key for a {@link NetworkRequest} object included with the intent after
3994 * successfully finding a network for the applications request. Retrieve it with
3995 * {@link android.content.Intent#getParcelableExtra(String)}.
3996 */
3997 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
3998
3999
4000 /**
4001 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
4002 *
4003 * This function behaves identically to the version that takes a NetworkCallback, but instead
4004 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4005 * the request may outlive the calling application and get called back when a suitable
4006 * network is found.
4007 * <p>
4008 * The operation is an Intent broadcast that goes to a broadcast receiver that
4009 * you registered with {@link Context#registerReceiver} or through the
4010 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4011 * <p>
4012 * The operation Intent is delivered with two extras, a {@link Network} typed
4013 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4014 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4015 * the original requests parameters. It is important to create a new,
4016 * {@link NetworkCallback} based request before completing the processing of the
4017 * Intent to reserve the network or it will be released shortly after the Intent
4018 * is processed.
4019 * <p>
4020 * If there is already a request for this Intent registered (with the equality of
4021 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4022 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4023 * <p>
4024 * The request may be released normally by calling
4025 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4026 * <p>It is presently unsupported to request a network with either
4027 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4028 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4029 * as these {@code NetworkCapabilities} represent states that a particular
4030 * network may never attain, and whether a network will attain these states
4031 * is unknown prior to bringing up the network so the framework does not
4032 * know how to go about satisfying a request with these capabilities.
4033 *
4034 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4035 * number of outstanding requests to 100 per app (identified by their UID), shared with
4036 * all variants of this method, of {@link #registerNetworkCallback} as well as
4037 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4038 * Requesting a network with this method will count toward this limit. If this limit is
4039 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4040 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4041 * or {@link #releaseNetworkRequest(PendingIntent)}.
4042 *
4043 * <p>This method requires the caller to hold either the
4044 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4045 * or the ability to modify system settings as determined by
4046 * {@link android.provider.Settings.System#canWrite}.</p>
4047 *
4048 * @param request {@link NetworkRequest} describing this request.
4049 * @param operation Action to perform when the network is available (corresponds
4050 * to the {@link NetworkCallback#onAvailable} call. Typically
4051 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4052 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4053 * @throws SecurityException if missing the appropriate permissions.
4054 * @throws RuntimeException if the app already has too many callbacks registered.
4055 */
4056 public void requestNetwork(@NonNull NetworkRequest request,
4057 @NonNull PendingIntent operation) {
4058 printStackTrace();
4059 checkPendingIntentNotNull(operation);
4060 try {
4061 mService.pendingRequestForNetwork(
4062 request.networkCapabilities, operation, mContext.getOpPackageName(),
4063 getAttributionTag());
4064 } catch (RemoteException e) {
4065 throw e.rethrowFromSystemServer();
4066 } catch (ServiceSpecificException e) {
4067 throw convertServiceException(e);
4068 }
4069 }
4070
4071 /**
4072 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4073 * <p>
4074 * This method has the same behavior as
4075 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4076 * releasing network resources and disconnecting.
4077 *
4078 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4079 * PendingIntent passed to
4080 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4081 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4082 */
4083 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4084 printStackTrace();
4085 checkPendingIntentNotNull(operation);
4086 try {
4087 mService.releasePendingNetworkRequest(operation);
4088 } catch (RemoteException e) {
4089 throw e.rethrowFromSystemServer();
4090 }
4091 }
4092
4093 private static void checkPendingIntentNotNull(PendingIntent intent) {
4094 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4095 }
4096
4097 private static void checkCallbackNotNull(NetworkCallback callback) {
4098 Preconditions.checkNotNull(callback, "null NetworkCallback");
4099 }
4100
4101 private static void checkTimeout(int timeoutMs) {
4102 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
4103 }
4104
4105 /**
4106 * Registers to receive notifications about all networks which satisfy the given
4107 * {@link NetworkRequest}. The callbacks will continue to be called until
4108 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4109 * called.
4110 *
4111 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4112 * number of outstanding requests to 100 per app (identified by their UID), shared with
4113 * all variants of this method, of {@link #requestNetwork} as well as
4114 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4115 * Requesting a network with this method will count toward this limit. If this limit is
4116 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4117 * make sure to unregister the callbacks with
4118 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4119 *
4120 * @param request {@link NetworkRequest} describing this request.
4121 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4122 * networks change state.
4123 * The callback is invoked on the default internal Handler.
4124 * @throws RuntimeException if the app already has too many callbacks registered.
4125 */
4126 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4127 public void registerNetworkCallback(@NonNull NetworkRequest request,
4128 @NonNull NetworkCallback networkCallback) {
4129 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4130 }
4131
4132 /**
4133 * Registers to receive notifications about all networks which satisfy the given
4134 * {@link NetworkRequest}. The callbacks will continue to be called until
4135 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4136 * called.
4137 *
4138 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4139 * number of outstanding requests to 100 per app (identified by their UID), shared with
4140 * all variants of this method, of {@link #requestNetwork} as well as
4141 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4142 * Requesting a network with this method will count toward this limit. If this limit is
4143 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4144 * make sure to unregister the callbacks with
4145 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4146 *
4147 *
4148 * @param request {@link NetworkRequest} describing this request.
4149 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4150 * networks change state.
4151 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4152 * @throws RuntimeException if the app already has too many callbacks registered.
4153 */
4154 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4155 public void registerNetworkCallback(@NonNull NetworkRequest request,
4156 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4157 CallbackHandler cbHandler = new CallbackHandler(handler);
4158 NetworkCapabilities nc = request.networkCapabilities;
4159 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4160 }
4161
4162 /**
4163 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4164 * {@link NetworkRequest}.
4165 *
4166 * This function behaves identically to the version that takes a NetworkCallback, but instead
4167 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4168 * the request may outlive the calling application and get called back when a suitable
4169 * network is found.
4170 * <p>
4171 * The operation is an Intent broadcast that goes to a broadcast receiver that
4172 * you registered with {@link Context#registerReceiver} or through the
4173 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4174 * <p>
4175 * The operation Intent is delivered with two extras, a {@link Network} typed
4176 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4177 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4178 * the original requests parameters.
4179 * <p>
4180 * If there is already a request for this Intent registered (with the equality of
4181 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4182 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4183 * <p>
4184 * The request may be released normally by calling
4185 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4186 *
4187 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4188 * number of outstanding requests to 100 per app (identified by their UID), shared with
4189 * all variants of this method, of {@link #requestNetwork} as well as
4190 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4191 * Requesting a network with this method will count toward this limit. If this limit is
4192 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4193 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4194 * or {@link #releaseNetworkRequest(PendingIntent)}.
4195 *
4196 * @param request {@link NetworkRequest} describing this request.
4197 * @param operation Action to perform when the network is available (corresponds
4198 * to the {@link NetworkCallback#onAvailable} call. Typically
4199 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4200 * @throws RuntimeException if the app already has too many callbacks registered.
4201 */
4202 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4203 public void registerNetworkCallback(@NonNull NetworkRequest request,
4204 @NonNull PendingIntent operation) {
4205 printStackTrace();
4206 checkPendingIntentNotNull(operation);
4207 try {
4208 mService.pendingListenForNetwork(
4209 request.networkCapabilities, operation, mContext.getOpPackageName());
4210 } catch (RemoteException e) {
4211 throw e.rethrowFromSystemServer();
4212 } catch (ServiceSpecificException e) {
4213 throw convertServiceException(e);
4214 }
4215 }
4216
4217 /**
4218 * Registers to receive notifications about changes in the system default network. The callbacks
4219 * will continue to be called until either the application exits or
4220 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4221 *
4222 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4223 * number of outstanding requests to 100 per app (identified by their UID), shared with
4224 * all variants of this method, of {@link #requestNetwork} as well as
4225 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4226 * Requesting a network with this method will count toward this limit. If this limit is
4227 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4228 * make sure to unregister the callbacks with
4229 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4230 *
4231 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4232 * system default network changes.
4233 * The callback is invoked on the default internal Handler.
4234 * @throws RuntimeException if the app already has too many callbacks registered.
4235 */
4236 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4237 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4238 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4239 }
4240
4241 /**
4242 * Registers to receive notifications about changes in the system default network. The callbacks
4243 * will continue to be called until either the application exits or
4244 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4245 *
4246 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4247 * number of outstanding requests to 100 per app (identified by their UID), shared with
4248 * all variants of this method, of {@link #requestNetwork} as well as
4249 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4250 * Requesting a network with this method will count toward this limit. If this limit is
4251 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4252 * make sure to unregister the callbacks with
4253 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4254 *
4255 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4256 * system default network changes.
4257 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4258 * @throws RuntimeException if the app already has too many callbacks registered.
4259 */
4260 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4261 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4262 @NonNull Handler handler) {
4263 // This works because if the NetworkCapabilities are null,
4264 // ConnectivityService takes them from the default request.
4265 //
4266 // Since the capabilities are exactly the same as the default request's
4267 // capabilities, this request is guaranteed, at all times, to be
4268 // satisfied by the same network, if any, that satisfies the default
4269 // request, i.e., the system default network.
4270 CallbackHandler cbHandler = new CallbackHandler(handler);
4271 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4272 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4273 }
4274
4275 /**
4276 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4277 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4278 * network connection for updated bandwidth information. The caller will be notified via
4279 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4280 * method assumes that the caller has previously called
4281 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4282 * changes.
4283 *
4284 * @param network {@link Network} specifying which network you're interested.
4285 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4286 */
4287 public boolean requestBandwidthUpdate(@NonNull Network network) {
4288 try {
4289 return mService.requestBandwidthUpdate(network);
4290 } catch (RemoteException e) {
4291 throw e.rethrowFromSystemServer();
4292 }
4293 }
4294
4295 /**
4296 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4297 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4298 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4299 * If the given {@code NetworkCallback} had previously been used with
4300 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4301 * will be disconnected.
4302 *
4303 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4304 * triggering it as soon as this call returns.
4305 *
4306 * @param networkCallback The {@link NetworkCallback} used when making the request.
4307 */
4308 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4309 printStackTrace();
4310 checkCallbackNotNull(networkCallback);
4311 final List<NetworkRequest> reqs = new ArrayList<>();
4312 // Find all requests associated to this callback and stop callback triggers immediately.
4313 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4314 synchronized (sCallbacks) {
4315 Preconditions.checkArgument(networkCallback.networkRequest != null,
4316 "NetworkCallback was not registered");
4317 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4318 Log.d(TAG, "NetworkCallback was already unregistered");
4319 return;
4320 }
4321 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4322 if (e.getValue() == networkCallback) {
4323 reqs.add(e.getKey());
4324 }
4325 }
4326 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4327 for (NetworkRequest r : reqs) {
4328 try {
4329 mService.releaseNetworkRequest(r);
4330 } catch (RemoteException e) {
4331 throw e.rethrowFromSystemServer();
4332 }
4333 // Only remove mapping if rpc was successful.
4334 sCallbacks.remove(r);
4335 }
4336 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4337 }
4338 }
4339
4340 /**
4341 * Unregisters a callback previously registered via
4342 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4343 *
4344 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4345 * PendingIntent passed to
4346 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4347 * Cannot be null.
4348 */
4349 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4350 releaseNetworkRequest(operation);
4351 }
4352
4353 /**
4354 * Informs the system whether it should switch to {@code network} regardless of whether it is
4355 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4356 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4357 * the system default network regardless of any other network that's currently connected. If
4358 * {@code always} is true, then the choice is remembered, so that the next time the user
4359 * connects to this network, the system will switch to it.
4360 *
4361 * @param network The network to accept.
4362 * @param accept Whether to accept the network even if unvalidated.
4363 * @param always Whether to remember this choice in the future.
4364 *
4365 * @hide
4366 */
4367 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4368 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4369 try {
4370 mService.setAcceptUnvalidated(network, accept, always);
4371 } catch (RemoteException e) {
4372 throw e.rethrowFromSystemServer();
4373 }
4374 }
4375
4376 /**
4377 * Informs the system whether it should consider the network as validated even if it only has
4378 * partial connectivity. If {@code accept} is true, then the network will be considered as
4379 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4380 * is remembered, so that the next time the user connects to this network, the system will
4381 * switch to it.
4382 *
4383 * @param network The network to accept.
4384 * @param accept Whether to consider the network as validated even if it has partial
4385 * connectivity.
4386 * @param always Whether to remember this choice in the future.
4387 *
4388 * @hide
4389 */
4390 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4391 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4392 try {
4393 mService.setAcceptPartialConnectivity(network, accept, always);
4394 } catch (RemoteException e) {
4395 throw e.rethrowFromSystemServer();
4396 }
4397 }
4398
4399 /**
4400 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4401 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4402 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4403 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4404 *
4405 * @param network The network to accept.
4406 *
4407 * @hide
4408 */
4409 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4410 public void setAvoidUnvalidated(Network network) {
4411 try {
4412 mService.setAvoidUnvalidated(network);
4413 } catch (RemoteException e) {
4414 throw e.rethrowFromSystemServer();
4415 }
4416 }
4417
4418 /**
4419 * Requests that the system open the captive portal app on the specified network.
4420 *
4421 * @param network The network to log into.
4422 *
4423 * @hide
4424 */
4425 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4426 public void startCaptivePortalApp(Network network) {
4427 try {
4428 mService.startCaptivePortalApp(network);
4429 } catch (RemoteException e) {
4430 throw e.rethrowFromSystemServer();
4431 }
4432 }
4433
4434 /**
4435 * Requests that the system open the captive portal app with the specified extras.
4436 *
4437 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4438 * corresponding permission.
4439 * @param network Network on which the captive portal was detected.
4440 * @param appExtras Extras to include in the app start intent.
4441 * @hide
4442 */
4443 @SystemApi
4444 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4445 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4446 try {
4447 mService.startCaptivePortalAppInternal(network, appExtras);
4448 } catch (RemoteException e) {
4449 throw e.rethrowFromSystemServer();
4450 }
4451 }
4452
4453 /**
4454 * Determine whether the device is configured to avoid bad wifi.
4455 * @hide
4456 */
4457 @SystemApi
4458 @RequiresPermission(anyOf = {
4459 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4460 android.Manifest.permission.NETWORK_STACK})
4461 public boolean shouldAvoidBadWifi() {
4462 try {
4463 return mService.shouldAvoidBadWifi();
4464 } catch (RemoteException e) {
4465 throw e.rethrowFromSystemServer();
4466 }
4467 }
4468
4469 /**
4470 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4471 * time-sensitive user-facing operations when the system default network is temporarily
4472 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4473 * this method), and the operation should be infrequent to ensure that data usage is limited.
4474 *
4475 * An example of such an operation might be a time-sensitive foreground activity, such as a
4476 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4477 */
4478 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4479
4480 /**
4481 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4482 * a backup channel for traffic that is primarily going over another network.
4483 *
4484 * An example might be maintaining backup connections to peers or servers for the purpose of
4485 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4486 * on backup paths should be negligible compared to the traffic on the main path.
4487 */
4488 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4489
4490 /**
4491 * It is acceptable to use metered data to improve network latency and performance.
4492 */
4493 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4494
4495 /**
4496 * Return value to use for unmetered networks. On such networks we currently set all the flags
4497 * to true.
4498 * @hide
4499 */
4500 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4501 MULTIPATH_PREFERENCE_HANDOVER |
4502 MULTIPATH_PREFERENCE_RELIABILITY |
4503 MULTIPATH_PREFERENCE_PERFORMANCE;
4504
4505 /** @hide */
4506 @Retention(RetentionPolicy.SOURCE)
4507 @IntDef(flag = true, value = {
4508 MULTIPATH_PREFERENCE_HANDOVER,
4509 MULTIPATH_PREFERENCE_RELIABILITY,
4510 MULTIPATH_PREFERENCE_PERFORMANCE,
4511 })
4512 public @interface MultipathPreference {
4513 }
4514
4515 /**
4516 * Provides a hint to the calling application on whether it is desirable to use the
4517 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4518 * for multipath data transfer on this network when it is not the system default network.
4519 * Applications desiring to use multipath network protocols should call this method before
4520 * each such operation.
4521 *
4522 * @param network The network on which the application desires to use multipath data.
4523 * If {@code null}, this method will return the a preference that will generally
4524 * apply to metered networks.
4525 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4526 */
4527 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4528 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
4529 try {
4530 return mService.getMultipathPreference(network);
4531 } catch (RemoteException e) {
4532 throw e.rethrowFromSystemServer();
4533 }
4534 }
4535
4536 /**
4537 * Resets all connectivity manager settings back to factory defaults.
4538 * @hide
4539 */
4540 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4541 public void factoryReset() {
4542 try {
4543 mService.factoryReset();
4544 mTetheringManager.stopAllTethering();
4545 } catch (RemoteException e) {
4546 throw e.rethrowFromSystemServer();
4547 }
4548 }
4549
4550 /**
4551 * Binds the current process to {@code network}. All Sockets created in the future
4552 * (and not explicitly bound via a bound SocketFactory from
4553 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4554 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4555 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4556 * work and all host name resolutions will fail. This is by design so an application doesn't
4557 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4558 * To clear binding pass {@code null} for {@code network}. Using individually bound
4559 * Sockets created by Network.getSocketFactory().createSocket() and
4560 * performing network-specific host name resolutions via
4561 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4562 * {@code bindProcessToNetwork}.
4563 *
4564 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4565 * the current binding.
4566 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4567 */
4568 public boolean bindProcessToNetwork(@Nullable Network network) {
4569 // Forcing callers to call through non-static function ensures ConnectivityManager
4570 // instantiated.
4571 return setProcessDefaultNetwork(network);
4572 }
4573
4574 /**
4575 * Binds the current process to {@code network}. All Sockets created in the future
4576 * (and not explicitly bound via a bound SocketFactory from
4577 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4578 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4579 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4580 * work and all host name resolutions will fail. This is by design so an application doesn't
4581 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4582 * To clear binding pass {@code null} for {@code network}. Using individually bound
4583 * Sockets created by Network.getSocketFactory().createSocket() and
4584 * performing network-specific host name resolutions via
4585 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4586 * {@code setProcessDefaultNetwork}.
4587 *
4588 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4589 * the current binding.
4590 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4591 * @deprecated This function can throw {@link IllegalStateException}. Use
4592 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4593 * is a direct replacement.
4594 */
4595 @Deprecated
4596 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
4597 int netId = (network == null) ? NETID_UNSET : network.netId;
4598 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4599
4600 if (netId != NETID_UNSET) {
4601 netId = network.getNetIdForResolv();
4602 }
4603
4604 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4605 return false;
4606 }
4607
4608 if (!isSameNetId) {
4609 // Set HTTP proxy system properties to match network.
4610 // TODO: Deprecate this static method and replace it with a non-static version.
4611 try {
4612 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4613 } catch (SecurityException e) {
4614 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4615 Log.e(TAG, "Can't set proxy properties", e);
4616 }
4617 // Must flush DNS cache as new network may have different DNS resolutions.
4618 InetAddress.clearDnsCache();
4619 // Must flush socket pool as idle sockets will be bound to previous network and may
4620 // cause subsequent fetches to be performed on old network.
4621 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
4622 }
4623
4624 return true;
4625 }
4626
4627 /**
4628 * Returns the {@link Network} currently bound to this process via
4629 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4630 *
4631 * @return {@code Network} to which this process is bound, or {@code null}.
4632 */
4633 @Nullable
4634 public Network getBoundNetworkForProcess() {
4635 // Forcing callers to call thru non-static function ensures ConnectivityManager
4636 // instantiated.
4637 return getProcessDefaultNetwork();
4638 }
4639
4640 /**
4641 * Returns the {@link Network} currently bound to this process via
4642 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4643 *
4644 * @return {@code Network} to which this process is bound, or {@code null}.
4645 * @deprecated Using this function can lead to other functions throwing
4646 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4647 * {@code getBoundNetworkForProcess} is a direct replacement.
4648 */
4649 @Deprecated
4650 @Nullable
4651 public static Network getProcessDefaultNetwork() {
4652 int netId = NetworkUtils.getBoundNetworkForProcess();
4653 if (netId == NETID_UNSET) return null;
4654 return new Network(netId);
4655 }
4656
4657 private void unsupportedStartingFrom(int version) {
4658 if (Process.myUid() == Process.SYSTEM_UID) {
4659 // The getApplicationInfo() call we make below is not supported in system context. Let
4660 // the call through here, and rely on the fact that ConnectivityService will refuse to
4661 // allow the system to use these APIs anyway.
4662 return;
4663 }
4664
4665 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4666 throw new UnsupportedOperationException(
4667 "This method is not supported in target SDK version " + version + " and above");
4668 }
4669 }
4670
4671 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4672 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
4673 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
4674 // remove these exemptions. Note that this check is not secure, and apps can still access these
4675 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4676 // so is unsupported and may break in the future. http://b/22728205
4677 private void checkLegacyRoutingApiAccess() {
4678 unsupportedStartingFrom(VERSION_CODES.M);
4679 }
4680
4681 /**
4682 * Binds host resolutions performed by this process to {@code network}.
4683 * {@link #bindProcessToNetwork} takes precedence over this setting.
4684 *
4685 * @param network The {@link Network} to bind host resolutions from the current process to, or
4686 * {@code null} to clear the current binding.
4687 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4688 * @hide
4689 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4690 */
4691 @Deprecated
4692 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4693 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
4694 return NetworkUtils.bindProcessToNetworkForHostResolution(
4695 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
4696 }
4697
4698 /**
4699 * Device is not restricting metered network activity while application is running on
4700 * background.
4701 */
4702 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4703
4704 /**
4705 * Device is restricting metered network activity while application is running on background,
4706 * but application is allowed to bypass it.
4707 * <p>
4708 * In this state, application should take action to mitigate metered network access.
4709 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4710 */
4711 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4712
4713 /**
4714 * Device is restricting metered network activity while application is running on background.
4715 * <p>
4716 * In this state, application should not try to use the network while running on background,
4717 * because it would be denied.
4718 */
4719 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4720
4721 /**
4722 * A change in the background metered network activity restriction has occurred.
4723 * <p>
4724 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4725 * applies to them.
4726 * <p>
4727 * This is only sent to registered receivers, not manifest receivers.
4728 */
4729 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4730 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4731 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4732
4733 /** @hide */
4734 @Retention(RetentionPolicy.SOURCE)
4735 @IntDef(flag = false, value = {
4736 RESTRICT_BACKGROUND_STATUS_DISABLED,
4737 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4738 RESTRICT_BACKGROUND_STATUS_ENABLED,
4739 })
4740 public @interface RestrictBackgroundStatus {
4741 }
4742
4743 private INetworkPolicyManager getNetworkPolicyManager() {
4744 synchronized (this) {
4745 if (mNPManager != null) {
4746 return mNPManager;
4747 }
4748 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4749 .getService(Context.NETWORK_POLICY_SERVICE));
4750 return mNPManager;
4751 }
4752 }
4753
4754 /**
4755 * Determines if the calling application is subject to metered network restrictions while
4756 * running on background.
4757 *
4758 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4759 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4760 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
4761 */
4762 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4763 try {
4764 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4765 } catch (RemoteException e) {
4766 throw e.rethrowFromSystemServer();
4767 }
4768 }
4769
4770 /**
4771 * The network watchlist is a list of domains and IP addresses that are associated with
4772 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4773 * currently used by the system for validation purposes.
4774 *
4775 * @return Hash of network watchlist config file. Null if config does not exist.
4776 */
4777 @Nullable
4778 public byte[] getNetworkWatchlistConfigHash() {
4779 try {
4780 return mService.getNetworkWatchlistConfigHash();
4781 } catch (RemoteException e) {
4782 Log.e(TAG, "Unable to get watchlist config hash");
4783 throw e.rethrowFromSystemServer();
4784 }
4785 }
4786
4787 /**
4788 * Returns the {@code uid} of the owner of a network connection.
4789 *
4790 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4791 * IPPROTO_UDP} currently supported.
4792 * @param local The local {@link InetSocketAddress} of a connection.
4793 * @param remote The remote {@link InetSocketAddress} of a connection.
4794 * @return {@code uid} if the connection is found and the app has permission to observe it
4795 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4796 * android.os.Process#INVALID_UID} if the connection is not found.
4797 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4798 * user.
4799 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
4800 */
4801 public int getConnectionOwnerUid(
4802 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
4803 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4804 try {
4805 return mService.getConnectionOwnerUid(connectionInfo);
4806 } catch (RemoteException e) {
4807 throw e.rethrowFromSystemServer();
4808 }
4809 }
4810
4811 private void printStackTrace() {
4812 if (DEBUG) {
4813 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4814 final StringBuffer sb = new StringBuffer();
4815 for (int i = 3; i < callStack.length; i++) {
4816 final String stackTrace = callStack[i].toString();
4817 if (stackTrace == null || stackTrace.contains("android.os")) {
4818 break;
4819 }
4820 sb.append(" [").append(stackTrace).append("]");
4821 }
4822 Log.d(TAG, "StackLog:" + sb.toString());
4823 }
4824 }
4825
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09004826 /** @hide */
4827 public TestNetworkManager startOrGetTestNetworkManager() {
4828 final IBinder tnBinder;
4829 try {
4830 tnBinder = mService.startOrGetTestNetworkService();
4831 } catch (RemoteException e) {
4832 throw e.rethrowFromSystemServer();
4833 }
4834
4835 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4836 }
4837
4838 /** @hide */
4839 public VpnManager createVpnManager() {
4840 return new VpnManager(mContext, mService);
4841 }
4842
4843 /** @hide */
4844 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4845 return new ConnectivityDiagnosticsManager(mContext, mService);
4846 }
4847
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004848 /**
4849 * Simulates a Data Stall for the specified Network.
4850 *
4851 * <p>This method should only be used for tests.
4852 *
4853 * <p>The caller must be the owner of the specified Network.
4854 *
4855 * @param detectionMethod The detection method used to identify the Data Stall.
4856 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4857 * @param network The Network for which a Data Stall is being simluated.
4858 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4859 * @throws SecurityException if the caller is not the owner of the given network.
4860 * @hide
4861 */
4862 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4863 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4864 android.Manifest.permission.NETWORK_STACK})
4865 public void simulateDataStall(int detectionMethod, long timestampMillis,
4866 @NonNull Network network, @NonNull PersistableBundle extras) {
4867 try {
4868 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4869 } catch (RemoteException e) {
4870 e.rethrowFromSystemServer();
4871 }
4872 }
4873
4874 private void setOemNetworkPreference(@NonNull OemNetworkPreferences preference) {
4875 Log.d(TAG, "setOemNetworkPreference called with preference: "
4876 + preference.toString());
4877 }
4878
4879 @NonNull
4880 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4881
4882 /**
4883 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4884 * receive available QoS events related to the {@link Network} and local ip + port
4885 * specified within socketInfo.
4886 * <p/>
4887 * The same {@link QosCallback} must be unregistered before being registered a second time,
4888 * otherwise {@link QosCallbackRegistrationException} is thrown.
4889 * <p/>
4890 * This API does not, in itself, require any permission if called with a network that is not
4891 * restricted. However, the underlying implementation currently only supports the IMS network,
4892 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4893 * useful, because they'd never be called back on networks that they would have access to.
4894 *
4895 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4896 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4897 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4898 * @throws RuntimeException if the app already has too many callbacks registered.
4899 *
4900 * Exceptions after the time of registration is passed through
4901 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4902 *
4903 * @param socketInfo the socket information used to match QoS events
4904 * @param callback receives qos events that satisfy socketInfo
4905 * @param executor The executor on which the callback will be invoked. The provided
4906 * {@link Executor} must run callback sequentially, otherwise the order of
4907 * callbacks cannot be guaranteed.
4908 *
4909 * @hide
4910 */
4911 @SystemApi
4912 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4913 @NonNull final QosCallback callback,
4914 @CallbackExecutor @NonNull final Executor executor) {
4915 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4916 Objects.requireNonNull(callback, "callback must be non-null");
4917 Objects.requireNonNull(executor, "executor must be non-null");
4918
4919 try {
4920 synchronized (mQosCallbackConnections) {
4921 if (getQosCallbackConnection(callback) == null) {
4922 final QosCallbackConnection connection =
4923 new QosCallbackConnection(this, callback, executor);
4924 mQosCallbackConnections.add(connection);
4925 mService.registerQosSocketCallback(socketInfo, connection);
4926 } else {
4927 Log.e(TAG, "registerQosCallback: Callback already registered");
4928 throw new QosCallbackRegistrationException();
4929 }
4930 }
4931 } catch (final RemoteException e) {
4932 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4933
4934 // The same unregister method method is called for consistency even though nothing
4935 // will be sent to the ConnectivityService since the callback was never successfully
4936 // registered.
4937 unregisterQosCallback(callback);
4938 e.rethrowFromSystemServer();
4939 } catch (final ServiceSpecificException e) {
4940 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4941 unregisterQosCallback(callback);
4942 throw convertServiceException(e);
4943 }
4944 }
4945
4946 /**
4947 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4948 * events once unregistered and can be registered a second time.
4949 * <p/>
4950 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4951 *
4952 * @param callback the callback being unregistered
4953 *
4954 * @hide
4955 */
4956 @SystemApi
4957 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4958 Objects.requireNonNull(callback, "The callback must be non-null");
4959 try {
4960 synchronized (mQosCallbackConnections) {
4961 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4962 if (connection != null) {
4963 connection.stopReceivingMessages();
4964 mService.unregisterQosCallback(connection);
4965 mQosCallbackConnections.remove(connection);
4966 } else {
4967 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4968 }
4969 }
4970 } catch (final RemoteException e) {
4971 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4972 e.rethrowFromSystemServer();
4973 }
4974 }
4975
4976 /**
4977 * Gets the connection related to the callback.
4978 *
4979 * @param callback the callback to look up
4980 * @return the related connection
4981 */
4982 @Nullable
4983 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4984 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4985 // Checking by reference here is intentional
4986 if (connection.getCallback() == callback) {
4987 return connection;
4988 }
4989 }
4990 return null;
4991 }
4992
4993 /**
4994 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4995 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4996 * be used to request that the system provide a network without causing the network to be
4997 * in the foreground.
4998 *
4999 * <p>This method will attempt to find the best network that matches the passed
5000 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5001 * criteria. The platform will evaluate which network is the best at its own discretion.
5002 * Throughput, latency, cost per byte, policy, user preference and other considerations
5003 * may be factored in the decision of what is considered the best network.
5004 *
5005 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5006 * matching this request, while always attempting to match the request to a better network if
5007 * possible. If a better match is found, the platform will switch this request to the now-best
5008 * network and inform the app of the newly best network by invoking
5009 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5010 * will not try to maintain any other network than the best one currently matching the request:
5011 * a network not matching any network request may be disconnected at any time.
5012 *
5013 * <p>For example, an application could use this method to obtain a connected cellular network
5014 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5015 * radio to consume additional power. Or, an application could inform the system that it wants
5016 * a network supporting sending MMSes and have the system let it know about the currently best
5017 * MMS-supporting network through the provided {@link NetworkCallback}.
5018 *
5019 * <p>The status of the request can be followed by listening to the various callbacks described
5020 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5021 * used to direct traffic to the network (although accessing some networks may be subject to
5022 * holding specific permissions). Callers will learn about the specific characteristics of the
5023 * network through
5024 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5025 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5026 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5027 * matching the request at any given time; therefore when a better network matching the request
5028 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5029 * with the new network after which no further updates are given about the previously-best
5030 * network, unless it becomes the best again at some later time. All callbacks are invoked
5031 * in order on the same thread, which by default is a thread created by the framework running
5032 * in the app.
5033 *
5034 * <p>This{@link NetworkRequest} will live until released via
5035 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5036 * which point the system may let go of the network at any time.
5037 *
5038 * <p>It is presently unsupported to request a network with mutable
5039 * {@link NetworkCapabilities} such as
5040 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5041 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5042 * as these {@code NetworkCapabilities} represent states that a particular
5043 * network may never attain, and whether a network will attain these states
5044 * is unknown prior to bringing up the network so the framework does not
5045 * know how to go about satisfying a request with these capabilities.
5046 *
5047 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5048 * number of outstanding requests to 100 per app (identified by their UID), shared with
5049 * all variants of this method, of {@link #registerNetworkCallback} as well as
5050 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5051 * Requesting a network with this method will count toward this limit. If this limit is
5052 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5053 * make sure to unregister the callbacks with
5054 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5055 *
5056 * @param request {@link NetworkRequest} describing this request.
5057 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5058 * If null, the callback is invoked on the default internal Handler.
5059 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5060 * the callback must not be shared - it uniquely specifies this request.
5061 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5062 * @throws SecurityException if missing the appropriate permissions.
5063 * @throws RuntimeException if the app already has too many callbacks registered.
5064 *
5065 * @hide
5066 */
5067 @SystemApi(client = MODULE_LIBRARIES)
5068 @SuppressLint("ExecutorRegistration")
5069 @RequiresPermission(anyOf = {
5070 android.Manifest.permission.NETWORK_SETTINGS,
5071 android.Manifest.permission.NETWORK_STACK,
5072 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5073 })
5074 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
5075 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
5076 final NetworkCapabilities nc = request.networkCapabilities;
5077 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
5078 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
5079 }
5080}