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