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