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