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