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