blob: de85833c56d0f629dbf875c0b60af4a5f4c21c39 [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 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001125 * @hide
1126 */
1127 @RequiresPermission(anyOf = {
1128 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin29278ee2021-03-22 11:51:27 +08001129 android.Manifest.permission.NETWORK_STACK,
1130 android.Manifest.permission.NETWORK_SETTINGS})
1131 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001132 public void setRequireVpnForUids(boolean requireVpn,
1133 @NonNull Collection<Range<Integer>> ranges) {
1134 Objects.requireNonNull(ranges);
1135 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1136 // This method is not necessarily expected to be used outside the system server, so
1137 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1138 // stack process, or by tests.
1139 UidRange[] rangesArray = new UidRange[ranges.size()];
1140 int index = 0;
1141 for (Range<Integer> range : ranges) {
1142 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1143 }
1144 try {
1145 mService.setRequireVpnForUids(requireVpn, rangesArray);
1146 } catch (RemoteException e) {
1147 throw e.rethrowFromSystemServer();
1148 }
1149 }
1150
1151 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001152 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1153 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1154 * but is still supported for backwards compatibility.
1155 * <p>
1156 * This type of VPN is assumed always to use the system default network, and must always declare
1157 * exactly one underlying network, which is the network that was the default when the VPN
1158 * connected.
1159 * <p>
1160 * Calling this method with {@code true} enables legacy behaviour, specifically:
1161 * <ul>
1162 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1163 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1164 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1165 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1166 * underlying the VPN.</li>
1167 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1168 * similarly replaced by the VPN network state.</li>
1169 * <li>Information on current network interfaces passed to NetworkStatsService will not
1170 * include any VPN interfaces.</li>
1171 * </ul>
1172 *
1173 * @param enabled whether legacy lockdown VPN is enabled or disabled
1174 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001175 * @hide
1176 */
1177 @RequiresPermission(anyOf = {
1178 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin29278ee2021-03-22 11:51:27 +08001179 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001180 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin29278ee2021-03-22 11:51:27 +08001181 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001182 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1183 try {
1184 mService.setLegacyLockdownVpnEnabled(enabled);
1185 } catch (RemoteException e) {
1186 throw e.rethrowFromSystemServer();
1187 }
1188 }
1189
1190 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001191 * Returns details about the currently active default data network
1192 * for a given uid. This is for internal use only to avoid spying
1193 * other apps.
1194 *
1195 * @return a {@link NetworkInfo} object for the current default network
1196 * for the given uid or {@code null} if no default network is
1197 * available for the specified uid.
1198 *
1199 * {@hide}
1200 */
1201 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1202 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1203 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1204 return getActiveNetworkInfoForUid(uid, false);
1205 }
1206
1207 /** {@hide} */
1208 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1209 try {
1210 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1211 } catch (RemoteException e) {
1212 throw e.rethrowFromSystemServer();
1213 }
1214 }
1215
1216 /**
1217 * Returns connection status information about a particular
1218 * network type.
1219 *
1220 * @param networkType integer specifying which networkType in
1221 * which you're interested.
1222 * @return a {@link NetworkInfo} object for the requested
1223 * network type or {@code null} if the type is not
1224 * supported by the device. If {@code networkType} is
1225 * TYPE_VPN and a VPN is active for the calling app,
1226 * then this method will try to return one of the
1227 * underlying networks for the VPN or null if the
1228 * VPN agent didn't specify any.
1229 *
1230 * @deprecated This method does not support multiple connected networks
1231 * of the same type. Use {@link #getAllNetworks} and
1232 * {@link #getNetworkInfo(android.net.Network)} instead.
1233 */
1234 @Deprecated
1235 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1236 @Nullable
1237 public NetworkInfo getNetworkInfo(int networkType) {
1238 try {
1239 return mService.getNetworkInfo(networkType);
1240 } catch (RemoteException e) {
1241 throw e.rethrowFromSystemServer();
1242 }
1243 }
1244
1245 /**
1246 * Returns connection status information about a particular
1247 * Network.
1248 *
1249 * @param network {@link Network} specifying which network
1250 * in which you're interested.
1251 * @return a {@link NetworkInfo} object for the requested
1252 * network or {@code null} if the {@code Network}
1253 * is not valid.
1254 * @deprecated See {@link NetworkInfo}.
1255 */
1256 @Deprecated
1257 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1258 @Nullable
1259 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1260 return getNetworkInfoForUid(network, Process.myUid(), false);
1261 }
1262
1263 /** {@hide} */
1264 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1265 try {
1266 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1267 } catch (RemoteException e) {
1268 throw e.rethrowFromSystemServer();
1269 }
1270 }
1271
1272 /**
1273 * Returns connection status information about all network
1274 * types supported by the device.
1275 *
1276 * @return an array of {@link NetworkInfo} objects. Check each
1277 * {@link NetworkInfo#getType} for which type each applies.
1278 *
1279 * @deprecated This method does not support multiple connected networks
1280 * of the same type. Use {@link #getAllNetworks} and
1281 * {@link #getNetworkInfo(android.net.Network)} instead.
1282 */
1283 @Deprecated
1284 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1285 @NonNull
1286 public NetworkInfo[] getAllNetworkInfo() {
1287 try {
1288 return mService.getAllNetworkInfo();
1289 } catch (RemoteException e) {
1290 throw e.rethrowFromSystemServer();
1291 }
1292 }
1293
1294 /**
junyulaib1211372021-03-03 12:09:05 +08001295 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1296 * connected.
1297 * @hide
1298 */
1299 @SystemApi(client = MODULE_LIBRARIES)
1300 @RequiresPermission(anyOf = {
1301 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1302 android.Manifest.permission.NETWORK_STACK,
1303 android.Manifest.permission.NETWORK_SETTINGS})
1304 @NonNull
1305 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1306 try {
1307 return mService.getAllNetworkStateSnapshot();
1308 } catch (RemoteException e) {
1309 throw e.rethrowFromSystemServer();
1310 }
1311 }
1312
1313 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001314 * Returns the {@link Network} object currently serving a given type, or
1315 * null if the given type is not connected.
1316 *
1317 * @hide
1318 * @deprecated This method does not support multiple connected networks
1319 * of the same type. Use {@link #getAllNetworks} and
1320 * {@link #getNetworkInfo(android.net.Network)} instead.
1321 */
1322 @Deprecated
1323 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1324 @UnsupportedAppUsage
1325 public Network getNetworkForType(int networkType) {
1326 try {
1327 return mService.getNetworkForType(networkType);
1328 } catch (RemoteException e) {
1329 throw e.rethrowFromSystemServer();
1330 }
1331 }
1332
1333 /**
1334 * Returns an array of all {@link Network} currently tracked by the
1335 * framework.
1336 *
1337 * @return an array of {@link Network} objects.
1338 */
1339 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1340 @NonNull
1341 public Network[] getAllNetworks() {
1342 try {
1343 return mService.getAllNetworks();
1344 } catch (RemoteException e) {
1345 throw e.rethrowFromSystemServer();
1346 }
1347 }
1348
1349 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001350 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001351 * the Networks that applications run by the given user will use by default.
1352 * @hide
1353 */
1354 @UnsupportedAppUsage
1355 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1356 try {
1357 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001358 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001359 } catch (RemoteException e) {
1360 throw e.rethrowFromSystemServer();
1361 }
1362 }
1363
1364 /**
1365 * Returns the IP information for the current default network.
1366 *
1367 * @return a {@link LinkProperties} object describing the IP info
1368 * for the current default network, or {@code null} if there
1369 * is no current default network.
1370 *
1371 * {@hide}
1372 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1373 * value of {@link #getActiveNetwork()} instead. In particular,
1374 * this method will return non-null LinkProperties even if the
1375 * app is blocked by policy from using this network.
1376 */
1377 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1378 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1379 public LinkProperties getActiveLinkProperties() {
1380 try {
1381 return mService.getActiveLinkProperties();
1382 } catch (RemoteException e) {
1383 throw e.rethrowFromSystemServer();
1384 }
1385 }
1386
1387 /**
1388 * Returns the IP information for a given network type.
1389 *
1390 * @param networkType the network type of interest.
1391 * @return a {@link LinkProperties} object describing the IP info
1392 * for the given networkType, or {@code null} if there is
1393 * no current default network.
1394 *
1395 * {@hide}
1396 * @deprecated This method does not support multiple connected networks
1397 * of the same type. Use {@link #getAllNetworks},
1398 * {@link #getNetworkInfo(android.net.Network)}, and
1399 * {@link #getLinkProperties(android.net.Network)} instead.
1400 */
1401 @Deprecated
1402 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1403 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1404 public LinkProperties getLinkProperties(int networkType) {
1405 try {
1406 return mService.getLinkPropertiesForType(networkType);
1407 } catch (RemoteException e) {
1408 throw e.rethrowFromSystemServer();
1409 }
1410 }
1411
1412 /**
1413 * Get the {@link LinkProperties} for the given {@link Network}. This
1414 * will return {@code null} if the network is unknown.
1415 *
1416 * @param network The {@link Network} object identifying the network in question.
1417 * @return The {@link LinkProperties} for the network, or {@code null}.
1418 */
1419 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1420 @Nullable
1421 public LinkProperties getLinkProperties(@Nullable Network network) {
1422 try {
1423 return mService.getLinkProperties(network);
1424 } catch (RemoteException e) {
1425 throw e.rethrowFromSystemServer();
1426 }
1427 }
1428
1429 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001430 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001431 * will return {@code null} if the network is unknown.
1432 *
Roshan Piuse08bc182020-12-22 15:10:42 -08001433 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1434 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1435 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1436 * this location sensitive information (subject to app's location permissions) will be
1437 * noted by system. To include any location sensitive data in {@link TransportInfo},
1438 * use a {@link NetworkCallback} with
1439 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1440 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001441 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001442 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001443 */
1444 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1445 @Nullable
1446 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1447 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001448 return mService.getNetworkCapabilities(
1449 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001450 } catch (RemoteException e) {
1451 throw e.rethrowFromSystemServer();
1452 }
1453 }
1454
1455 /**
1456 * Gets a URL that can be used for resolving whether a captive portal is present.
1457 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1458 * portal is present.
1459 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1460 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1461 *
1462 * The system network validation may be using different strategies to detect captive portals,
1463 * so this method does not necessarily return a URL used by the system. It only returns a URL
1464 * that may be relevant for other components trying to detect captive portals.
1465 *
1466 * @hide
1467 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1468 * system.
1469 */
1470 @Deprecated
1471 @SystemApi
1472 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1473 public String getCaptivePortalServerUrl() {
1474 try {
1475 return mService.getCaptivePortalServerUrl();
1476 } catch (RemoteException e) {
1477 throw e.rethrowFromSystemServer();
1478 }
1479 }
1480
1481 /**
1482 * Tells the underlying networking system that the caller wants to
1483 * begin using the named feature. The interpretation of {@code feature}
1484 * is completely up to each networking implementation.
1485 *
1486 * <p>This method requires the caller to hold either the
1487 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1488 * or the ability to modify system settings as determined by
1489 * {@link android.provider.Settings.System#canWrite}.</p>
1490 *
1491 * @param networkType specifies which network the request pertains to
1492 * @param feature the name of the feature to be used
1493 * @return an integer value representing the outcome of the request.
1494 * The interpretation of this value is specific to each networking
1495 * implementation+feature combination, except that the value {@code -1}
1496 * always indicates failure.
1497 *
1498 * @deprecated Deprecated in favor of the cleaner
1499 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1500 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1501 * throw {@code UnsupportedOperationException} if called.
1502 * @removed
1503 */
1504 @Deprecated
1505 public int startUsingNetworkFeature(int networkType, String feature) {
1506 checkLegacyRoutingApiAccess();
1507 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1508 if (netCap == null) {
1509 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1510 feature);
1511 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1512 }
1513
1514 NetworkRequest request = null;
1515 synchronized (sLegacyRequests) {
1516 LegacyRequest l = sLegacyRequests.get(netCap);
1517 if (l != null) {
1518 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1519 renewRequestLocked(l);
1520 if (l.currentNetwork != null) {
1521 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1522 } else {
1523 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1524 }
1525 }
1526
1527 request = requestNetworkForFeatureLocked(netCap);
1528 }
1529 if (request != null) {
1530 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1531 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1532 } else {
1533 Log.d(TAG, " request Failed");
1534 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1535 }
1536 }
1537
1538 /**
1539 * Tells the underlying networking system that the caller is finished
1540 * using the named feature. The interpretation of {@code feature}
1541 * is completely up to each networking implementation.
1542 *
1543 * <p>This method requires the caller to hold either the
1544 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1545 * or the ability to modify system settings as determined by
1546 * {@link android.provider.Settings.System#canWrite}.</p>
1547 *
1548 * @param networkType specifies which network the request pertains to
1549 * @param feature the name of the feature that is no longer needed
1550 * @return an integer value representing the outcome of the request.
1551 * The interpretation of this value is specific to each networking
1552 * implementation+feature combination, except that the value {@code -1}
1553 * always indicates failure.
1554 *
1555 * @deprecated Deprecated in favor of the cleaner
1556 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1557 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1558 * throw {@code UnsupportedOperationException} if called.
1559 * @removed
1560 */
1561 @Deprecated
1562 public int stopUsingNetworkFeature(int networkType, String feature) {
1563 checkLegacyRoutingApiAccess();
1564 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1565 if (netCap == null) {
1566 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1567 feature);
1568 return -1;
1569 }
1570
1571 if (removeRequestForFeature(netCap)) {
1572 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1573 }
1574 return 1;
1575 }
1576
1577 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1578 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1579 if (networkType == TYPE_MOBILE) {
1580 switch (feature) {
1581 case "enableCBS":
1582 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1583 case "enableDUN":
1584 case "enableDUNAlways":
1585 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1586 case "enableFOTA":
1587 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1588 case "enableHIPRI":
1589 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1590 case "enableIMS":
1591 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1592 case "enableMMS":
1593 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1594 case "enableSUPL":
1595 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1596 default:
1597 return null;
1598 }
1599 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1600 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1601 }
1602 return null;
1603 }
1604
1605 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1606 if (netCap == null) return TYPE_NONE;
1607 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1608 return TYPE_MOBILE_CBS;
1609 }
1610 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1611 return TYPE_MOBILE_IMS;
1612 }
1613 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1614 return TYPE_MOBILE_FOTA;
1615 }
1616 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1617 return TYPE_MOBILE_DUN;
1618 }
1619 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1620 return TYPE_MOBILE_SUPL;
1621 }
1622 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1623 return TYPE_MOBILE_MMS;
1624 }
1625 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1626 return TYPE_MOBILE_HIPRI;
1627 }
1628 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1629 return TYPE_WIFI_P2P;
1630 }
1631 return TYPE_NONE;
1632 }
1633
1634 private static class LegacyRequest {
1635 NetworkCapabilities networkCapabilities;
1636 NetworkRequest networkRequest;
1637 int expireSequenceNumber;
1638 Network currentNetwork;
1639 int delay = -1;
1640
1641 private void clearDnsBinding() {
1642 if (currentNetwork != null) {
1643 currentNetwork = null;
1644 setProcessDefaultNetworkForHostResolution(null);
1645 }
1646 }
1647
1648 NetworkCallback networkCallback = new NetworkCallback() {
1649 @Override
1650 public void onAvailable(Network network) {
1651 currentNetwork = network;
1652 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1653 setProcessDefaultNetworkForHostResolution(network);
1654 }
1655 @Override
1656 public void onLost(Network network) {
1657 if (network.equals(currentNetwork)) clearDnsBinding();
1658 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1659 }
1660 };
1661 }
1662
1663 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1664 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1665 new HashMap<>();
1666
1667 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1668 synchronized (sLegacyRequests) {
1669 LegacyRequest l = sLegacyRequests.get(netCap);
1670 if (l != null) return l.networkRequest;
1671 }
1672 return null;
1673 }
1674
1675 private void renewRequestLocked(LegacyRequest l) {
1676 l.expireSequenceNumber++;
1677 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1678 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1679 }
1680
1681 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1682 int ourSeqNum = -1;
1683 synchronized (sLegacyRequests) {
1684 LegacyRequest l = sLegacyRequests.get(netCap);
1685 if (l == null) return;
1686 ourSeqNum = l.expireSequenceNumber;
1687 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
1688 }
1689 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1690 }
1691
1692 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1693 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1694 int delay = -1;
1695 int type = legacyTypeForNetworkCapabilities(netCap);
1696 try {
1697 delay = mService.getRestoreDefaultNetworkDelay(type);
1698 } catch (RemoteException e) {
1699 throw e.rethrowFromSystemServer();
1700 }
1701 LegacyRequest l = new LegacyRequest();
1702 l.networkCapabilities = netCap;
1703 l.delay = delay;
1704 l.expireSequenceNumber = 0;
1705 l.networkRequest = sendRequestForNetwork(
1706 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
1707 if (l.networkRequest == null) return null;
1708 sLegacyRequests.put(netCap, l);
1709 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1710 return l.networkRequest;
1711 }
1712
1713 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1714 if (delay >= 0) {
1715 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
1716 CallbackHandler handler = getDefaultHandler();
1717 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1718 handler.sendMessageDelayed(msg, delay);
1719 }
1720 }
1721
1722 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1723 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1724 final LegacyRequest l;
1725 synchronized (sLegacyRequests) {
1726 l = sLegacyRequests.remove(netCap);
1727 }
1728 if (l == null) return false;
1729 unregisterNetworkCallback(l.networkCallback);
1730 l.clearDnsBinding();
1731 return true;
1732 }
1733
1734 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1735 static {
1736 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1737 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1738 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1739 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1740 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1741 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1742 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1743 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1744 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1745 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1746 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1747 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1748 }
1749
1750 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1751 static {
1752 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1753 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1754 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1755 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1756 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1757 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1758 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1759 }
1760
1761 /**
1762 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1763 * instance suitable for registering a request or callback. Throws an
1764 * IllegalArgumentException if no mapping from the legacy type to
1765 * NetworkCapabilities is known.
1766 *
1767 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1768 * to find the network instead.
1769 * @hide
1770 */
1771 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1772 final NetworkCapabilities nc = new NetworkCapabilities();
1773
1774 // Map from type to transports.
1775 final int NOT_FOUND = -1;
1776 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00001777 if (transport == NOT_FOUND) {
1778 throw new IllegalArgumentException("unknown legacy type: " + type);
1779 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001780 nc.addTransportType(transport);
1781
1782 // Map from type to capabilities.
1783 nc.addCapability(sLegacyTypeToCapability.get(
1784 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1785 nc.maybeMarkCapabilitiesRestricted();
1786 return nc;
1787 }
1788
1789 /** @hide */
1790 public static class PacketKeepaliveCallback {
1791 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1792 public PacketKeepaliveCallback() {
1793 }
1794 /** The requested keepalive was successfully started. */
1795 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1796 public void onStarted() {}
1797 /** The keepalive was successfully stopped. */
1798 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1799 public void onStopped() {}
1800 /** An error occurred. */
1801 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1802 public void onError(int error) {}
1803 }
1804
1805 /**
1806 * Allows applications to request that the system periodically send specific packets on their
1807 * behalf, using hardware offload to save battery power.
1808 *
1809 * To request that the system send keepalives, call one of the methods that return a
1810 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1811 * passing in a non-null callback. If the callback is successfully started, the callback's
1812 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1813 * specifying one of the {@code ERROR_*} constants in this class.
1814 *
1815 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1816 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1817 * {@link PacketKeepaliveCallback#onError} if an error occurred.
1818 *
1819 * @deprecated Use {@link SocketKeepalive} instead.
1820 *
1821 * @hide
1822 */
1823 public class PacketKeepalive {
1824
1825 private static final String TAG = "PacketKeepalive";
1826
1827 /** @hide */
1828 public static final int SUCCESS = 0;
1829
1830 /** @hide */
1831 public static final int NO_KEEPALIVE = -1;
1832
1833 /** @hide */
1834 public static final int BINDER_DIED = -10;
1835
1836 /** The specified {@code Network} is not connected. */
1837 public static final int ERROR_INVALID_NETWORK = -20;
1838 /** The specified IP addresses are invalid. For example, the specified source IP address is
1839 * not configured on the specified {@code Network}. */
1840 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1841 /** The requested port is invalid. */
1842 public static final int ERROR_INVALID_PORT = -22;
1843 /** The packet length is invalid (e.g., too long). */
1844 public static final int ERROR_INVALID_LENGTH = -23;
1845 /** The packet transmission interval is invalid (e.g., too short). */
1846 public static final int ERROR_INVALID_INTERVAL = -24;
1847
1848 /** The hardware does not support this request. */
1849 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
1850 /** The hardware returned an error. */
1851 public static final int ERROR_HARDWARE_ERROR = -31;
1852
1853 /** The NAT-T destination port for IPsec */
1854 public static final int NATT_PORT = 4500;
1855
1856 /** The minimum interval in seconds between keepalive packet transmissions */
1857 public static final int MIN_INTERVAL = 10;
1858
1859 private final Network mNetwork;
1860 private final ISocketKeepaliveCallback mCallback;
1861 private final ExecutorService mExecutor;
1862
1863 private volatile Integer mSlot;
1864
1865 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1866 public void stop() {
1867 try {
1868 mExecutor.execute(() -> {
1869 try {
1870 if (mSlot != null) {
1871 mService.stopKeepalive(mNetwork, mSlot);
1872 }
1873 } catch (RemoteException e) {
1874 Log.e(TAG, "Error stopping packet keepalive: ", e);
1875 throw e.rethrowFromSystemServer();
1876 }
1877 });
1878 } catch (RejectedExecutionException e) {
1879 // The internal executor has already stopped due to previous event.
1880 }
1881 }
1882
1883 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00001884 Objects.requireNonNull(network, "network cannot be null");
1885 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001886 mNetwork = network;
1887 mExecutor = Executors.newSingleThreadExecutor();
1888 mCallback = new ISocketKeepaliveCallback.Stub() {
1889 @Override
1890 public void onStarted(int slot) {
1891 final long token = Binder.clearCallingIdentity();
1892 try {
1893 mExecutor.execute(() -> {
1894 mSlot = slot;
1895 callback.onStarted();
1896 });
1897 } finally {
1898 Binder.restoreCallingIdentity(token);
1899 }
1900 }
1901
1902 @Override
1903 public void onStopped() {
1904 final long token = Binder.clearCallingIdentity();
1905 try {
1906 mExecutor.execute(() -> {
1907 mSlot = null;
1908 callback.onStopped();
1909 });
1910 } finally {
1911 Binder.restoreCallingIdentity(token);
1912 }
1913 mExecutor.shutdown();
1914 }
1915
1916 @Override
1917 public void onError(int error) {
1918 final long token = Binder.clearCallingIdentity();
1919 try {
1920 mExecutor.execute(() -> {
1921 mSlot = null;
1922 callback.onError(error);
1923 });
1924 } finally {
1925 Binder.restoreCallingIdentity(token);
1926 }
1927 mExecutor.shutdown();
1928 }
1929
1930 @Override
1931 public void onDataReceived() {
1932 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1933 // this callback when data is received.
1934 }
1935 };
1936 }
1937 }
1938
1939 /**
1940 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1941 *
1942 * @deprecated Use {@link #createSocketKeepalive} instead.
1943 *
1944 * @hide
1945 */
1946 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1947 public PacketKeepalive startNattKeepalive(
1948 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1949 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1950 final PacketKeepalive k = new PacketKeepalive(network, callback);
1951 try {
1952 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
1953 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1954 } catch (RemoteException e) {
1955 Log.e(TAG, "Error starting packet keepalive: ", e);
1956 throw e.rethrowFromSystemServer();
1957 }
1958 return k;
1959 }
1960
1961 // Construct an invalid fd.
1962 private ParcelFileDescriptor createInvalidFd() {
1963 final int invalidFd = -1;
1964 return ParcelFileDescriptor.adoptFd(invalidFd);
1965 }
1966
1967 /**
1968 * Request that keepalives be started on a IPsec NAT-T socket.
1969 *
1970 * @param network The {@link Network} the socket is on.
1971 * @param socket The socket that needs to be kept alive.
1972 * @param source The source address of the {@link UdpEncapsulationSocket}.
1973 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1974 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1975 * must run callback sequentially, otherwise the order of callbacks cannot be
1976 * guaranteed.
1977 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1978 * changes. Must be extended by applications that use this API.
1979 *
1980 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1981 * given socket.
1982 **/
1983 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
1984 @NonNull UdpEncapsulationSocket socket,
1985 @NonNull InetAddress source,
1986 @NonNull InetAddress destination,
1987 @NonNull @CallbackExecutor Executor executor,
1988 @NonNull Callback callback) {
1989 ParcelFileDescriptor dup;
1990 try {
1991 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1992 // which cannot be obtained by the app process.
1993 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1994 } catch (IOException ignored) {
1995 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1996 // ERROR_INVALID_SOCKET.
1997 dup = createInvalidFd();
1998 }
1999 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2000 destination, executor, callback);
2001 }
2002
2003 /**
2004 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2005 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2006 *
2007 * @param network The {@link Network} the socket is on.
2008 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2009 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2010 * from that port.
2011 * @param source The source address of the {@link UdpEncapsulationSocket}.
2012 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2013 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2014 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2015 * must run callback sequentially, otherwise the order of callbacks cannot be
2016 * guaranteed.
2017 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2018 * changes. Must be extended by applications that use this API.
2019 *
2020 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2021 * given socket.
2022 * @hide
2023 */
2024 @SystemApi
2025 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2026 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2027 @NonNull ParcelFileDescriptor pfd,
2028 @NonNull InetAddress source,
2029 @NonNull InetAddress destination,
2030 @NonNull @CallbackExecutor Executor executor,
2031 @NonNull Callback callback) {
2032 ParcelFileDescriptor dup;
2033 try {
2034 // TODO: Consider remove unnecessary dup.
2035 dup = pfd.dup();
2036 } catch (IOException ignored) {
2037 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2038 // ERROR_INVALID_SOCKET.
2039 dup = createInvalidFd();
2040 }
2041 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002042 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002043 }
2044
2045 /**
2046 * Request that keepalives be started on a TCP socket.
2047 * The socket must be established.
2048 *
2049 * @param network The {@link Network} the socket is on.
2050 * @param socket The socket that needs to be kept alive.
2051 * @param executor The executor on which callback will be invoked. This implementation assumes
2052 * the provided {@link Executor} runs the callbacks in sequence with no
2053 * concurrency. Failing this, no guarantee of correctness can be made. It is
2054 * the responsibility of the caller to ensure the executor provides this
2055 * guarantee. A simple way of creating such an executor is with the standard
2056 * tool {@code Executors.newSingleThreadExecutor}.
2057 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2058 * changes. Must be extended by applications that use this API.
2059 *
2060 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2061 * given socket.
2062 * @hide
2063 */
2064 @SystemApi
2065 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2066 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2067 @NonNull Socket socket,
2068 @NonNull Executor executor,
2069 @NonNull Callback callback) {
2070 ParcelFileDescriptor dup;
2071 try {
2072 dup = ParcelFileDescriptor.fromSocket(socket);
2073 } catch (UncheckedIOException ignored) {
2074 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2075 // ERROR_INVALID_SOCKET.
2076 dup = createInvalidFd();
2077 }
2078 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2079 }
2080
2081 /**
2082 * Ensure that a network route exists to deliver traffic to the specified
2083 * host via the specified network interface. An attempt to add a route that
2084 * already exists is ignored, but treated as successful.
2085 *
2086 * <p>This method requires the caller to hold either the
2087 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2088 * or the ability to modify system settings as determined by
2089 * {@link android.provider.Settings.System#canWrite}.</p>
2090 *
2091 * @param networkType the type of the network over which traffic to the specified
2092 * host is to be routed
2093 * @param hostAddress the IP address of the host to which the route is desired
2094 * @return {@code true} on success, {@code false} on failure
2095 *
2096 * @deprecated Deprecated in favor of the
2097 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2098 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2099 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2100 * throw {@code UnsupportedOperationException} if called.
2101 * @removed
2102 */
2103 @Deprecated
2104 public boolean requestRouteToHost(int networkType, int hostAddress) {
2105 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2106 }
2107
2108 /**
2109 * Ensure that a network route exists to deliver traffic to the specified
2110 * host via the specified network interface. An attempt to add a route that
2111 * already exists is ignored, but treated as successful.
2112 *
2113 * <p>This method requires the caller to hold either the
2114 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2115 * or the ability to modify system settings as determined by
2116 * {@link android.provider.Settings.System#canWrite}.</p>
2117 *
2118 * @param networkType the type of the network over which traffic to the specified
2119 * host is to be routed
2120 * @param hostAddress the IP address of the host to which the route is desired
2121 * @return {@code true} on success, {@code false} on failure
2122 * @hide
2123 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2124 * {@link #bindProcessToNetwork} API.
2125 */
2126 @Deprecated
2127 @UnsupportedAppUsage
lucaslin29278ee2021-03-22 11:51:27 +08002128 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002129 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2130 checkLegacyRoutingApiAccess();
2131 try {
2132 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2133 mContext.getOpPackageName(), getAttributionTag());
2134 } catch (RemoteException e) {
2135 throw e.rethrowFromSystemServer();
2136 }
2137 }
2138
2139 /**
2140 * @return the context's attribution tag
2141 */
2142 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2143 private @Nullable String getAttributionTag() {
Roshan Piusa8a477b2020-12-17 14:53:09 -08002144 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002145 }
2146
2147 /**
2148 * Returns the value of the setting for background data usage. If false,
2149 * applications should not use the network if the application is not in the
2150 * foreground. Developers should respect this setting, and check the value
2151 * of this before performing any background data operations.
2152 * <p>
2153 * All applications that have background services that use the network
2154 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2155 * <p>
2156 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2157 * background data depends on several combined factors, and this method will
2158 * always return {@code true}. Instead, when background data is unavailable,
2159 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2160 *
2161 * @return Whether background data usage is allowed.
2162 */
2163 @Deprecated
2164 public boolean getBackgroundDataSetting() {
2165 // assume that background data is allowed; final authority is
2166 // NetworkInfo which may be blocked.
2167 return true;
2168 }
2169
2170 /**
2171 * Sets the value of the setting for background data usage.
2172 *
2173 * @param allowBackgroundData Whether an application should use data while
2174 * it is in the background.
2175 *
2176 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2177 * @see #getBackgroundDataSetting()
2178 * @hide
2179 */
2180 @Deprecated
2181 @UnsupportedAppUsage
2182 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2183 // ignored
2184 }
2185
2186 /**
2187 * @hide
2188 * @deprecated Talk to TelephonyManager directly
2189 */
2190 @Deprecated
2191 @UnsupportedAppUsage
2192 public boolean getMobileDataEnabled() {
2193 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2194 if (tm != null) {
2195 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2196 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2197 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2198 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2199 + " retVal=" + retVal);
2200 return retVal;
2201 }
2202 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2203 return false;
2204 }
2205
2206 /**
2207 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2208 * to find out when the system default network has gone in to a high power state.
2209 */
2210 public interface OnNetworkActiveListener {
2211 /**
2212 * Called on the main thread of the process to report that the current data network
2213 * has become active, and it is now a good time to perform any pending network
2214 * operations. Note that this listener only tells you when the network becomes
2215 * active; if at any other time you want to know whether it is active (and thus okay
2216 * to initiate network traffic), you can retrieve its instantaneous state with
2217 * {@link ConnectivityManager#isDefaultNetworkActive}.
2218 */
2219 void onNetworkActive();
2220 }
2221
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002222 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2223 mNetworkActivityListeners = new ArrayMap<>();
2224
2225 /**
2226 * Start listening to reports when the system's default data network is active, meaning it is
2227 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2228 * to determine the current state of the system's default network after registering the
2229 * listener.
2230 * <p>
2231 * If the process default network has been set with
2232 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2233 * reflect the process's default, but the system default.
2234 *
2235 * @param l The listener to be told when the network is active.
2236 */
2237 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
2238 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2239 @Override
2240 public void onNetworkActive() throws RemoteException {
2241 l.onNetworkActive();
2242 }
2243 };
2244
2245 try {
lucaslin709eb842021-01-21 02:04:15 +08002246 mService.registerNetworkActivityListener(rl);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002247 mNetworkActivityListeners.put(l, rl);
2248 } catch (RemoteException e) {
2249 throw e.rethrowFromSystemServer();
2250 }
2251 }
2252
2253 /**
2254 * Remove network active listener previously registered with
2255 * {@link #addDefaultNetworkActiveListener}.
2256 *
2257 * @param l Previously registered listener.
2258 */
2259 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
2260 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002261 if (rl == null) {
2262 throw new IllegalArgumentException("Listener was not registered.");
2263 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002264 try {
lucaslin709eb842021-01-21 02:04:15 +08002265 mService.registerNetworkActivityListener(rl);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002266 } catch (RemoteException e) {
2267 throw e.rethrowFromSystemServer();
2268 }
2269 }
2270
2271 /**
2272 * Return whether the data network is currently active. An active network means that
2273 * it is currently in a high power state for performing data transmission. On some
2274 * types of networks, it may be expensive to move and stay in such a state, so it is
2275 * more power efficient to batch network traffic together when the radio is already in
2276 * this state. This method tells you whether right now is currently a good time to
2277 * initiate network traffic, as the network is already active.
2278 */
2279 public boolean isDefaultNetworkActive() {
2280 try {
lucaslin709eb842021-01-21 02:04:15 +08002281 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002282 } catch (RemoteException e) {
2283 throw e.rethrowFromSystemServer();
2284 }
2285 }
2286
2287 /**
2288 * {@hide}
2289 */
2290 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002291 mContext = Objects.requireNonNull(context, "missing context");
2292 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002293 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
2294 sInstance = this;
2295 }
2296
2297 /** {@hide} */
2298 @UnsupportedAppUsage
2299 public static ConnectivityManager from(Context context) {
2300 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2301 }
2302
2303 /** @hide */
2304 public NetworkRequest getDefaultRequest() {
2305 try {
2306 // This is not racy as the default request is final in ConnectivityService.
2307 return mService.getDefaultRequest();
2308 } catch (RemoteException e) {
2309 throw e.rethrowFromSystemServer();
2310 }
2311 }
2312
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002313 /**
2314 * Check if the package is a allowed to write settings. This also accounts that such an access
2315 * happened.
2316 *
2317 * @return {@code true} iff the package is allowed to write settings.
2318 */
2319 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2320 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2321 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2322 boolean throwException) {
2323 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2324 throwException);
2325 }
2326
2327 /**
2328 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2329 * situations where a Context pointer is unavailable.
2330 * @hide
2331 */
2332 @Deprecated
2333 static ConnectivityManager getInstanceOrNull() {
2334 return sInstance;
2335 }
2336
2337 /**
2338 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2339 * situations where a Context pointer is unavailable.
2340 * @hide
2341 */
2342 @Deprecated
2343 @UnsupportedAppUsage
2344 private static ConnectivityManager getInstance() {
2345 if (getInstanceOrNull() == null) {
2346 throw new IllegalStateException("No ConnectivityManager yet constructed");
2347 }
2348 return getInstanceOrNull();
2349 }
2350
2351 /**
2352 * Get the set of tetherable, available interfaces. This list is limited by
2353 * device configuration and current interface existence.
2354 *
2355 * @return an array of 0 or more Strings of tetherable interface names.
2356 *
2357 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2358 * {@hide}
2359 */
2360 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2361 @UnsupportedAppUsage
2362 @Deprecated
2363 public String[] getTetherableIfaces() {
2364 return mTetheringManager.getTetherableIfaces();
2365 }
2366
2367 /**
2368 * Get the set of tethered interfaces.
2369 *
2370 * @return an array of 0 or more String of currently tethered interface names.
2371 *
2372 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2373 * {@hide}
2374 */
2375 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2376 @UnsupportedAppUsage
2377 @Deprecated
2378 public String[] getTetheredIfaces() {
2379 return mTetheringManager.getTetheredIfaces();
2380 }
2381
2382 /**
2383 * Get the set of interface names which attempted to tether but
2384 * failed. Re-attempting to tether may cause them to reset to the Tethered
2385 * state. Alternatively, causing the interface to be destroyed and recreated
2386 * may cause them to reset to the available state.
2387 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2388 * information on the cause of the errors.
2389 *
2390 * @return an array of 0 or more String indicating the interface names
2391 * which failed to tether.
2392 *
2393 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2394 * {@hide}
2395 */
2396 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2397 @UnsupportedAppUsage
2398 @Deprecated
2399 public String[] getTetheringErroredIfaces() {
2400 return mTetheringManager.getTetheringErroredIfaces();
2401 }
2402
2403 /**
2404 * Get the set of tethered dhcp ranges.
2405 *
2406 * @deprecated This method is not supported.
2407 * TODO: remove this function when all of clients are removed.
2408 * {@hide}
2409 */
2410 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2411 @Deprecated
2412 public String[] getTetheredDhcpRanges() {
2413 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2414 }
2415
2416 /**
2417 * Attempt to tether the named interface. This will setup a dhcp server
2418 * on the interface, forward and NAT IP packets and forward DNS requests
2419 * to the best active upstream network interface. Note that if no upstream
2420 * IP network interface is available, dhcp will still run and traffic will be
2421 * allowed between the tethered devices and this device, though upstream net
2422 * access will of course fail until an upstream network interface becomes
2423 * active.
2424 *
2425 * <p>This method requires the caller to hold either the
2426 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2427 * or the ability to modify system settings as determined by
2428 * {@link android.provider.Settings.System#canWrite}.</p>
2429 *
2430 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2431 * and WifiStateMachine which need direct access. All other clients should use
2432 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2433 * logic.</p>
2434 *
2435 * @param iface the interface name to tether.
2436 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2437 * @deprecated Use {@link TetheringManager#startTethering} instead
2438 *
2439 * {@hide}
2440 */
2441 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2442 @Deprecated
2443 public int tether(String iface) {
2444 return mTetheringManager.tether(iface);
2445 }
2446
2447 /**
2448 * Stop tethering the named interface.
2449 *
2450 * <p>This method requires the caller to hold either the
2451 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2452 * or the ability to modify system settings as determined by
2453 * {@link android.provider.Settings.System#canWrite}.</p>
2454 *
2455 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2456 * and WifiStateMachine which need direct access. All other clients should use
2457 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2458 * logic.</p>
2459 *
2460 * @param iface the interface name to untether.
2461 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2462 *
2463 * {@hide}
2464 */
2465 @UnsupportedAppUsage
2466 @Deprecated
2467 public int untether(String iface) {
2468 return mTetheringManager.untether(iface);
2469 }
2470
2471 /**
2472 * Check if the device allows for tethering. It may be disabled via
2473 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2474 * due to device configuration.
2475 *
2476 * <p>If this app does not have permission to use this API, it will always
2477 * return false rather than throw an exception.</p>
2478 *
2479 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2480 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2481 *
2482 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2483 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2484 *
2485 * @return a boolean - {@code true} indicating Tethering is supported.
2486 *
2487 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2488 * {@hide}
2489 */
2490 @SystemApi
2491 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2492 android.Manifest.permission.WRITE_SETTINGS})
2493 public boolean isTetheringSupported() {
2494 return mTetheringManager.isTetheringSupported();
2495 }
2496
2497 /**
2498 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2499 *
2500 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2501 * @hide
2502 */
2503 @SystemApi
2504 @Deprecated
2505 public static abstract class OnStartTetheringCallback {
2506 /**
2507 * Called when tethering has been successfully started.
2508 */
2509 public void onTetheringStarted() {}
2510
2511 /**
2512 * Called when starting tethering failed.
2513 */
2514 public void onTetheringFailed() {}
2515 }
2516
2517 /**
2518 * Convenient overload for
2519 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2520 * handler to run on the current thread's {@link Looper}.
2521 *
2522 * @deprecated Use {@link TetheringManager#startTethering} instead.
2523 * @hide
2524 */
2525 @SystemApi
2526 @Deprecated
2527 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2528 public void startTethering(int type, boolean showProvisioningUi,
2529 final OnStartTetheringCallback callback) {
2530 startTethering(type, showProvisioningUi, callback, null);
2531 }
2532
2533 /**
2534 * Runs tether provisioning for the given type if needed and then starts tethering if
2535 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2536 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2537 * schedules tether provisioning re-checks if appropriate.
2538 *
2539 * @param type The type of tethering to start. Must be one of
2540 * {@link ConnectivityManager.TETHERING_WIFI},
2541 * {@link ConnectivityManager.TETHERING_USB}, or
2542 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2543 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2544 * is one. This should be true the first time this function is called and also any time
2545 * the user can see this UI. It gives users information from their carrier about the
2546 * check failing and how they can sign up for tethering if possible.
2547 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2548 * of the result of trying to tether.
2549 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2550 *
2551 * @deprecated Use {@link TetheringManager#startTethering} instead.
2552 * @hide
2553 */
2554 @SystemApi
2555 @Deprecated
2556 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2557 public void startTethering(int type, boolean showProvisioningUi,
2558 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002559 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002560
2561 final Executor executor = new Executor() {
2562 @Override
2563 public void execute(Runnable command) {
2564 if (handler == null) {
2565 command.run();
2566 } else {
2567 handler.post(command);
2568 }
2569 }
2570 };
2571
2572 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2573 @Override
2574 public void onTetheringStarted() {
2575 callback.onTetheringStarted();
2576 }
2577
2578 @Override
2579 public void onTetheringFailed(final int error) {
2580 callback.onTetheringFailed();
2581 }
2582 };
2583
2584 final TetheringRequest request = new TetheringRequest.Builder(type)
2585 .setShouldShowEntitlementUi(showProvisioningUi).build();
2586
2587 mTetheringManager.startTethering(request, executor, tetheringCallback);
2588 }
2589
2590 /**
2591 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2592 * applicable.
2593 *
2594 * @param type The type of tethering to stop. Must be one of
2595 * {@link ConnectivityManager.TETHERING_WIFI},
2596 * {@link ConnectivityManager.TETHERING_USB}, or
2597 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2598 *
2599 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2600 * @hide
2601 */
2602 @SystemApi
2603 @Deprecated
2604 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2605 public void stopTethering(int type) {
2606 mTetheringManager.stopTethering(type);
2607 }
2608
2609 /**
2610 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2611 * upstream status.
2612 *
2613 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2614 * @hide
2615 */
2616 @SystemApi
2617 @Deprecated
2618 public abstract static class OnTetheringEventCallback {
2619
2620 /**
2621 * Called when tethering upstream changed. This can be called multiple times and can be
2622 * called any time.
2623 *
2624 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2625 * have any upstream.
2626 */
2627 public void onUpstreamChanged(@Nullable Network network) {}
2628 }
2629
2630 @GuardedBy("mTetheringEventCallbacks")
2631 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2632 mTetheringEventCallbacks = new ArrayMap<>();
2633
2634 /**
2635 * Start listening to tethering change events. Any new added callback will receive the last
2636 * tethering status right away. If callback is registered when tethering has no upstream or
2637 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2638 * with a null argument. The same callback object cannot be registered twice.
2639 *
2640 * @param executor the executor on which callback will be invoked.
2641 * @param callback the callback to be called when tethering has change events.
2642 *
2643 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2644 * @hide
2645 */
2646 @SystemApi
2647 @Deprecated
2648 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2649 public void registerTetheringEventCallback(
2650 @NonNull @CallbackExecutor Executor executor,
2651 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002652 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002653
2654 final TetheringEventCallback tetherCallback =
2655 new TetheringEventCallback() {
2656 @Override
2657 public void onUpstreamChanged(@Nullable Network network) {
2658 callback.onUpstreamChanged(network);
2659 }
2660 };
2661
2662 synchronized (mTetheringEventCallbacks) {
2663 mTetheringEventCallbacks.put(callback, tetherCallback);
2664 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
2665 }
2666 }
2667
2668 /**
2669 * Remove tethering event callback previously registered with
2670 * {@link #registerTetheringEventCallback}.
2671 *
2672 * @param callback previously registered callback.
2673 *
2674 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
2675 * @hide
2676 */
2677 @SystemApi
2678 @Deprecated
2679 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2680 public void unregisterTetheringEventCallback(
2681 @NonNull final OnTetheringEventCallback callback) {
2682 Objects.requireNonNull(callback, "The callback must be non-null");
2683 synchronized (mTetheringEventCallbacks) {
2684 final TetheringEventCallback tetherCallback =
2685 mTetheringEventCallbacks.remove(callback);
2686 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
2687 }
2688 }
2689
2690
2691 /**
2692 * Get the list of regular expressions that define any tetherable
2693 * USB network interfaces. If USB tethering is not supported by the
2694 * device, this list should be empty.
2695 *
2696 * @return an array of 0 or more regular expression Strings defining
2697 * what interfaces are considered tetherable usb interfaces.
2698 *
2699 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2700 * {@hide}
2701 */
2702 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2703 @UnsupportedAppUsage
2704 @Deprecated
2705 public String[] getTetherableUsbRegexs() {
2706 return mTetheringManager.getTetherableUsbRegexs();
2707 }
2708
2709 /**
2710 * Get the list of regular expressions that define any tetherable
2711 * Wifi network interfaces. If Wifi tethering is not supported by the
2712 * device, this list should be empty.
2713 *
2714 * @return an array of 0 or more regular expression Strings defining
2715 * what interfaces are considered tetherable wifi interfaces.
2716 *
2717 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2718 * {@hide}
2719 */
2720 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2721 @UnsupportedAppUsage
2722 @Deprecated
2723 public String[] getTetherableWifiRegexs() {
2724 return mTetheringManager.getTetherableWifiRegexs();
2725 }
2726
2727 /**
2728 * Get the list of regular expressions that define any tetherable
2729 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2730 * device, this list should be empty.
2731 *
2732 * @return an array of 0 or more regular expression Strings defining
2733 * what interfaces are considered tetherable bluetooth interfaces.
2734 *
2735 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2736 *TetheringManager.TetheringInterfaceRegexps)} instead.
2737 * {@hide}
2738 */
2739 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2740 @UnsupportedAppUsage
2741 @Deprecated
2742 public String[] getTetherableBluetoothRegexs() {
2743 return mTetheringManager.getTetherableBluetoothRegexs();
2744 }
2745
2746 /**
2747 * Attempt to both alter the mode of USB and Tethering of USB. A
2748 * utility method to deal with some of the complexity of USB - will
2749 * attempt to switch to Rndis and subsequently tether the resulting
2750 * interface on {@code true} or turn off tethering and switch off
2751 * Rndis on {@code false}.
2752 *
2753 * <p>This method requires the caller to hold either the
2754 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2755 * or the ability to modify system settings as determined by
2756 * {@link android.provider.Settings.System#canWrite}.</p>
2757 *
2758 * @param enable a boolean - {@code true} to enable tethering
2759 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2760 * @deprecated Use {@link TetheringManager#startTethering} instead
2761 *
2762 * {@hide}
2763 */
2764 @UnsupportedAppUsage
2765 @Deprecated
2766 public int setUsbTethering(boolean enable) {
2767 return mTetheringManager.setUsbTethering(enable);
2768 }
2769
2770 /**
2771 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2772 * {@hide}
2773 */
2774 @SystemApi
2775 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002776 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002777 /**
2778 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2779 * {@hide}
2780 */
2781 @Deprecated
2782 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2783 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2784 /**
2785 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2786 * {@hide}
2787 */
2788 @Deprecated
2789 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2790 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2791 /**
2792 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2793 * {@hide}
2794 */
2795 @Deprecated
2796 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2797 /**
2798 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2799 * {@hide}
2800 */
2801 @Deprecated
2802 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2803 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2804 /**
2805 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
2806 * {@hide}
2807 */
2808 @Deprecated
2809 public static final int TETHER_ERROR_MASTER_ERROR =
2810 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
2811 /**
2812 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2813 * {@hide}
2814 */
2815 @Deprecated
2816 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2817 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2818 /**
2819 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2820 * {@hide}
2821 */
2822 @Deprecated
2823 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2824 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2825 /**
2826 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
2827 * {@hide}
2828 */
2829 @Deprecated
2830 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
2831 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
2832 /**
2833 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
2834 * {@hide}
2835 */
2836 @Deprecated
2837 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
2838 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
2839 /**
2840 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2841 * {@hide}
2842 */
2843 @Deprecated
2844 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2845 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2846 /**
2847 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
2848 * {@hide}
2849 */
2850 @SystemApi
2851 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002852 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002853 /**
2854 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2855 * {@hide}
2856 */
2857 @Deprecated
2858 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2859 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2860 /**
2861 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2862 * {@hide}
2863 */
2864 @SystemApi
2865 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002866 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002867
2868 /**
2869 * Get a more detailed error code after a Tethering or Untethering
2870 * request asynchronously failed.
2871 *
2872 * @param iface The name of the interface of interest
2873 * @return error The error code of the last error tethering or untethering the named
2874 * interface
2875 *
2876 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2877 * {@hide}
2878 */
2879 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2880 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2881 @Deprecated
2882 public int getLastTetherError(String iface) {
2883 int error = mTetheringManager.getLastTetherError(iface);
2884 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2885 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2886 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2887 // instead.
2888 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2889 }
2890 return error;
2891 }
2892
2893 /** @hide */
2894 @Retention(RetentionPolicy.SOURCE)
2895 @IntDef(value = {
2896 TETHER_ERROR_NO_ERROR,
2897 TETHER_ERROR_PROVISION_FAILED,
2898 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2899 })
2900 public @interface EntitlementResultCode {
2901 }
2902
2903 /**
2904 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
2905 * entitlement succeeded.
2906 *
2907 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
2908 * @hide
2909 */
2910 @SystemApi
2911 @Deprecated
2912 public interface OnTetheringEntitlementResultListener {
2913 /**
2914 * Called to notify entitlement result.
2915 *
2916 * @param resultCode an int value of entitlement result. It may be one of
2917 * {@link #TETHER_ERROR_NO_ERROR},
2918 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2919 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2920 */
2921 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
2922 }
2923
2924 /**
2925 * Get the last value of the entitlement check on this downstream. If the cached value is
2926 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2927 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2928 * guaranteed that the UI-based entitlement check will complete in any specific time period
2929 * and may in fact never complete. Any successful entitlement check the platform performs for
2930 * any reason will update the cached value.
2931 *
2932 * @param type the downstream type of tethering. Must be one of
2933 * {@link #TETHERING_WIFI},
2934 * {@link #TETHERING_USB}, or
2935 * {@link #TETHERING_BLUETOOTH}.
2936 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
2937 * @param executor the executor on which callback will be invoked.
2938 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2939 * notify the caller of the result of entitlement check. The listener may be called zero
2940 * or one time.
2941 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
2942 * {@hide}
2943 */
2944 @SystemApi
2945 @Deprecated
2946 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2947 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2948 @NonNull @CallbackExecutor Executor executor,
2949 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002950 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002951 ResultReceiver wrappedListener = new ResultReceiver(null) {
2952 @Override
2953 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08002954 final long token = Binder.clearCallingIdentity();
2955 try {
2956 executor.execute(() -> {
2957 listener.onTetheringEntitlementResult(resultCode);
2958 });
2959 } finally {
2960 Binder.restoreCallingIdentity(token);
2961 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002962 }
2963 };
2964
2965 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
2966 showEntitlementUi);
2967 }
2968
2969 /**
2970 * Report network connectivity status. This is currently used only
2971 * to alter status bar UI.
2972 * <p>This method requires the caller to hold the permission
2973 * {@link android.Manifest.permission#STATUS_BAR}.
2974 *
2975 * @param networkType The type of network you want to report on
2976 * @param percentage The quality of the connection 0 is bad, 100 is good
2977 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
2978 * {@hide}
2979 */
2980 public void reportInetCondition(int networkType, int percentage) {
2981 printStackTrace();
2982 try {
2983 mService.reportInetCondition(networkType, percentage);
2984 } catch (RemoteException e) {
2985 throw e.rethrowFromSystemServer();
2986 }
2987 }
2988
2989 /**
2990 * Report a problem network to the framework. This provides a hint to the system
2991 * that there might be connectivity problems on this network and may cause
2992 * the framework to re-evaluate network connectivity and/or switch to another
2993 * network.
2994 *
2995 * @param network The {@link Network} the application was attempting to use
2996 * or {@code null} to indicate the current default network.
2997 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2998 * working and non-working connectivity.
2999 */
3000 @Deprecated
3001 public void reportBadNetwork(@Nullable Network network) {
3002 printStackTrace();
3003 try {
3004 // One of these will be ignored because it matches system's current state.
3005 // The other will trigger the necessary reevaluation.
3006 mService.reportNetworkConnectivity(network, true);
3007 mService.reportNetworkConnectivity(network, false);
3008 } catch (RemoteException e) {
3009 throw e.rethrowFromSystemServer();
3010 }
3011 }
3012
3013 /**
3014 * Report to the framework whether a network has working connectivity.
3015 * This provides a hint to the system that a particular network is providing
3016 * working connectivity or not. In response the framework may re-evaluate
3017 * the network's connectivity and might take further action thereafter.
3018 *
3019 * @param network The {@link Network} the application was attempting to use
3020 * or {@code null} to indicate the current default network.
3021 * @param hasConnectivity {@code true} if the application was able to successfully access the
3022 * Internet using {@code network} or {@code false} if not.
3023 */
3024 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3025 printStackTrace();
3026 try {
3027 mService.reportNetworkConnectivity(network, hasConnectivity);
3028 } catch (RemoteException e) {
3029 throw e.rethrowFromSystemServer();
3030 }
3031 }
3032
3033 /**
3034 * Set a network-independent global http proxy. This is not normally what you want
3035 * for typical HTTP proxies - they are general network dependent. However if you're
3036 * doing something unusual like general internal filtering this may be useful. On
3037 * a private network where the proxy is not accessible, you may break HTTP using this.
3038 *
3039 * @param p A {@link ProxyInfo} object defining the new global
3040 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
3041 * @hide
3042 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003043 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003044 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wangf9294e72021-03-18 09:44:34 +08003045 public void setGlobalProxy(@Nullable ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003046 try {
3047 mService.setGlobalProxy(p);
3048 } catch (RemoteException e) {
3049 throw e.rethrowFromSystemServer();
3050 }
3051 }
3052
3053 /**
3054 * Retrieve any network-independent global HTTP proxy.
3055 *
3056 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3057 * if no global HTTP proxy is set.
3058 * @hide
3059 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003060 @SystemApi(client = MODULE_LIBRARIES)
3061 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003062 public ProxyInfo getGlobalProxy() {
3063 try {
3064 return mService.getGlobalProxy();
3065 } catch (RemoteException e) {
3066 throw e.rethrowFromSystemServer();
3067 }
3068 }
3069
3070 /**
3071 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3072 * network-specific HTTP proxy. If {@code network} is null, the
3073 * network-specific proxy returned is the proxy of the default active
3074 * network.
3075 *
3076 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3077 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3078 * or when {@code network} is {@code null},
3079 * the {@code ProxyInfo} for the default active network. Returns
3080 * {@code null} when no proxy applies or the caller doesn't have
3081 * permission to use {@code network}.
3082 * @hide
3083 */
3084 public ProxyInfo getProxyForNetwork(Network network) {
3085 try {
3086 return mService.getProxyForNetwork(network);
3087 } catch (RemoteException e) {
3088 throw e.rethrowFromSystemServer();
3089 }
3090 }
3091
3092 /**
3093 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3094 * otherwise if this process is bound to a {@link Network} using
3095 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3096 * the default network's proxy is returned.
3097 *
3098 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3099 * HTTP proxy is active.
3100 */
3101 @Nullable
3102 public ProxyInfo getDefaultProxy() {
3103 return getProxyForNetwork(getBoundNetworkForProcess());
3104 }
3105
3106 /**
3107 * Returns true if the hardware supports the given network type
3108 * else it returns false. This doesn't indicate we have coverage
3109 * or are authorized onto a network, just whether or not the
3110 * hardware supports it. For example a GSM phone without a SIM
3111 * should still return {@code true} for mobile data, but a wifi only
3112 * tablet would return {@code false}.
3113 *
3114 * @param networkType The network type we'd like to check
3115 * @return {@code true} if supported, else {@code false}
3116 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3117 * @hide
3118 */
3119 @Deprecated
3120 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3121 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3122 public boolean isNetworkSupported(int networkType) {
3123 try {
3124 return mService.isNetworkSupported(networkType);
3125 } catch (RemoteException e) {
3126 throw e.rethrowFromSystemServer();
3127 }
3128 }
3129
3130 /**
3131 * Returns if the currently active data network is metered. A network is
3132 * classified as metered when the user is sensitive to heavy data usage on
3133 * that connection due to monetary costs, data limitations or
3134 * battery/performance issues. You should check this before doing large
3135 * data transfers, and warn the user or delay the operation until another
3136 * network is available.
3137 *
3138 * @return {@code true} if large transfers should be avoided, otherwise
3139 * {@code false}.
3140 */
3141 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3142 public boolean isActiveNetworkMetered() {
3143 try {
3144 return mService.isActiveNetworkMetered();
3145 } catch (RemoteException e) {
3146 throw e.rethrowFromSystemServer();
3147 }
3148 }
3149
3150 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003151 * Set sign in error notification to visible or invisible
3152 *
3153 * @hide
3154 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3155 */
3156 @Deprecated
3157 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3158 String action) {
3159 try {
3160 mService.setProvisioningNotificationVisible(visible, networkType, action);
3161 } catch (RemoteException e) {
3162 throw e.rethrowFromSystemServer();
3163 }
3164 }
3165
3166 /**
3167 * Set the value for enabling/disabling airplane mode
3168 *
3169 * @param enable whether to enable airplane mode or not
3170 *
3171 * @hide
3172 */
3173 @RequiresPermission(anyOf = {
3174 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3175 android.Manifest.permission.NETWORK_SETTINGS,
3176 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3177 android.Manifest.permission.NETWORK_STACK})
3178 @SystemApi
3179 public void setAirplaneMode(boolean enable) {
3180 try {
3181 mService.setAirplaneMode(enable);
3182 } catch (RemoteException e) {
3183 throw e.rethrowFromSystemServer();
3184 }
3185 }
3186
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003187 /**
3188 * Registers the specified {@link NetworkProvider}.
3189 * Each listener must only be registered once. The listener can be unregistered with
3190 * {@link #unregisterNetworkProvider}.
3191 *
3192 * @param provider the provider to register
3193 * @return the ID of the provider. This ID must be used by the provider when registering
3194 * {@link android.net.NetworkAgent}s.
3195 * @hide
3196 */
3197 @SystemApi
3198 @RequiresPermission(anyOf = {
3199 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3200 android.Manifest.permission.NETWORK_FACTORY})
3201 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3202 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3203 throw new IllegalStateException("NetworkProviders can only be registered once");
3204 }
3205
3206 try {
3207 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3208 provider.getName());
3209 provider.setProviderId(providerId);
3210 } catch (RemoteException e) {
3211 throw e.rethrowFromSystemServer();
3212 }
3213 return provider.getProviderId();
3214 }
3215
3216 /**
3217 * Unregisters the specified NetworkProvider.
3218 *
3219 * @param provider the provider to unregister
3220 * @hide
3221 */
3222 @SystemApi
3223 @RequiresPermission(anyOf = {
3224 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3225 android.Manifest.permission.NETWORK_FACTORY})
3226 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3227 try {
3228 mService.unregisterNetworkProvider(provider.getMessenger());
3229 } catch (RemoteException e) {
3230 throw e.rethrowFromSystemServer();
3231 }
3232 provider.setProviderId(NetworkProvider.ID_NONE);
3233 }
3234
3235
3236 /** @hide exposed via the NetworkProvider class. */
3237 @RequiresPermission(anyOf = {
3238 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3239 android.Manifest.permission.NETWORK_FACTORY})
3240 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3241 try {
3242 mService.declareNetworkRequestUnfulfillable(request);
3243 } catch (RemoteException e) {
3244 throw e.rethrowFromSystemServer();
3245 }
3246 }
3247
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003248 /**
3249 * @hide
3250 * Register a NetworkAgent with ConnectivityService.
3251 * @return Network corresponding to NetworkAgent.
3252 */
3253 @RequiresPermission(anyOf = {
3254 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3255 android.Manifest.permission.NETWORK_FACTORY})
3256 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003257 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3258 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003259 try {
3260 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3261 } catch (RemoteException e) {
3262 throw e.rethrowFromSystemServer();
3263 }
3264 }
3265
3266 /**
3267 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3268 * changes. Should be extended by applications wanting notifications.
3269 *
3270 * A {@code NetworkCallback} is registered by calling
3271 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3272 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3273 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3274 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3275 * A {@code NetworkCallback} should be registered at most once at any time.
3276 * A {@code NetworkCallback} that has been unregistered can be registered again.
3277 */
3278 public static class NetworkCallback {
3279 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003280 * No flags associated with this callback.
3281 * @hide
3282 */
3283 public static final int FLAG_NONE = 0;
3284 /**
3285 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3286 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3287 * <p>
3288 * These include:
3289 * <li> Some transport info instances (retrieved via
3290 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3291 * contain location sensitive information.
3292 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3293 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3294 * </p>
3295 * <p>
3296 * Note:
3297 * <li> Retrieving this location sensitive information (subject to app's location
3298 * permissions) will be noted by system. </li>
3299 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3300 * not include location sensitive info.
3301 * </p>
3302 */
3303 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3304
3305 /** @hide */
3306 @Retention(RetentionPolicy.SOURCE)
3307 @IntDef(flag = true, prefix = "FLAG_", value = {
3308 FLAG_NONE,
3309 FLAG_INCLUDE_LOCATION_INFO
3310 })
3311 public @interface Flag { }
3312
3313 /**
3314 * All the valid flags for error checking.
3315 */
3316 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3317
3318 public NetworkCallback() {
3319 this(FLAG_NONE);
3320 }
3321
3322 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003323 if ((flags & VALID_FLAGS) != flags) {
3324 throw new IllegalArgumentException("Invalid flags");
3325 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003326 mFlags = flags;
3327 }
3328
3329 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003330 * Called when the framework connects to a new network to evaluate whether it satisfies this
3331 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3332 * callback. There is no guarantee that this new network will satisfy any requests, or that
3333 * the network will stay connected for longer than the time necessary to evaluate it.
3334 * <p>
3335 * Most applications <b>should not</b> act on this callback, and should instead use
3336 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3337 * the framework in properly evaluating the network &mdash; for example, an application that
3338 * can automatically log in to a captive portal without user intervention.
3339 *
3340 * @param network The {@link Network} of the network that is being evaluated.
3341 *
3342 * @hide
3343 */
3344 public void onPreCheck(@NonNull Network network) {}
3345
3346 /**
3347 * Called when the framework connects and has declared a new network ready for use.
3348 * This callback may be called more than once if the {@link Network} that is
3349 * satisfying the request changes.
3350 *
3351 * @param network The {@link Network} of the satisfying network.
3352 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3353 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3354 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3355 * @hide
3356 */
3357 public void onAvailable(@NonNull Network network,
3358 @NonNull NetworkCapabilities networkCapabilities,
3359 @NonNull LinkProperties linkProperties, boolean blocked) {
3360 // Internally only this method is called when a new network is available, and
3361 // it calls the callback in the same way and order that older versions used
3362 // to call so as not to change the behavior.
3363 onAvailable(network);
3364 if (!networkCapabilities.hasCapability(
3365 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3366 onNetworkSuspended(network);
3367 }
3368 onCapabilitiesChanged(network, networkCapabilities);
3369 onLinkPropertiesChanged(network, linkProperties);
3370 onBlockedStatusChanged(network, blocked);
3371 }
3372
3373 /**
3374 * Called when the framework connects and has declared a new network ready for use.
3375 *
3376 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3377 * be available at the same time, and onAvailable will be called for each of these as they
3378 * appear.
3379 *
3380 * <p>For callbacks registered with {@link #requestNetwork} and
3381 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3382 * is the new best network for this request and is now tracked by this callback ; this
3383 * callback will no longer receive method calls about other networks that may have been
3384 * passed to this method previously. The previously-best network may have disconnected, or
3385 * it may still be around and the newly-best network may simply be better.
3386 *
3387 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3388 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3389 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3390 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3391 *
3392 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3393 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3394 * this callback as this is prone to race conditions (there is no guarantee the objects
3395 * returned by these methods will be current). Instead, wait for a call to
3396 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3397 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3398 * to be well-ordered with respect to other callbacks.
3399 *
3400 * @param network The {@link Network} of the satisfying network.
3401 */
3402 public void onAvailable(@NonNull Network network) {}
3403
3404 /**
3405 * Called when the network is about to be lost, typically because there are no outstanding
3406 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3407 * with the new replacement network for graceful handover. This method is not guaranteed
3408 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3409 * network is suddenly disconnected.
3410 *
3411 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3412 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3413 * this callback as this is prone to race conditions ; calling these methods while in a
3414 * callback may return an outdated or even a null object.
3415 *
3416 * @param network The {@link Network} that is about to be lost.
3417 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3418 * connected for graceful handover; note that the network may still
3419 * suffer a hard loss at any time.
3420 */
3421 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3422
3423 /**
3424 * Called when a network disconnects or otherwise no longer satisfies this request or
3425 * callback.
3426 *
3427 * <p>If the callback was registered with requestNetwork() or
3428 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3429 * returned by onAvailable() when that network is lost and no other network satisfies
3430 * the criteria of the request.
3431 *
3432 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3433 * each network which no longer satisfies the criteria of the callback.
3434 *
3435 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3436 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3437 * this callback as this is prone to race conditions ; calling these methods while in a
3438 * callback may return an outdated or even a null object.
3439 *
3440 * @param network The {@link Network} lost.
3441 */
3442 public void onLost(@NonNull Network network) {}
3443
3444 /**
3445 * Called if no network is found within the timeout time specified in
3446 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3447 * requested network request cannot be fulfilled (whether or not a timeout was
3448 * specified). When this callback is invoked the associated
3449 * {@link NetworkRequest} will have already been removed and released, as if
3450 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3451 */
3452 public void onUnavailable() {}
3453
3454 /**
3455 * Called when the network corresponding to this request changes capabilities but still
3456 * satisfies the requested criteria.
3457 *
3458 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3459 * to be called immediately after {@link #onAvailable}.
3460 *
3461 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3462 * ConnectivityManager methods in this callback as this is prone to race conditions :
3463 * calling these methods while in a callback may return an outdated or even a null object.
3464 *
3465 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003466 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003467 * network.
3468 */
3469 public void onCapabilitiesChanged(@NonNull Network network,
3470 @NonNull NetworkCapabilities networkCapabilities) {}
3471
3472 /**
3473 * Called when the network corresponding to this request changes {@link LinkProperties}.
3474 *
3475 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3476 * to be called immediately after {@link #onAvailable}.
3477 *
3478 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3479 * ConnectivityManager methods in this callback as this is prone to race conditions :
3480 * calling these methods while in a callback may return an outdated or even a null object.
3481 *
3482 * @param network The {@link Network} whose link properties have changed.
3483 * @param linkProperties The new {@link LinkProperties} for this network.
3484 */
3485 public void onLinkPropertiesChanged(@NonNull Network network,
3486 @NonNull LinkProperties linkProperties) {}
3487
3488 /**
3489 * Called when the network the framework connected to for this request suspends data
3490 * transmission temporarily.
3491 *
3492 * <p>This generally means that while the TCP connections are still live temporarily
3493 * network data fails to transfer. To give a specific example, this is used on cellular
3494 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3495 * means read operations on sockets on this network will block once the buffers are
3496 * drained, and write operations will block once the buffers are full.
3497 *
3498 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3499 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3500 * this callback as this is prone to race conditions (there is no guarantee the objects
3501 * returned by these methods will be current).
3502 *
3503 * @hide
3504 */
3505 public void onNetworkSuspended(@NonNull Network network) {}
3506
3507 /**
3508 * Called when the network the framework connected to for this request
3509 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3510 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3511
3512 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3513 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3514 * this callback as this is prone to race conditions : calling these methods while in a
3515 * callback may return an outdated or even a null object.
3516 *
3517 * @hide
3518 */
3519 public void onNetworkResumed(@NonNull Network network) {}
3520
3521 /**
3522 * Called when access to the specified network is blocked or unblocked.
3523 *
3524 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3525 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3526 * this callback as this is prone to race conditions : calling these methods while in a
3527 * callback may return an outdated or even a null object.
3528 *
3529 * @param network The {@link Network} whose blocked status has changed.
3530 * @param blocked The blocked status of this {@link Network}.
3531 */
3532 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3533
3534 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08003535 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003536 }
3537
3538 /**
3539 * Constant error codes used by ConnectivityService to communicate about failures and errors
3540 * across a Binder boundary.
3541 * @hide
3542 */
3543 public interface Errors {
3544 int TOO_MANY_REQUESTS = 1;
3545 }
3546
3547 /** @hide */
3548 public static class TooManyRequestsException extends RuntimeException {}
3549
3550 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3551 switch (e.errorCode) {
3552 case Errors.TOO_MANY_REQUESTS:
3553 return new TooManyRequestsException();
3554 default:
3555 Log.w(TAG, "Unknown service error code " + e.errorCode);
3556 return new RuntimeException(e);
3557 }
3558 }
3559
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003560 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003561 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003562 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003563 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003564 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003565 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003566 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003567 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003568 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003569 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003570 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003571 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003572 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003573 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003574 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003575 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003576 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003577 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003578 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003579 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003580 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003581 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003582
3583 /** @hide */
3584 public static String getCallbackName(int whichCallback) {
3585 switch (whichCallback) {
3586 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3587 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3588 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3589 case CALLBACK_LOST: return "CALLBACK_LOST";
3590 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3591 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3592 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
3593 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3594 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3595 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
3596 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
3597 default:
3598 return Integer.toString(whichCallback);
3599 }
3600 }
3601
3602 private class CallbackHandler extends Handler {
3603 private static final String TAG = "ConnectivityManager.CallbackHandler";
3604 private static final boolean DBG = false;
3605
3606 CallbackHandler(Looper looper) {
3607 super(looper);
3608 }
3609
3610 CallbackHandler(Handler handler) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003611 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003612 }
3613
3614 @Override
3615 public void handleMessage(Message message) {
3616 if (message.what == EXPIRE_LEGACY_REQUEST) {
3617 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3618 return;
3619 }
3620
3621 final NetworkRequest request = getObject(message, NetworkRequest.class);
3622 final Network network = getObject(message, Network.class);
3623 final NetworkCallback callback;
3624 synchronized (sCallbacks) {
3625 callback = sCallbacks.get(request);
3626 if (callback == null) {
3627 Log.w(TAG,
3628 "callback not found for " + getCallbackName(message.what) + " message");
3629 return;
3630 }
3631 if (message.what == CALLBACK_UNAVAIL) {
3632 sCallbacks.remove(request);
3633 callback.networkRequest = ALREADY_UNREGISTERED;
3634 }
3635 }
3636 if (DBG) {
3637 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
3638 }
3639
3640 switch (message.what) {
3641 case CALLBACK_PRECHECK: {
3642 callback.onPreCheck(network);
3643 break;
3644 }
3645 case CALLBACK_AVAILABLE: {
3646 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3647 LinkProperties lp = getObject(message, LinkProperties.class);
3648 callback.onAvailable(network, cap, lp, message.arg1 != 0);
3649 break;
3650 }
3651 case CALLBACK_LOSING: {
3652 callback.onLosing(network, message.arg1);
3653 break;
3654 }
3655 case CALLBACK_LOST: {
3656 callback.onLost(network);
3657 break;
3658 }
3659 case CALLBACK_UNAVAIL: {
3660 callback.onUnavailable();
3661 break;
3662 }
3663 case CALLBACK_CAP_CHANGED: {
3664 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3665 callback.onCapabilitiesChanged(network, cap);
3666 break;
3667 }
3668 case CALLBACK_IP_CHANGED: {
3669 LinkProperties lp = getObject(message, LinkProperties.class);
3670 callback.onLinkPropertiesChanged(network, lp);
3671 break;
3672 }
3673 case CALLBACK_SUSPENDED: {
3674 callback.onNetworkSuspended(network);
3675 break;
3676 }
3677 case CALLBACK_RESUMED: {
3678 callback.onNetworkResumed(network);
3679 break;
3680 }
3681 case CALLBACK_BLK_CHANGED: {
3682 boolean blocked = message.arg1 != 0;
3683 callback.onBlockedStatusChanged(network, blocked);
3684 }
3685 }
3686 }
3687
3688 private <T> T getObject(Message msg, Class<T> c) {
3689 return (T) msg.getData().getParcelable(c.getSimpleName());
3690 }
3691 }
3692
3693 private CallbackHandler getDefaultHandler() {
3694 synchronized (sCallbacks) {
3695 if (sCallbackHandler == null) {
3696 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
3697 }
3698 return sCallbackHandler;
3699 }
3700 }
3701
3702 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3703 private static CallbackHandler sCallbackHandler;
3704
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003705 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3706 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3707 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003708 printStackTrace();
3709 checkCallbackNotNull(callback);
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003710 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3711 throw new IllegalArgumentException("null NetworkCapabilities");
3712 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003713 final NetworkRequest request;
3714 final String callingPackageName = mContext.getOpPackageName();
3715 try {
3716 synchronized(sCallbacks) {
3717 if (callback.networkRequest != null
3718 && callback.networkRequest != ALREADY_UNREGISTERED) {
3719 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3720 // and requests (http://b/20701525).
3721 Log.e(TAG, "NetworkCallback was already registered");
3722 }
3723 Messenger messenger = new Messenger(handler);
3724 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08003725 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003726 if (reqType == LISTEN) {
3727 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08003728 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08003729 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003730 } else {
3731 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003732 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3733 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003734 }
3735 if (request != null) {
3736 sCallbacks.put(request, callback);
3737 }
3738 callback.networkRequest = request;
3739 }
3740 } catch (RemoteException e) {
3741 throw e.rethrowFromSystemServer();
3742 } catch (ServiceSpecificException e) {
3743 throw convertServiceException(e);
3744 }
3745 return request;
3746 }
3747
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003748 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3749 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3750 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3751 legacyType, handler);
3752 }
3753
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003754 /**
3755 * Helper function to request a network with a particular legacy type.
3756 *
3757 * This API is only for use in internal system code that requests networks with legacy type and
3758 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
3759 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
3760 *
3761 * @param request {@link NetworkRequest} describing this request.
3762 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3763 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3764 * be a positive value (i.e. >0).
3765 * @param legacyType to specify the network type(#TYPE_*).
3766 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3767 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3768 * the callback must not be shared - it uniquely specifies this request.
3769 *
3770 * @hide
3771 */
3772 @SystemApi
3773 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
3774 public void requestNetwork(@NonNull NetworkRequest request,
3775 int timeoutMs, int legacyType, @NonNull Handler handler,
3776 @NonNull NetworkCallback networkCallback) {
3777 if (legacyType == TYPE_NONE) {
3778 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3779 }
3780 CallbackHandler cbHandler = new CallbackHandler(handler);
3781 NetworkCapabilities nc = request.networkCapabilities;
3782 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
3783 }
3784
3785 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003786 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003787 *
3788 * <p>This method will attempt to find the best network that matches the passed
3789 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3790 * criteria. The platform will evaluate which network is the best at its own discretion.
3791 * Throughput, latency, cost per byte, policy, user preference and other considerations
3792 * may be factored in the decision of what is considered the best network.
3793 *
3794 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3795 * matching this request, while always attempting to match the request to a better network if
3796 * possible. If a better match is found, the platform will switch this request to the now-best
3797 * network and inform the app of the newly best network by invoking
3798 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3799 * will not try to maintain any other network than the best one currently matching the request:
3800 * a network not matching any network request may be disconnected at any time.
3801 *
3802 * <p>For example, an application could use this method to obtain a connected cellular network
3803 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3804 * radio to consume additional power. Or, an application could inform the system that it wants
3805 * a network supporting sending MMSes and have the system let it know about the currently best
3806 * MMS-supporting network through the provided {@link NetworkCallback}.
3807 *
3808 * <p>The status of the request can be followed by listening to the various callbacks described
3809 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3810 * used to direct traffic to the network (although accessing some networks may be subject to
3811 * holding specific permissions). Callers will learn about the specific characteristics of the
3812 * network through
3813 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3814 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3815 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3816 * matching the request at any given time; therefore when a better network matching the request
3817 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3818 * with the new network after which no further updates are given about the previously-best
3819 * network, unless it becomes the best again at some later time. All callbacks are invoked
3820 * in order on the same thread, which by default is a thread created by the framework running
3821 * in the app.
3822 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3823 * callbacks are invoked.
3824 *
3825 * <p>This{@link NetworkRequest} will live until released via
3826 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3827 * which point the system may let go of the network at any time.
3828 *
3829 * <p>A version of this method which takes a timeout is
3830 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3831 * wait for a limited amount of time for the network to become unavailable.
3832 *
3833 * <p>It is presently unsupported to request a network with mutable
3834 * {@link NetworkCapabilities} such as
3835 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3836 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3837 * as these {@code NetworkCapabilities} represent states that a particular
3838 * network may never attain, and whether a network will attain these states
3839 * is unknown prior to bringing up the network so the framework does not
3840 * know how to go about satisfying a request with these capabilities.
3841 *
3842 * <p>This method requires the caller to hold either the
3843 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3844 * or the ability to modify system settings as determined by
3845 * {@link android.provider.Settings.System#canWrite}.</p>
3846 *
3847 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3848 * number of outstanding requests to 100 per app (identified by their UID), shared with
3849 * all variants of this method, of {@link #registerNetworkCallback} as well as
3850 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3851 * Requesting a network with this method will count toward this limit. If this limit is
3852 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3853 * make sure to unregister the callbacks with
3854 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3855 *
3856 * @param request {@link NetworkRequest} describing this request.
3857 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3858 * the callback must not be shared - it uniquely specifies this request.
3859 * The callback is invoked on the default internal Handler.
3860 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3861 * @throws SecurityException if missing the appropriate permissions.
3862 * @throws RuntimeException if the app already has too many callbacks registered.
3863 */
3864 public void requestNetwork(@NonNull NetworkRequest request,
3865 @NonNull NetworkCallback networkCallback) {
3866 requestNetwork(request, networkCallback, getDefaultHandler());
3867 }
3868
3869 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003870 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003871 *
3872 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3873 * but runs all the callbacks on the passed Handler.
3874 *
3875 * <p>This method has the same permission requirements as
3876 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3877 * and throws the same exceptions in the same conditions.
3878 *
3879 * @param request {@link NetworkRequest} describing this request.
3880 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3881 * the callback must not be shared - it uniquely specifies this request.
3882 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3883 */
3884 public void requestNetwork(@NonNull NetworkRequest request,
3885 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
3886 CallbackHandler cbHandler = new CallbackHandler(handler);
3887 NetworkCapabilities nc = request.networkCapabilities;
3888 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
3889 }
3890
3891 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003892 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003893 * by a timeout.
3894 *
3895 * This function behaves identically to the non-timed-out version
3896 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3897 * is not found within the given time (in milliseconds) the
3898 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3899 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3900 * not have to be released if timed-out (it is automatically released). Unregistering a
3901 * request that timed out is not an error.
3902 *
3903 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3904 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3905 * for that purpose. Calling this method will attempt to bring up the requested network.
3906 *
3907 * <p>This method has the same permission requirements as
3908 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3909 * and throws the same exceptions in the same conditions.
3910 *
3911 * @param request {@link NetworkRequest} describing this request.
3912 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3913 * the callback must not be shared - it uniquely specifies this request.
3914 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3915 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3916 * be a positive value (i.e. >0).
3917 */
3918 public void requestNetwork(@NonNull NetworkRequest request,
3919 @NonNull NetworkCallback networkCallback, int timeoutMs) {
3920 checkTimeout(timeoutMs);
3921 NetworkCapabilities nc = request.networkCapabilities;
3922 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3923 getDefaultHandler());
3924 }
3925
3926 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003927 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003928 * by a timeout.
3929 *
3930 * This method behaves identically to
3931 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3932 * on the passed Handler.
3933 *
3934 * <p>This method has the same permission requirements as
3935 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3936 * and throws the same exceptions in the same conditions.
3937 *
3938 * @param request {@link NetworkRequest} describing this request.
3939 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3940 * the callback must not be shared - it uniquely specifies this request.
3941 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3942 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3943 * before {@link NetworkCallback#onUnavailable} is called.
3944 */
3945 public void requestNetwork(@NonNull NetworkRequest request,
3946 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
3947 checkTimeout(timeoutMs);
3948 CallbackHandler cbHandler = new CallbackHandler(handler);
3949 NetworkCapabilities nc = request.networkCapabilities;
3950 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
3951 }
3952
3953 /**
3954 * The lookup key for a {@link Network} object included with the intent after
3955 * successfully finding a network for the applications request. Retrieve it with
3956 * {@link android.content.Intent#getParcelableExtra(String)}.
3957 * <p>
3958 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3959 * then you must get a ConnectivityManager instance before doing so.
3960 */
3961 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
3962
3963 /**
3964 * The lookup key for a {@link NetworkRequest} object included with the intent after
3965 * successfully finding a network for the applications request. Retrieve it with
3966 * {@link android.content.Intent#getParcelableExtra(String)}.
3967 */
3968 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
3969
3970
3971 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003972 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003973 *
3974 * This function behaves identically to the version that takes a NetworkCallback, but instead
3975 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3976 * the request may outlive the calling application and get called back when a suitable
3977 * network is found.
3978 * <p>
3979 * The operation is an Intent broadcast that goes to a broadcast receiver that
3980 * you registered with {@link Context#registerReceiver} or through the
3981 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3982 * <p>
3983 * The operation Intent is delivered with two extras, a {@link Network} typed
3984 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3985 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3986 * the original requests parameters. It is important to create a new,
3987 * {@link NetworkCallback} based request before completing the processing of the
3988 * Intent to reserve the network or it will be released shortly after the Intent
3989 * is processed.
3990 * <p>
3991 * If there is already a request for this Intent registered (with the equality of
3992 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3993 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3994 * <p>
3995 * The request may be released normally by calling
3996 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
3997 * <p>It is presently unsupported to request a network with either
3998 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3999 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4000 * as these {@code NetworkCapabilities} represent states that a particular
4001 * network may never attain, and whether a network will attain these states
4002 * is unknown prior to bringing up the network so the framework does not
4003 * know how to go about satisfying a request with these capabilities.
4004 *
4005 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4006 * number of outstanding requests to 100 per app (identified by their UID), shared with
4007 * all variants of this method, of {@link #registerNetworkCallback} as well as
4008 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4009 * Requesting a network with this method will count toward this limit. If this limit is
4010 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4011 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4012 * or {@link #releaseNetworkRequest(PendingIntent)}.
4013 *
4014 * <p>This method requires the caller to hold either the
4015 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4016 * or the ability to modify system settings as determined by
4017 * {@link android.provider.Settings.System#canWrite}.</p>
4018 *
4019 * @param request {@link NetworkRequest} describing this request.
4020 * @param operation Action to perform when the network is available (corresponds
4021 * to the {@link NetworkCallback#onAvailable} call. Typically
4022 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4023 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4024 * @throws SecurityException if missing the appropriate permissions.
4025 * @throws RuntimeException if the app already has too many callbacks registered.
4026 */
4027 public void requestNetwork(@NonNull NetworkRequest request,
4028 @NonNull PendingIntent operation) {
4029 printStackTrace();
4030 checkPendingIntentNotNull(operation);
4031 try {
4032 mService.pendingRequestForNetwork(
4033 request.networkCapabilities, operation, mContext.getOpPackageName(),
4034 getAttributionTag());
4035 } catch (RemoteException e) {
4036 throw e.rethrowFromSystemServer();
4037 } catch (ServiceSpecificException e) {
4038 throw convertServiceException(e);
4039 }
4040 }
4041
4042 /**
4043 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4044 * <p>
4045 * This method has the same behavior as
4046 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4047 * releasing network resources and disconnecting.
4048 *
4049 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4050 * PendingIntent passed to
4051 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4052 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4053 */
4054 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4055 printStackTrace();
4056 checkPendingIntentNotNull(operation);
4057 try {
4058 mService.releasePendingNetworkRequest(operation);
4059 } catch (RemoteException e) {
4060 throw e.rethrowFromSystemServer();
4061 }
4062 }
4063
4064 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004065 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004066 }
4067
4068 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004069 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004070 }
4071
4072 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004073 if (timeoutMs <= 0) {
4074 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4075 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004076 }
4077
4078 /**
4079 * Registers to receive notifications about all networks which satisfy the given
4080 * {@link NetworkRequest}. The callbacks will continue to be called until
4081 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4082 * called.
4083 *
4084 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4085 * number of outstanding requests to 100 per app (identified by their UID), shared with
4086 * all variants of this method, of {@link #requestNetwork} as well as
4087 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4088 * Requesting a network with this method will count toward this limit. If this limit is
4089 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4090 * make sure to unregister the callbacks with
4091 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4092 *
4093 * @param request {@link NetworkRequest} describing this request.
4094 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4095 * networks change state.
4096 * The callback is invoked on the default internal Handler.
4097 * @throws RuntimeException if the app already has too many callbacks registered.
4098 */
4099 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4100 public void registerNetworkCallback(@NonNull NetworkRequest request,
4101 @NonNull NetworkCallback networkCallback) {
4102 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4103 }
4104
4105 /**
4106 * Registers to receive notifications about all networks which satisfy the given
4107 * {@link NetworkRequest}. The callbacks will continue to be called until
4108 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4109 * called.
4110 *
4111 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4112 * number of outstanding requests to 100 per app (identified by their UID), shared with
4113 * all variants of this method, of {@link #requestNetwork} as well as
4114 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4115 * Requesting a network with this method will count toward this limit. If this limit is
4116 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4117 * make sure to unregister the callbacks with
4118 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4119 *
4120 *
4121 * @param request {@link NetworkRequest} describing this request.
4122 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4123 * networks change state.
4124 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4125 * @throws RuntimeException if the app already has too many callbacks registered.
4126 */
4127 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4128 public void registerNetworkCallback(@NonNull NetworkRequest request,
4129 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4130 CallbackHandler cbHandler = new CallbackHandler(handler);
4131 NetworkCapabilities nc = request.networkCapabilities;
4132 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4133 }
4134
4135 /**
4136 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4137 * {@link NetworkRequest}.
4138 *
4139 * This function behaves identically to the version that takes a NetworkCallback, but instead
4140 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4141 * the request may outlive the calling application and get called back when a suitable
4142 * network is found.
4143 * <p>
4144 * The operation is an Intent broadcast that goes to a broadcast receiver that
4145 * you registered with {@link Context#registerReceiver} or through the
4146 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4147 * <p>
4148 * The operation Intent is delivered with two extras, a {@link Network} typed
4149 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4150 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4151 * the original requests parameters.
4152 * <p>
4153 * If there is already a request for this Intent registered (with the equality of
4154 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4155 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4156 * <p>
4157 * The request may be released normally by calling
4158 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4159 *
4160 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4161 * number of outstanding requests to 100 per app (identified by their UID), shared with
4162 * all variants of this method, of {@link #requestNetwork} as well as
4163 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4164 * Requesting a network with this method will count toward this limit. If this limit is
4165 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4166 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4167 * or {@link #releaseNetworkRequest(PendingIntent)}.
4168 *
4169 * @param request {@link NetworkRequest} describing this request.
4170 * @param operation Action to perform when the network is available (corresponds
4171 * to the {@link NetworkCallback#onAvailable} call. Typically
4172 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4173 * @throws RuntimeException if the app already has too many callbacks registered.
4174 */
4175 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4176 public void registerNetworkCallback(@NonNull NetworkRequest request,
4177 @NonNull PendingIntent operation) {
4178 printStackTrace();
4179 checkPendingIntentNotNull(operation);
4180 try {
4181 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004182 request.networkCapabilities, operation, mContext.getOpPackageName(),
4183 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004184 } catch (RemoteException e) {
4185 throw e.rethrowFromSystemServer();
4186 } catch (ServiceSpecificException e) {
4187 throw convertServiceException(e);
4188 }
4189 }
4190
4191 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004192 * Registers to receive notifications about changes in the application's default network. This
4193 * may be a physical network or a virtual network, such as a VPN that applies to the
4194 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004195 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4196 *
4197 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4198 * number of outstanding requests to 100 per app (identified by their UID), shared with
4199 * all variants of this method, of {@link #requestNetwork} as well as
4200 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4201 * Requesting a network with this method will count toward this limit. If this limit is
4202 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4203 * make sure to unregister the callbacks with
4204 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4205 *
4206 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004207 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004208 * The callback is invoked on the default internal Handler.
4209 * @throws RuntimeException if the app already has too many callbacks registered.
4210 */
4211 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4212 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4213 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4214 }
4215
4216 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004217 * Registers to receive notifications about changes in the application's default network. This
4218 * may be a physical network or a virtual network, such as a VPN that applies to the
4219 * application. The callbacks will continue to be called until either the application exits or
4220 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4221 *
4222 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4223 * number of outstanding requests to 100 per app (identified by their UID), shared with
4224 * all variants of this method, of {@link #requestNetwork} as well as
4225 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4226 * Requesting a network with this method will count toward this limit. If this limit is
4227 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4228 * make sure to unregister the callbacks with
4229 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4230 *
4231 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4232 * application's default network changes.
4233 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4234 * @throws RuntimeException if the app already has too many callbacks registered.
4235 */
4236 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4237 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4238 @NonNull Handler handler) {
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004239 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4240 }
4241
4242 /**
4243 * Registers to receive notifications about changes in the default network for the specified
4244 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4245 * UID. The callbacks will continue to be called until either the application exits or
4246 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4247 *
4248 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4249 * number of outstanding requests to 100 per app (identified by their UID), shared with
4250 * all variants of this method, of {@link #requestNetwork} as well as
4251 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4252 * Requesting a network with this method will count toward this limit. If this limit is
4253 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4254 * make sure to unregister the callbacks with
4255 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4256 *
4257 * @param uid the UID for which to track default network changes.
4258 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4259 * UID's default network changes.
4260 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4261 * @throws RuntimeException if the app already has too many callbacks registered.
4262 * @hide
4263 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004264 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004265 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4266 @RequiresPermission(anyOf = {
4267 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4268 android.Manifest.permission.NETWORK_SETTINGS})
4269 public void registerDefaultNetworkCallbackAsUid(int uid,
4270 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004271 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004272 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004273 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4274 }
4275
4276 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004277 * Registers to receive notifications about changes in the system default network. The callbacks
4278 * will continue to be called until either the application exits or
4279 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4280 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004281 * This method should not be used to determine networking state seen by applications, because in
4282 * many cases, most or even all application traffic may not use the default network directly,
4283 * and traffic from different applications may go on different networks by default. As an
4284 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4285 * and not onto the system default network. Applications or system components desiring to do
4286 * determine network state as seen by applications should use other methods such as
4287 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4288 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004289 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4290 * number of outstanding requests to 100 per app (identified by their UID), shared with
4291 * all variants of this method, of {@link #requestNetwork} as well as
4292 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4293 * Requesting a network with this method will count toward this limit. If this limit is
4294 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4295 * make sure to unregister the callbacks with
4296 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4297 *
4298 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4299 * system default network changes.
4300 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4301 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004302 *
4303 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004304 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004305 @SystemApi(client = MODULE_LIBRARIES)
4306 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4307 @RequiresPermission(anyOf = {
4308 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4309 android.Manifest.permission.NETWORK_SETTINGS})
4310 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004311 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004312 CallbackHandler cbHandler = new CallbackHandler(handler);
4313 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004314 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004315 }
4316
4317 /**
junyulaibd123062021-03-15 11:48:48 +08004318 * Registers to receive notifications about the best matching network which satisfy the given
4319 * {@link NetworkRequest}. The callbacks will continue to be called until
4320 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4321 * called.
4322 *
4323 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4324 * number of outstanding requests to 100 per app (identified by their UID), shared with
4325 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4326 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4327 * Requesting a network with this method will count toward this limit. If this limit is
4328 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4329 * make sure to unregister the callbacks with
4330 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4331 *
4332 *
4333 * @param request {@link NetworkRequest} describing this request.
4334 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4335 * networks change state.
4336 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4337 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004338 */
junyulai5a5c99b2021-03-05 15:51:17 +08004339 @SuppressLint("ExecutorRegistration")
4340 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4341 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4342 final NetworkCapabilities nc = request.networkCapabilities;
4343 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004344 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004345 }
4346
4347 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004348 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4349 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4350 * network connection for updated bandwidth information. The caller will be notified via
4351 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4352 * method assumes that the caller has previously called
4353 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4354 * changes.
4355 *
4356 * @param network {@link Network} specifying which network you're interested.
4357 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4358 */
4359 public boolean requestBandwidthUpdate(@NonNull Network network) {
4360 try {
4361 return mService.requestBandwidthUpdate(network);
4362 } catch (RemoteException e) {
4363 throw e.rethrowFromSystemServer();
4364 }
4365 }
4366
4367 /**
4368 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4369 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4370 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4371 * If the given {@code NetworkCallback} had previously been used with
4372 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4373 * will be disconnected.
4374 *
4375 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4376 * triggering it as soon as this call returns.
4377 *
4378 * @param networkCallback The {@link NetworkCallback} used when making the request.
4379 */
4380 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4381 printStackTrace();
4382 checkCallbackNotNull(networkCallback);
4383 final List<NetworkRequest> reqs = new ArrayList<>();
4384 // Find all requests associated to this callback and stop callback triggers immediately.
4385 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4386 synchronized (sCallbacks) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004387 if (networkCallback.networkRequest == null) {
4388 throw new IllegalArgumentException("NetworkCallback was not registered");
4389 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004390 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4391 Log.d(TAG, "NetworkCallback was already unregistered");
4392 return;
4393 }
4394 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4395 if (e.getValue() == networkCallback) {
4396 reqs.add(e.getKey());
4397 }
4398 }
4399 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4400 for (NetworkRequest r : reqs) {
4401 try {
4402 mService.releaseNetworkRequest(r);
4403 } catch (RemoteException e) {
4404 throw e.rethrowFromSystemServer();
4405 }
4406 // Only remove mapping if rpc was successful.
4407 sCallbacks.remove(r);
4408 }
4409 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4410 }
4411 }
4412
4413 /**
4414 * Unregisters a callback previously registered via
4415 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4416 *
4417 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4418 * PendingIntent passed to
4419 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4420 * Cannot be null.
4421 */
4422 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4423 releaseNetworkRequest(operation);
4424 }
4425
4426 /**
4427 * Informs the system whether it should switch to {@code network} regardless of whether it is
4428 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4429 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4430 * the system default network regardless of any other network that's currently connected. If
4431 * {@code always} is true, then the choice is remembered, so that the next time the user
4432 * connects to this network, the system will switch to it.
4433 *
4434 * @param network The network to accept.
4435 * @param accept Whether to accept the network even if unvalidated.
4436 * @param always Whether to remember this choice in the future.
4437 *
4438 * @hide
4439 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004440 @SystemApi(client = MODULE_LIBRARIES)
4441 @RequiresPermission(anyOf = {
4442 android.Manifest.permission.NETWORK_SETTINGS,
4443 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4444 android.Manifest.permission.NETWORK_STACK,
4445 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4446 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004447 try {
4448 mService.setAcceptUnvalidated(network, accept, always);
4449 } catch (RemoteException e) {
4450 throw e.rethrowFromSystemServer();
4451 }
4452 }
4453
4454 /**
4455 * Informs the system whether it should consider the network as validated even if it only has
4456 * partial connectivity. If {@code accept} is true, then the network will be considered as
4457 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4458 * is remembered, so that the next time the user connects to this network, the system will
4459 * switch to it.
4460 *
4461 * @param network The network to accept.
4462 * @param accept Whether to consider the network as validated even if it has partial
4463 * connectivity.
4464 * @param always Whether to remember this choice in the future.
4465 *
4466 * @hide
4467 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004468 @SystemApi(client = MODULE_LIBRARIES)
4469 @RequiresPermission(anyOf = {
4470 android.Manifest.permission.NETWORK_SETTINGS,
4471 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4472 android.Manifest.permission.NETWORK_STACK,
4473 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4474 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4475 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004476 try {
4477 mService.setAcceptPartialConnectivity(network, accept, always);
4478 } catch (RemoteException e) {
4479 throw e.rethrowFromSystemServer();
4480 }
4481 }
4482
4483 /**
4484 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4485 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4486 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4487 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4488 *
4489 * @param network The network to accept.
4490 *
4491 * @hide
4492 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004493 @SystemApi(client = MODULE_LIBRARIES)
4494 @RequiresPermission(anyOf = {
4495 android.Manifest.permission.NETWORK_SETTINGS,
4496 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4497 android.Manifest.permission.NETWORK_STACK,
4498 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4499 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004500 try {
4501 mService.setAvoidUnvalidated(network);
4502 } catch (RemoteException e) {
4503 throw e.rethrowFromSystemServer();
4504 }
4505 }
4506
4507 /**
4508 * Requests that the system open the captive portal app on the specified network.
4509 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004510 * <p>This is to be used on networks where a captive portal was detected, as per
4511 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4512 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004513 * @param network The network to log into.
4514 *
4515 * @hide
4516 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004517 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4518 @RequiresPermission(anyOf = {
4519 android.Manifest.permission.NETWORK_SETTINGS,
4520 android.Manifest.permission.NETWORK_STACK,
4521 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4522 })
4523 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004524 try {
4525 mService.startCaptivePortalApp(network);
4526 } catch (RemoteException e) {
4527 throw e.rethrowFromSystemServer();
4528 }
4529 }
4530
4531 /**
4532 * Requests that the system open the captive portal app with the specified extras.
4533 *
4534 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4535 * corresponding permission.
4536 * @param network Network on which the captive portal was detected.
4537 * @param appExtras Extras to include in the app start intent.
4538 * @hide
4539 */
4540 @SystemApi
4541 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4542 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4543 try {
4544 mService.startCaptivePortalAppInternal(network, appExtras);
4545 } catch (RemoteException e) {
4546 throw e.rethrowFromSystemServer();
4547 }
4548 }
4549
4550 /**
4551 * Determine whether the device is configured to avoid bad wifi.
4552 * @hide
4553 */
4554 @SystemApi
4555 @RequiresPermission(anyOf = {
4556 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4557 android.Manifest.permission.NETWORK_STACK})
4558 public boolean shouldAvoidBadWifi() {
4559 try {
4560 return mService.shouldAvoidBadWifi();
4561 } catch (RemoteException e) {
4562 throw e.rethrowFromSystemServer();
4563 }
4564 }
4565
4566 /**
4567 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4568 * time-sensitive user-facing operations when the system default network is temporarily
4569 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4570 * this method), and the operation should be infrequent to ensure that data usage is limited.
4571 *
4572 * An example of such an operation might be a time-sensitive foreground activity, such as a
4573 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4574 */
4575 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4576
4577 /**
4578 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4579 * a backup channel for traffic that is primarily going over another network.
4580 *
4581 * An example might be maintaining backup connections to peers or servers for the purpose of
4582 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4583 * on backup paths should be negligible compared to the traffic on the main path.
4584 */
4585 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4586
4587 /**
4588 * It is acceptable to use metered data to improve network latency and performance.
4589 */
4590 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4591
4592 /**
4593 * Return value to use for unmetered networks. On such networks we currently set all the flags
4594 * to true.
4595 * @hide
4596 */
4597 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4598 MULTIPATH_PREFERENCE_HANDOVER |
4599 MULTIPATH_PREFERENCE_RELIABILITY |
4600 MULTIPATH_PREFERENCE_PERFORMANCE;
4601
4602 /** @hide */
4603 @Retention(RetentionPolicy.SOURCE)
4604 @IntDef(flag = true, value = {
4605 MULTIPATH_PREFERENCE_HANDOVER,
4606 MULTIPATH_PREFERENCE_RELIABILITY,
4607 MULTIPATH_PREFERENCE_PERFORMANCE,
4608 })
4609 public @interface MultipathPreference {
4610 }
4611
4612 /**
4613 * Provides a hint to the calling application on whether it is desirable to use the
4614 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4615 * for multipath data transfer on this network when it is not the system default network.
4616 * Applications desiring to use multipath network protocols should call this method before
4617 * each such operation.
4618 *
4619 * @param network The network on which the application desires to use multipath data.
4620 * If {@code null}, this method will return the a preference that will generally
4621 * apply to metered networks.
4622 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4623 */
4624 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4625 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
4626 try {
4627 return mService.getMultipathPreference(network);
4628 } catch (RemoteException e) {
4629 throw e.rethrowFromSystemServer();
4630 }
4631 }
4632
4633 /**
4634 * Resets all connectivity manager settings back to factory defaults.
4635 * @hide
4636 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004637 @SystemApi(client = MODULE_LIBRARIES)
4638 @RequiresPermission(anyOf = {
4639 android.Manifest.permission.NETWORK_SETTINGS,
4640 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004641 public void factoryReset() {
4642 try {
4643 mService.factoryReset();
4644 mTetheringManager.stopAllTethering();
4645 } catch (RemoteException e) {
4646 throw e.rethrowFromSystemServer();
4647 }
4648 }
4649
4650 /**
4651 * Binds the current process to {@code network}. All Sockets created in the future
4652 * (and not explicitly bound via a bound SocketFactory from
4653 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4654 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4655 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4656 * work and all host name resolutions will fail. This is by design so an application doesn't
4657 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4658 * To clear binding pass {@code null} for {@code network}. Using individually bound
4659 * Sockets created by Network.getSocketFactory().createSocket() and
4660 * performing network-specific host name resolutions via
4661 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4662 * {@code bindProcessToNetwork}.
4663 *
4664 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4665 * the current binding.
4666 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4667 */
4668 public boolean bindProcessToNetwork(@Nullable Network network) {
4669 // Forcing callers to call through non-static function ensures ConnectivityManager
4670 // instantiated.
4671 return setProcessDefaultNetwork(network);
4672 }
4673
4674 /**
4675 * Binds the current process to {@code network}. All Sockets created in the future
4676 * (and not explicitly bound via a bound SocketFactory from
4677 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4678 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4679 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4680 * work and all host name resolutions will fail. This is by design so an application doesn't
4681 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4682 * To clear binding pass {@code null} for {@code network}. Using individually bound
4683 * Sockets created by Network.getSocketFactory().createSocket() and
4684 * performing network-specific host name resolutions via
4685 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4686 * {@code setProcessDefaultNetwork}.
4687 *
4688 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4689 * the current binding.
4690 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4691 * @deprecated This function can throw {@link IllegalStateException}. Use
4692 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4693 * is a direct replacement.
4694 */
4695 @Deprecated
4696 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
4697 int netId = (network == null) ? NETID_UNSET : network.netId;
4698 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4699
4700 if (netId != NETID_UNSET) {
4701 netId = network.getNetIdForResolv();
4702 }
4703
4704 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4705 return false;
4706 }
4707
4708 if (!isSameNetId) {
4709 // Set HTTP proxy system properties to match network.
4710 // TODO: Deprecate this static method and replace it with a non-static version.
4711 try {
Remi NGUYEN VAN345c2df2021-02-03 10:18:20 +09004712 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004713 } catch (SecurityException e) {
4714 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4715 Log.e(TAG, "Can't set proxy properties", e);
4716 }
4717 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN342dddd2021-03-18 23:27:19 +09004718 InetAddressCompat.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004719 // Must flush socket pool as idle sockets will be bound to previous network and may
4720 // cause subsequent fetches to be performed on old network.
4721 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
4722 }
4723
4724 return true;
4725 }
4726
4727 /**
4728 * Returns the {@link Network} currently bound to this process via
4729 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4730 *
4731 * @return {@code Network} to which this process is bound, or {@code null}.
4732 */
4733 @Nullable
4734 public Network getBoundNetworkForProcess() {
4735 // Forcing callers to call thru non-static function ensures ConnectivityManager
4736 // instantiated.
4737 return getProcessDefaultNetwork();
4738 }
4739
4740 /**
4741 * Returns the {@link Network} currently bound to this process via
4742 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4743 *
4744 * @return {@code Network} to which this process is bound, or {@code null}.
4745 * @deprecated Using this function can lead to other functions throwing
4746 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4747 * {@code getBoundNetworkForProcess} is a direct replacement.
4748 */
4749 @Deprecated
4750 @Nullable
4751 public static Network getProcessDefaultNetwork() {
4752 int netId = NetworkUtils.getBoundNetworkForProcess();
4753 if (netId == NETID_UNSET) return null;
4754 return new Network(netId);
4755 }
4756
4757 private void unsupportedStartingFrom(int version) {
4758 if (Process.myUid() == Process.SYSTEM_UID) {
4759 // The getApplicationInfo() call we make below is not supported in system context. Let
4760 // the call through here, and rely on the fact that ConnectivityService will refuse to
4761 // allow the system to use these APIs anyway.
4762 return;
4763 }
4764
4765 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4766 throw new UnsupportedOperationException(
4767 "This method is not supported in target SDK version " + version + " and above");
4768 }
4769 }
4770
4771 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4772 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
4773 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
4774 // remove these exemptions. Note that this check is not secure, and apps can still access these
4775 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4776 // so is unsupported and may break in the future. http://b/22728205
4777 private void checkLegacyRoutingApiAccess() {
4778 unsupportedStartingFrom(VERSION_CODES.M);
4779 }
4780
4781 /**
4782 * Binds host resolutions performed by this process to {@code network}.
4783 * {@link #bindProcessToNetwork} takes precedence over this setting.
4784 *
4785 * @param network The {@link Network} to bind host resolutions from the current process to, or
4786 * {@code null} to clear the current binding.
4787 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4788 * @hide
4789 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4790 */
4791 @Deprecated
4792 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4793 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
4794 return NetworkUtils.bindProcessToNetworkForHostResolution(
4795 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
4796 }
4797
4798 /**
4799 * Device is not restricting metered network activity while application is running on
4800 * background.
4801 */
4802 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4803
4804 /**
4805 * Device is restricting metered network activity while application is running on background,
4806 * but application is allowed to bypass it.
4807 * <p>
4808 * In this state, application should take action to mitigate metered network access.
4809 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4810 */
4811 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4812
4813 /**
4814 * Device is restricting metered network activity while application is running on background.
4815 * <p>
4816 * In this state, application should not try to use the network while running on background,
4817 * because it would be denied.
4818 */
4819 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4820
4821 /**
4822 * A change in the background metered network activity restriction has occurred.
4823 * <p>
4824 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4825 * applies to them.
4826 * <p>
4827 * This is only sent to registered receivers, not manifest receivers.
4828 */
4829 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4830 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4831 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4832
4833 /** @hide */
4834 @Retention(RetentionPolicy.SOURCE)
4835 @IntDef(flag = false, value = {
4836 RESTRICT_BACKGROUND_STATUS_DISABLED,
4837 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4838 RESTRICT_BACKGROUND_STATUS_ENABLED,
4839 })
4840 public @interface RestrictBackgroundStatus {
4841 }
4842
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004843 /**
4844 * Determines if the calling application is subject to metered network restrictions while
4845 * running on background.
4846 *
4847 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4848 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4849 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
4850 */
4851 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4852 try {
Remi NGUYEN VANe62e7ff2021-03-18 14:23:12 +09004853 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004854 } catch (RemoteException e) {
4855 throw e.rethrowFromSystemServer();
4856 }
4857 }
4858
4859 /**
4860 * The network watchlist is a list of domains and IP addresses that are associated with
4861 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4862 * currently used by the system for validation purposes.
4863 *
4864 * @return Hash of network watchlist config file. Null if config does not exist.
4865 */
4866 @Nullable
4867 public byte[] getNetworkWatchlistConfigHash() {
4868 try {
4869 return mService.getNetworkWatchlistConfigHash();
4870 } catch (RemoteException e) {
4871 Log.e(TAG, "Unable to get watchlist config hash");
4872 throw e.rethrowFromSystemServer();
4873 }
4874 }
4875
4876 /**
4877 * Returns the {@code uid} of the owner of a network connection.
4878 *
4879 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4880 * IPPROTO_UDP} currently supported.
4881 * @param local The local {@link InetSocketAddress} of a connection.
4882 * @param remote The remote {@link InetSocketAddress} of a connection.
4883 * @return {@code uid} if the connection is found and the app has permission to observe it
4884 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4885 * android.os.Process#INVALID_UID} if the connection is not found.
4886 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4887 * user.
4888 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
4889 */
4890 public int getConnectionOwnerUid(
4891 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
4892 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4893 try {
4894 return mService.getConnectionOwnerUid(connectionInfo);
4895 } catch (RemoteException e) {
4896 throw e.rethrowFromSystemServer();
4897 }
4898 }
4899
4900 private void printStackTrace() {
4901 if (DEBUG) {
4902 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4903 final StringBuffer sb = new StringBuffer();
4904 for (int i = 3; i < callStack.length; i++) {
4905 final String stackTrace = callStack[i].toString();
4906 if (stackTrace == null || stackTrace.contains("android.os")) {
4907 break;
4908 }
4909 sb.append(" [").append(stackTrace).append("]");
4910 }
4911 Log.d(TAG, "StackLog:" + sb.toString());
4912 }
4913 }
4914
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09004915 /** @hide */
4916 public TestNetworkManager startOrGetTestNetworkManager() {
4917 final IBinder tnBinder;
4918 try {
4919 tnBinder = mService.startOrGetTestNetworkService();
4920 } catch (RemoteException e) {
4921 throw e.rethrowFromSystemServer();
4922 }
4923
4924 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4925 }
4926
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09004927 /** @hide */
4928 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4929 return new ConnectivityDiagnosticsManager(mContext, mService);
4930 }
4931
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004932 /**
4933 * Simulates a Data Stall for the specified Network.
4934 *
4935 * <p>This method should only be used for tests.
4936 *
4937 * <p>The caller must be the owner of the specified Network.
4938 *
4939 * @param detectionMethod The detection method used to identify the Data Stall.
4940 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4941 * @param network The Network for which a Data Stall is being simluated.
4942 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4943 * @throws SecurityException if the caller is not the owner of the given network.
4944 * @hide
4945 */
4946 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4947 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4948 android.Manifest.permission.NETWORK_STACK})
4949 public void simulateDataStall(int detectionMethod, long timestampMillis,
4950 @NonNull Network network, @NonNull PersistableBundle extras) {
4951 try {
4952 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4953 } catch (RemoteException e) {
4954 e.rethrowFromSystemServer();
4955 }
4956 }
4957
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004958 @NonNull
4959 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4960
4961 /**
4962 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4963 * receive available QoS events related to the {@link Network} and local ip + port
4964 * specified within socketInfo.
4965 * <p/>
4966 * The same {@link QosCallback} must be unregistered before being registered a second time,
4967 * otherwise {@link QosCallbackRegistrationException} is thrown.
4968 * <p/>
4969 * This API does not, in itself, require any permission if called with a network that is not
4970 * restricted. However, the underlying implementation currently only supports the IMS network,
4971 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4972 * useful, because they'd never be called back on networks that they would have access to.
4973 *
4974 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4975 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4976 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4977 * @throws RuntimeException if the app already has too many callbacks registered.
4978 *
4979 * Exceptions after the time of registration is passed through
4980 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4981 *
4982 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004983 * @param executor The executor on which the callback will be invoked. The provided
4984 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08004985 * callbacks cannot be guaranteed.onQosCallbackRegistered
4986 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004987 *
4988 * @hide
4989 */
4990 @SystemApi
4991 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08004992 @CallbackExecutor @NonNull final Executor executor,
4993 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004994 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004995 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08004996 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004997
4998 try {
4999 synchronized (mQosCallbackConnections) {
5000 if (getQosCallbackConnection(callback) == null) {
5001 final QosCallbackConnection connection =
5002 new QosCallbackConnection(this, callback, executor);
5003 mQosCallbackConnections.add(connection);
5004 mService.registerQosSocketCallback(socketInfo, connection);
5005 } else {
5006 Log.e(TAG, "registerQosCallback: Callback already registered");
5007 throw new QosCallbackRegistrationException();
5008 }
5009 }
5010 } catch (final RemoteException e) {
5011 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5012
5013 // The same unregister method method is called for consistency even though nothing
5014 // will be sent to the ConnectivityService since the callback was never successfully
5015 // registered.
5016 unregisterQosCallback(callback);
5017 e.rethrowFromSystemServer();
5018 } catch (final ServiceSpecificException e) {
5019 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5020 unregisterQosCallback(callback);
5021 throw convertServiceException(e);
5022 }
5023 }
5024
5025 /**
5026 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5027 * events once unregistered and can be registered a second time.
5028 * <p/>
5029 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5030 *
5031 * @param callback the callback being unregistered
5032 *
5033 * @hide
5034 */
5035 @SystemApi
5036 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5037 Objects.requireNonNull(callback, "The callback must be non-null");
5038 try {
5039 synchronized (mQosCallbackConnections) {
5040 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5041 if (connection != null) {
5042 connection.stopReceivingMessages();
5043 mService.unregisterQosCallback(connection);
5044 mQosCallbackConnections.remove(connection);
5045 } else {
5046 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5047 }
5048 }
5049 } catch (final RemoteException e) {
5050 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5051 e.rethrowFromSystemServer();
5052 }
5053 }
5054
5055 /**
5056 * Gets the connection related to the callback.
5057 *
5058 * @param callback the callback to look up
5059 * @return the related connection
5060 */
5061 @Nullable
5062 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5063 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5064 // Checking by reference here is intentional
5065 if (connection.getCallback() == callback) {
5066 return connection;
5067 }
5068 }
5069 return null;
5070 }
5071
5072 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005073 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005074 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5075 * be used to request that the system provide a network without causing the network to be
5076 * in the foreground.
5077 *
5078 * <p>This method will attempt to find the best network that matches the passed
5079 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5080 * criteria. The platform will evaluate which network is the best at its own discretion.
5081 * Throughput, latency, cost per byte, policy, user preference and other considerations
5082 * may be factored in the decision of what is considered the best network.
5083 *
5084 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5085 * matching this request, while always attempting to match the request to a better network if
5086 * possible. If a better match is found, the platform will switch this request to the now-best
5087 * network and inform the app of the newly best network by invoking
5088 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5089 * will not try to maintain any other network than the best one currently matching the request:
5090 * a network not matching any network request may be disconnected at any time.
5091 *
5092 * <p>For example, an application could use this method to obtain a connected cellular network
5093 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5094 * radio to consume additional power. Or, an application could inform the system that it wants
5095 * a network supporting sending MMSes and have the system let it know about the currently best
5096 * MMS-supporting network through the provided {@link NetworkCallback}.
5097 *
5098 * <p>The status of the request can be followed by listening to the various callbacks described
5099 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5100 * used to direct traffic to the network (although accessing some networks may be subject to
5101 * holding specific permissions). Callers will learn about the specific characteristics of the
5102 * network through
5103 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5104 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5105 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5106 * matching the request at any given time; therefore when a better network matching the request
5107 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5108 * with the new network after which no further updates are given about the previously-best
5109 * network, unless it becomes the best again at some later time. All callbacks are invoked
5110 * in order on the same thread, which by default is a thread created by the framework running
5111 * in the app.
5112 *
5113 * <p>This{@link NetworkRequest} will live until released via
5114 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5115 * which point the system may let go of the network at any time.
5116 *
5117 * <p>It is presently unsupported to request a network with mutable
5118 * {@link NetworkCapabilities} such as
5119 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5120 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5121 * as these {@code NetworkCapabilities} represent states that a particular
5122 * network may never attain, and whether a network will attain these states
5123 * is unknown prior to bringing up the network so the framework does not
5124 * know how to go about satisfying a request with these capabilities.
5125 *
5126 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5127 * number of outstanding requests to 100 per app (identified by their UID), shared with
5128 * all variants of this method, of {@link #registerNetworkCallback} as well as
5129 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5130 * Requesting a network with this method will count toward this limit. If this limit is
5131 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5132 * make sure to unregister the callbacks with
5133 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5134 *
5135 * @param request {@link NetworkRequest} describing this request.
5136 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5137 * If null, the callback is invoked on the default internal Handler.
5138 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5139 * the callback must not be shared - it uniquely specifies this request.
5140 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5141 * @throws SecurityException if missing the appropriate permissions.
5142 * @throws RuntimeException if the app already has too many callbacks registered.
5143 *
5144 * @hide
5145 */
5146 @SystemApi(client = MODULE_LIBRARIES)
5147 @SuppressLint("ExecutorRegistration")
5148 @RequiresPermission(anyOf = {
5149 android.Manifest.permission.NETWORK_SETTINGS,
5150 android.Manifest.permission.NETWORK_STACK,
5151 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5152 })
5153 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaidbb70462021-03-09 20:49:48 +08005154 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005155 final NetworkCapabilities nc = request.networkCapabilities;
5156 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005157 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005158 }
James Mattis12aeab82021-01-10 14:24:24 -08005159
5160 /**
James Mattis12aeab82021-01-10 14:24:24 -08005161 * Used by automotive devices to set the network preferences used to direct traffic at an
5162 * application level as per the given OemNetworkPreferences. An example use-case would be an
5163 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5164 * vehicle via a particular network.
5165 *
5166 * Calling this will overwrite the existing preference.
5167 *
5168 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5169 * @param executor the executor on which listener will be invoked.
5170 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5171 * communicate completion of setOemNetworkPreference(). This will only be
5172 * called once upon successful completion of setOemNetworkPreference().
5173 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5174 * @throws SecurityException if missing the appropriate permissions.
5175 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005176 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005177 */
James Mattis6e2d7022021-01-26 16:23:52 -08005178 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005179 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005180 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005181 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005182 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005183 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5184 if (null != listener) {
5185 Objects.requireNonNull(executor, "Executor must be non-null");
5186 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005187 final IOnCompleteListener listenerInternal = listener == null ? null :
5188 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005189 @Override
5190 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005191 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005192 }
5193 };
5194
5195 try {
5196 mService.setOemNetworkPreference(preference, listenerInternal);
5197 } catch (RemoteException e) {
5198 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5199 throw e.rethrowFromSystemServer();
5200 }
5201 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005202
Chalard Jeanad565e22021-02-25 17:23:40 +09005203 /**
5204 * Request that a user profile is put by default on a network matching a given preference.
5205 *
5206 * See the documentation for the individual preferences for a description of the supported
5207 * behaviors.
5208 *
5209 * @param profile the profile concerned.
5210 * @param preference the preference for this profile.
5211 * @param executor an executor to execute the listener on. Optional if listener is null.
5212 * @param listener an optional listener to listen for completion of the operation.
5213 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5214 * @throws SecurityException if missing the appropriate permissions.
5215 * @hide
5216 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005217 // This function is for establishing per-profile default networking and can only be called by
5218 // the device policy manager, running as the system server. It would make no sense to call it
5219 // on a context for a user because it does not establish a setting on behalf of a user, rather
5220 // it establishes a setting for a user on behalf of the DPM.
5221 @SuppressLint({"UserHandle"})
5222 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005223 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5224 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5225 @ProfileNetworkPreference final int preference,
5226 @Nullable @CallbackExecutor final Executor executor,
5227 @Nullable final Runnable listener) {
5228 if (null != listener) {
5229 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5230 }
5231 final IOnCompleteListener proxy;
5232 if (null == listener) {
5233 proxy = null;
5234 } else {
5235 proxy = new IOnCompleteListener.Stub() {
5236 @Override
5237 public void onComplete() {
5238 executor.execute(listener::run);
5239 }
5240 };
5241 }
5242 try {
5243 mService.setProfileNetworkPreference(profile, preference, proxy);
5244 } catch (RemoteException e) {
5245 throw e.rethrowFromSystemServer();
5246 }
5247 }
5248
lucaslin5cdbcfb2021-03-12 00:46:33 +08005249 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005250 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005251 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005252 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005253
5254 /**
5255 * Get the network ID range reserved for IPSec tunnel interfaces.
5256 *
5257 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5258 * @hide
5259 */
5260 @SystemApi(client = MODULE_LIBRARIES)
5261 @NonNull
5262 public static Range<Integer> getIpSecNetIdRange() {
5263 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5264 }
lucaslin889dcda2021-03-12 17:56:09 +08005265
5266 /**
5267 * Get private DNS mode from settings.
5268 *
lucaslindebfe602021-03-17 14:53:35 +08005269 * @param context The Context to query the private DNS mode from settings.
lucaslin889dcda2021-03-12 17:56:09 +08005270 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5271 *
5272 * @hide
5273 */
5274 @SystemApi(client = MODULE_LIBRARIES)
5275 @NonNull
5276 @PrivateDnsMode
lucasline2cd02d2021-03-16 17:11:14 +08005277 public static String getPrivateDnsMode(@NonNull Context context) {
5278 final ContentResolver cr = context.getContentResolver();
lucaslin889dcda2021-03-12 17:56:09 +08005279 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5280 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5281 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5282 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5283 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5284 return mode;
5285 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005286}