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