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