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