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