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