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