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