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