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