blob: 8b669284adc1edfbd879a6241b86e6c21f5a691b [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;
lucaslin889dcda2021-03-12 17:56:09 +080026import static android.provider.Settings.Global.PRIVATE_DNS_DEFAULT_MODE;
27import static android.provider.Settings.Global.PRIVATE_DNS_MODE;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090028
29import android.annotation.CallbackExecutor;
30import android.annotation.IntDef;
31import android.annotation.NonNull;
32import android.annotation.Nullable;
33import android.annotation.RequiresPermission;
34import android.annotation.SdkConstant;
35import android.annotation.SdkConstant.SdkConstantType;
lucaslin889dcda2021-03-12 17:56:09 +080036import android.annotation.StringDef;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090037import android.annotation.SuppressLint;
38import android.annotation.SystemApi;
39import android.annotation.SystemService;
40import android.app.PendingIntent;
41import android.compat.annotation.UnsupportedAppUsage;
lucaslin889dcda2021-03-12 17:56:09 +080042import android.content.ContentResolver;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090043import android.content.Context;
44import android.content.Intent;
45import android.net.IpSecManager.UdpEncapsulationSocket;
46import android.net.SocketKeepalive.Callback;
47import android.net.TetheringManager.StartTetheringCallback;
48import android.net.TetheringManager.TetheringEventCallback;
49import android.net.TetheringManager.TetheringRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -080050import android.net.wifi.WifiNetworkSuggestion;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090051import android.os.Binder;
52import android.os.Build;
53import android.os.Build.VERSION_CODES;
54import android.os.Bundle;
55import android.os.Handler;
56import android.os.IBinder;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090057import android.os.Looper;
58import android.os.Message;
59import android.os.Messenger;
60import android.os.ParcelFileDescriptor;
61import android.os.PersistableBundle;
62import android.os.Process;
63import android.os.RemoteException;
64import android.os.ResultReceiver;
65import android.os.ServiceManager;
66import android.os.ServiceSpecificException;
67import android.provider.Settings;
68import android.telephony.SubscriptionManager;
69import android.telephony.TelephonyManager;
lucaslin889dcda2021-03-12 17:56:09 +080070import android.text.TextUtils;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090071import android.util.ArrayMap;
72import android.util.Log;
73import android.util.Range;
74import android.util.SparseIntArray;
75
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 */
lucaslin889dcda2021-03-12 17:56:09 +0800810 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900811 public static final String PRIVATE_DNS_MODE_OFF = "off";
812 /**
813 * @hide
814 */
lucaslin889dcda2021-03-12 17:56:09 +0800815 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900816 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
817 /**
818 * @hide
819 */
lucaslin889dcda2021-03-12 17:56:09 +0800820 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900821 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin889dcda2021-03-12 17:56:09 +0800822
823 /** @hide */
824 @Retention(RetentionPolicy.SOURCE)
825 @StringDef(value = {
826 PRIVATE_DNS_MODE_OFF,
827 PRIVATE_DNS_MODE_OPPORTUNISTIC,
828 PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
829 })
830 public @interface PrivateDnsMode {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900831
832 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
833 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900834
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900835 /**
836 * A kludge to facilitate static access where a Context pointer isn't available, like in the
837 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
838 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
839 * methods that take a Context argument.
840 */
841 private static ConnectivityManager sInstance;
842
843 private final Context mContext;
844
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900845 private INetworkPolicyManager mNPManager;
846 private final TetheringManager mTetheringManager;
847
848 /**
849 * Tests if a given integer represents a valid network type.
850 * @param networkType the type to be tested
851 * @return a boolean. {@code true} if the type is valid, else {@code false}
852 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
853 * validate a network type.
854 */
855 @Deprecated
856 public static boolean isNetworkTypeValid(int networkType) {
857 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
858 }
859
860 /**
861 * Returns a non-localized string representing a given network type.
862 * ONLY used for debugging output.
863 * @param type the type needing naming
864 * @return a String for the given type, or a string version of the type ("87")
865 * if no name is known.
866 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
867 * {@hide}
868 */
869 @Deprecated
870 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
871 public static String getNetworkTypeName(int type) {
872 switch (type) {
873 case TYPE_NONE:
874 return "NONE";
875 case TYPE_MOBILE:
876 return "MOBILE";
877 case TYPE_WIFI:
878 return "WIFI";
879 case TYPE_MOBILE_MMS:
880 return "MOBILE_MMS";
881 case TYPE_MOBILE_SUPL:
882 return "MOBILE_SUPL";
883 case TYPE_MOBILE_DUN:
884 return "MOBILE_DUN";
885 case TYPE_MOBILE_HIPRI:
886 return "MOBILE_HIPRI";
887 case TYPE_WIMAX:
888 return "WIMAX";
889 case TYPE_BLUETOOTH:
890 return "BLUETOOTH";
891 case TYPE_DUMMY:
892 return "DUMMY";
893 case TYPE_ETHERNET:
894 return "ETHERNET";
895 case TYPE_MOBILE_FOTA:
896 return "MOBILE_FOTA";
897 case TYPE_MOBILE_IMS:
898 return "MOBILE_IMS";
899 case TYPE_MOBILE_CBS:
900 return "MOBILE_CBS";
901 case TYPE_WIFI_P2P:
902 return "WIFI_P2P";
903 case TYPE_MOBILE_IA:
904 return "MOBILE_IA";
905 case TYPE_MOBILE_EMERGENCY:
906 return "MOBILE_EMERGENCY";
907 case TYPE_PROXY:
908 return "PROXY";
909 case TYPE_VPN:
910 return "VPN";
911 default:
912 return Integer.toString(type);
913 }
914 }
915
916 /**
917 * @hide
918 * TODO: Expose for SystemServer when becomes a module.
919 */
920 public void systemReady() {
921 try {
922 mService.systemReady();
923 } catch (RemoteException e) {
924 throw e.rethrowFromSystemServer();
925 }
926 }
927
928 /**
929 * Checks if a given type uses the cellular data connection.
930 * This should be replaced in the future by a network property.
931 * @param networkType the type to check
932 * @return a boolean - {@code true} if uses cellular network, else {@code false}
933 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
934 * {@hide}
935 */
936 @Deprecated
937 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
938 public static boolean isNetworkTypeMobile(int networkType) {
939 switch (networkType) {
940 case TYPE_MOBILE:
941 case TYPE_MOBILE_MMS:
942 case TYPE_MOBILE_SUPL:
943 case TYPE_MOBILE_DUN:
944 case TYPE_MOBILE_HIPRI:
945 case TYPE_MOBILE_FOTA:
946 case TYPE_MOBILE_IMS:
947 case TYPE_MOBILE_CBS:
948 case TYPE_MOBILE_IA:
949 case TYPE_MOBILE_EMERGENCY:
950 return true;
951 default:
952 return false;
953 }
954 }
955
956 /**
957 * Checks if the given network type is backed by a Wi-Fi radio.
958 *
959 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
960 * @hide
961 */
962 @Deprecated
963 public static boolean isNetworkTypeWifi(int networkType) {
964 switch (networkType) {
965 case TYPE_WIFI:
966 case TYPE_WIFI_P2P:
967 return true;
968 default:
969 return false;
970 }
971 }
972
973 /**
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() {
Roshan Piusa8a477b2020-12-17 14:53:09 -08002117 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,
2295 throwException);
2296 }
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
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003216 /**
3217 * @hide
3218 * Register a NetworkAgent with ConnectivityService.
3219 * @return Network corresponding to NetworkAgent.
3220 */
3221 @RequiresPermission(anyOf = {
3222 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3223 android.Manifest.permission.NETWORK_FACTORY})
3224 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003225 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3226 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003227 try {
3228 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3229 } catch (RemoteException e) {
3230 throw e.rethrowFromSystemServer();
3231 }
3232 }
3233
3234 /**
3235 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3236 * changes. Should be extended by applications wanting notifications.
3237 *
3238 * A {@code NetworkCallback} is registered by calling
3239 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3240 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3241 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3242 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3243 * A {@code NetworkCallback} should be registered at most once at any time.
3244 * A {@code NetworkCallback} that has been unregistered can be registered again.
3245 */
3246 public static class NetworkCallback {
3247 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003248 * No flags associated with this callback.
3249 * @hide
3250 */
3251 public static final int FLAG_NONE = 0;
3252 /**
3253 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3254 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3255 * <p>
3256 * These include:
3257 * <li> Some transport info instances (retrieved via
3258 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3259 * contain location sensitive information.
3260 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3261 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3262 * </p>
3263 * <p>
3264 * Note:
3265 * <li> Retrieving this location sensitive information (subject to app's location
3266 * permissions) will be noted by system. </li>
3267 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3268 * not include location sensitive info.
3269 * </p>
3270 */
3271 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3272
3273 /** @hide */
3274 @Retention(RetentionPolicy.SOURCE)
3275 @IntDef(flag = true, prefix = "FLAG_", value = {
3276 FLAG_NONE,
3277 FLAG_INCLUDE_LOCATION_INFO
3278 })
3279 public @interface Flag { }
3280
3281 /**
3282 * All the valid flags for error checking.
3283 */
3284 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3285
3286 public NetworkCallback() {
3287 this(FLAG_NONE);
3288 }
3289
3290 public NetworkCallback(@Flag int flags) {
3291 Preconditions.checkArgument((flags & VALID_FLAGS) == flags);
3292 mFlags = flags;
3293 }
3294
3295 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003296 * Called when the framework connects to a new network to evaluate whether it satisfies this
3297 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3298 * callback. There is no guarantee that this new network will satisfy any requests, or that
3299 * the network will stay connected for longer than the time necessary to evaluate it.
3300 * <p>
3301 * Most applications <b>should not</b> act on this callback, and should instead use
3302 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3303 * the framework in properly evaluating the network &mdash; for example, an application that
3304 * can automatically log in to a captive portal without user intervention.
3305 *
3306 * @param network The {@link Network} of the network that is being evaluated.
3307 *
3308 * @hide
3309 */
3310 public void onPreCheck(@NonNull Network network) {}
3311
3312 /**
3313 * Called when the framework connects and has declared a new network ready for use.
3314 * This callback may be called more than once if the {@link Network} that is
3315 * satisfying the request changes.
3316 *
3317 * @param network The {@link Network} of the satisfying network.
3318 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3319 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3320 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3321 * @hide
3322 */
3323 public void onAvailable(@NonNull Network network,
3324 @NonNull NetworkCapabilities networkCapabilities,
3325 @NonNull LinkProperties linkProperties, boolean blocked) {
3326 // Internally only this method is called when a new network is available, and
3327 // it calls the callback in the same way and order that older versions used
3328 // to call so as not to change the behavior.
3329 onAvailable(network);
3330 if (!networkCapabilities.hasCapability(
3331 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3332 onNetworkSuspended(network);
3333 }
3334 onCapabilitiesChanged(network, networkCapabilities);
3335 onLinkPropertiesChanged(network, linkProperties);
3336 onBlockedStatusChanged(network, blocked);
3337 }
3338
3339 /**
3340 * Called when the framework connects and has declared a new network ready for use.
3341 *
3342 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3343 * be available at the same time, and onAvailable will be called for each of these as they
3344 * appear.
3345 *
3346 * <p>For callbacks registered with {@link #requestNetwork} and
3347 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3348 * is the new best network for this request and is now tracked by this callback ; this
3349 * callback will no longer receive method calls about other networks that may have been
3350 * passed to this method previously. The previously-best network may have disconnected, or
3351 * it may still be around and the newly-best network may simply be better.
3352 *
3353 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3354 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3355 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3356 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3357 *
3358 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3359 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3360 * this callback as this is prone to race conditions (there is no guarantee the objects
3361 * returned by these methods will be current). Instead, wait for a call to
3362 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3363 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3364 * to be well-ordered with respect to other callbacks.
3365 *
3366 * @param network The {@link Network} of the satisfying network.
3367 */
3368 public void onAvailable(@NonNull Network network) {}
3369
3370 /**
3371 * Called when the network is about to be lost, typically because there are no outstanding
3372 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3373 * with the new replacement network for graceful handover. This method is not guaranteed
3374 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3375 * network is suddenly disconnected.
3376 *
3377 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3378 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3379 * this callback as this is prone to race conditions ; calling these methods while in a
3380 * callback may return an outdated or even a null object.
3381 *
3382 * @param network The {@link Network} that is about to be lost.
3383 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3384 * connected for graceful handover; note that the network may still
3385 * suffer a hard loss at any time.
3386 */
3387 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3388
3389 /**
3390 * Called when a network disconnects or otherwise no longer satisfies this request or
3391 * callback.
3392 *
3393 * <p>If the callback was registered with requestNetwork() or
3394 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3395 * returned by onAvailable() when that network is lost and no other network satisfies
3396 * the criteria of the request.
3397 *
3398 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3399 * each network which no longer satisfies the criteria of the callback.
3400 *
3401 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3402 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3403 * this callback as this is prone to race conditions ; calling these methods while in a
3404 * callback may return an outdated or even a null object.
3405 *
3406 * @param network The {@link Network} lost.
3407 */
3408 public void onLost(@NonNull Network network) {}
3409
3410 /**
3411 * Called if no network is found within the timeout time specified in
3412 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3413 * requested network request cannot be fulfilled (whether or not a timeout was
3414 * specified). When this callback is invoked the associated
3415 * {@link NetworkRequest} will have already been removed and released, as if
3416 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3417 */
3418 public void onUnavailable() {}
3419
3420 /**
3421 * Called when the network corresponding to this request changes capabilities but still
3422 * satisfies the requested criteria.
3423 *
3424 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3425 * to be called immediately after {@link #onAvailable}.
3426 *
3427 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3428 * ConnectivityManager methods in this callback as this is prone to race conditions :
3429 * calling these methods while in a callback may return an outdated or even a null object.
3430 *
3431 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003432 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003433 * network.
3434 */
3435 public void onCapabilitiesChanged(@NonNull Network network,
3436 @NonNull NetworkCapabilities networkCapabilities) {}
3437
3438 /**
3439 * Called when the network corresponding to this request changes {@link LinkProperties}.
3440 *
3441 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3442 * to be called immediately after {@link #onAvailable}.
3443 *
3444 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3445 * ConnectivityManager methods in this callback as this is prone to race conditions :
3446 * calling these methods while in a callback may return an outdated or even a null object.
3447 *
3448 * @param network The {@link Network} whose link properties have changed.
3449 * @param linkProperties The new {@link LinkProperties} for this network.
3450 */
3451 public void onLinkPropertiesChanged(@NonNull Network network,
3452 @NonNull LinkProperties linkProperties) {}
3453
3454 /**
3455 * Called when the network the framework connected to for this request suspends data
3456 * transmission temporarily.
3457 *
3458 * <p>This generally means that while the TCP connections are still live temporarily
3459 * network data fails to transfer. To give a specific example, this is used on cellular
3460 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3461 * means read operations on sockets on this network will block once the buffers are
3462 * drained, and write operations will block once the buffers are full.
3463 *
3464 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3465 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3466 * this callback as this is prone to race conditions (there is no guarantee the objects
3467 * returned by these methods will be current).
3468 *
3469 * @hide
3470 */
3471 public void onNetworkSuspended(@NonNull Network network) {}
3472
3473 /**
3474 * Called when the network the framework connected to for this request
3475 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3476 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3477
3478 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3479 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3480 * this callback as this is prone to race conditions : calling these methods while in a
3481 * callback may return an outdated or even a null object.
3482 *
3483 * @hide
3484 */
3485 public void onNetworkResumed(@NonNull Network network) {}
3486
3487 /**
3488 * Called when access to the specified network is blocked or unblocked.
3489 *
3490 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3491 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3492 * this callback as this is prone to race conditions : calling these methods while in a
3493 * callback may return an outdated or even a null object.
3494 *
3495 * @param network The {@link Network} whose blocked status has changed.
3496 * @param blocked The blocked status of this {@link Network}.
3497 */
3498 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3499
3500 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08003501 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003502 }
3503
3504 /**
3505 * Constant error codes used by ConnectivityService to communicate about failures and errors
3506 * across a Binder boundary.
3507 * @hide
3508 */
3509 public interface Errors {
3510 int TOO_MANY_REQUESTS = 1;
3511 }
3512
3513 /** @hide */
3514 public static class TooManyRequestsException extends RuntimeException {}
3515
3516 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3517 switch (e.errorCode) {
3518 case Errors.TOO_MANY_REQUESTS:
3519 return new TooManyRequestsException();
3520 default:
3521 Log.w(TAG, "Unknown service error code " + e.errorCode);
3522 return new RuntimeException(e);
3523 }
3524 }
3525
3526 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
3527 /** @hide */
3528 public static final int CALLBACK_PRECHECK = BASE + 1;
3529 /** @hide */
3530 public static final int CALLBACK_AVAILABLE = BASE + 2;
3531 /** @hide arg1 = TTL */
3532 public static final int CALLBACK_LOSING = BASE + 3;
3533 /** @hide */
3534 public static final int CALLBACK_LOST = BASE + 4;
3535 /** @hide */
3536 public static final int CALLBACK_UNAVAIL = BASE + 5;
3537 /** @hide */
3538 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3539 /** @hide */
3540 public static final int CALLBACK_IP_CHANGED = BASE + 7;
3541 /** @hide obj = NetworkCapabilities, arg1 = seq number */
3542 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
3543 /** @hide */
3544 public static final int CALLBACK_SUSPENDED = BASE + 9;
3545 /** @hide */
3546 public static final int CALLBACK_RESUMED = BASE + 10;
3547 /** @hide */
3548 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
3549
3550 /** @hide */
3551 public static String getCallbackName(int whichCallback) {
3552 switch (whichCallback) {
3553 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3554 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3555 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3556 case CALLBACK_LOST: return "CALLBACK_LOST";
3557 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3558 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3559 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
3560 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3561 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3562 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
3563 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
3564 default:
3565 return Integer.toString(whichCallback);
3566 }
3567 }
3568
3569 private class CallbackHandler extends Handler {
3570 private static final String TAG = "ConnectivityManager.CallbackHandler";
3571 private static final boolean DBG = false;
3572
3573 CallbackHandler(Looper looper) {
3574 super(looper);
3575 }
3576
3577 CallbackHandler(Handler handler) {
Remi NGUYEN VAN3f0e7dd2021-03-15 07:27:44 +00003578 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003579 }
3580
3581 @Override
3582 public void handleMessage(Message message) {
3583 if (message.what == EXPIRE_LEGACY_REQUEST) {
3584 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3585 return;
3586 }
3587
3588 final NetworkRequest request = getObject(message, NetworkRequest.class);
3589 final Network network = getObject(message, Network.class);
3590 final NetworkCallback callback;
3591 synchronized (sCallbacks) {
3592 callback = sCallbacks.get(request);
3593 if (callback == null) {
3594 Log.w(TAG,
3595 "callback not found for " + getCallbackName(message.what) + " message");
3596 return;
3597 }
3598 if (message.what == CALLBACK_UNAVAIL) {
3599 sCallbacks.remove(request);
3600 callback.networkRequest = ALREADY_UNREGISTERED;
3601 }
3602 }
3603 if (DBG) {
3604 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
3605 }
3606
3607 switch (message.what) {
3608 case CALLBACK_PRECHECK: {
3609 callback.onPreCheck(network);
3610 break;
3611 }
3612 case CALLBACK_AVAILABLE: {
3613 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3614 LinkProperties lp = getObject(message, LinkProperties.class);
3615 callback.onAvailable(network, cap, lp, message.arg1 != 0);
3616 break;
3617 }
3618 case CALLBACK_LOSING: {
3619 callback.onLosing(network, message.arg1);
3620 break;
3621 }
3622 case CALLBACK_LOST: {
3623 callback.onLost(network);
3624 break;
3625 }
3626 case CALLBACK_UNAVAIL: {
3627 callback.onUnavailable();
3628 break;
3629 }
3630 case CALLBACK_CAP_CHANGED: {
3631 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3632 callback.onCapabilitiesChanged(network, cap);
3633 break;
3634 }
3635 case CALLBACK_IP_CHANGED: {
3636 LinkProperties lp = getObject(message, LinkProperties.class);
3637 callback.onLinkPropertiesChanged(network, lp);
3638 break;
3639 }
3640 case CALLBACK_SUSPENDED: {
3641 callback.onNetworkSuspended(network);
3642 break;
3643 }
3644 case CALLBACK_RESUMED: {
3645 callback.onNetworkResumed(network);
3646 break;
3647 }
3648 case CALLBACK_BLK_CHANGED: {
3649 boolean blocked = message.arg1 != 0;
3650 callback.onBlockedStatusChanged(network, blocked);
3651 }
3652 }
3653 }
3654
3655 private <T> T getObject(Message msg, Class<T> c) {
3656 return (T) msg.getData().getParcelable(c.getSimpleName());
3657 }
3658 }
3659
3660 private CallbackHandler getDefaultHandler() {
3661 synchronized (sCallbacks) {
3662 if (sCallbackHandler == null) {
3663 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
3664 }
3665 return sCallbackHandler;
3666 }
3667 }
3668
3669 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3670 private static CallbackHandler sCallbackHandler;
3671
3672 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3673 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3674 printStackTrace();
3675 checkCallbackNotNull(callback);
Remi NGUYEN VAN3f0e7dd2021-03-15 07:27:44 +00003676 Preconditions.checkArgument(
3677 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3678 "null NetworkCapabilities");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003679 final NetworkRequest request;
3680 final String callingPackageName = mContext.getOpPackageName();
3681 try {
3682 synchronized(sCallbacks) {
3683 if (callback.networkRequest != null
3684 && callback.networkRequest != ALREADY_UNREGISTERED) {
3685 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3686 // and requests (http://b/20701525).
3687 Log.e(TAG, "NetworkCallback was already registered");
3688 }
3689 Messenger messenger = new Messenger(handler);
3690 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08003691 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003692 if (reqType == LISTEN) {
3693 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08003694 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08003695 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003696 } else {
3697 request = mService.requestNetwork(
3698 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
Roshan Piuse08bc182020-12-22 15:10:42 -08003699 callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003700 }
3701 if (request != null) {
3702 sCallbacks.put(request, callback);
3703 }
3704 callback.networkRequest = request;
3705 }
3706 } catch (RemoteException e) {
3707 throw e.rethrowFromSystemServer();
3708 } catch (ServiceSpecificException e) {
3709 throw convertServiceException(e);
3710 }
3711 return request;
3712 }
3713
3714 /**
3715 * Helper function to request a network with a particular legacy type.
3716 *
3717 * This API is only for use in internal system code that requests networks with legacy type and
3718 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
3719 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
3720 *
3721 * @param request {@link NetworkRequest} describing this request.
3722 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3723 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3724 * be a positive value (i.e. >0).
3725 * @param legacyType to specify the network type(#TYPE_*).
3726 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3727 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3728 * the callback must not be shared - it uniquely specifies this request.
3729 *
3730 * @hide
3731 */
3732 @SystemApi
3733 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
3734 public void requestNetwork(@NonNull NetworkRequest request,
3735 int timeoutMs, int legacyType, @NonNull Handler handler,
3736 @NonNull NetworkCallback networkCallback) {
3737 if (legacyType == TYPE_NONE) {
3738 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3739 }
3740 CallbackHandler cbHandler = new CallbackHandler(handler);
3741 NetworkCapabilities nc = request.networkCapabilities;
3742 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
3743 }
3744
3745 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003746 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003747 *
3748 * <p>This method will attempt to find the best network that matches the passed
3749 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3750 * criteria. The platform will evaluate which network is the best at its own discretion.
3751 * Throughput, latency, cost per byte, policy, user preference and other considerations
3752 * may be factored in the decision of what is considered the best network.
3753 *
3754 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3755 * matching this request, while always attempting to match the request to a better network if
3756 * possible. If a better match is found, the platform will switch this request to the now-best
3757 * network and inform the app of the newly best network by invoking
3758 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3759 * will not try to maintain any other network than the best one currently matching the request:
3760 * a network not matching any network request may be disconnected at any time.
3761 *
3762 * <p>For example, an application could use this method to obtain a connected cellular network
3763 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3764 * radio to consume additional power. Or, an application could inform the system that it wants
3765 * a network supporting sending MMSes and have the system let it know about the currently best
3766 * MMS-supporting network through the provided {@link NetworkCallback}.
3767 *
3768 * <p>The status of the request can be followed by listening to the various callbacks described
3769 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3770 * used to direct traffic to the network (although accessing some networks may be subject to
3771 * holding specific permissions). Callers will learn about the specific characteristics of the
3772 * network through
3773 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3774 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3775 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3776 * matching the request at any given time; therefore when a better network matching the request
3777 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3778 * with the new network after which no further updates are given about the previously-best
3779 * network, unless it becomes the best again at some later time. All callbacks are invoked
3780 * in order on the same thread, which by default is a thread created by the framework running
3781 * in the app.
3782 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3783 * callbacks are invoked.
3784 *
3785 * <p>This{@link NetworkRequest} will live until released via
3786 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3787 * which point the system may let go of the network at any time.
3788 *
3789 * <p>A version of this method which takes a timeout is
3790 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3791 * wait for a limited amount of time for the network to become unavailable.
3792 *
3793 * <p>It is presently unsupported to request a network with mutable
3794 * {@link NetworkCapabilities} such as
3795 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3796 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3797 * as these {@code NetworkCapabilities} represent states that a particular
3798 * network may never attain, and whether a network will attain these states
3799 * is unknown prior to bringing up the network so the framework does not
3800 * know how to go about satisfying a request with these capabilities.
3801 *
3802 * <p>This method requires the caller to hold either the
3803 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3804 * or the ability to modify system settings as determined by
3805 * {@link android.provider.Settings.System#canWrite}.</p>
3806 *
3807 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3808 * number of outstanding requests to 100 per app (identified by their UID), shared with
3809 * all variants of this method, of {@link #registerNetworkCallback} as well as
3810 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3811 * Requesting a network with this method will count toward this limit. If this limit is
3812 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3813 * make sure to unregister the callbacks with
3814 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3815 *
3816 * @param request {@link NetworkRequest} describing this request.
3817 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3818 * the callback must not be shared - it uniquely specifies this request.
3819 * The callback is invoked on the default internal Handler.
3820 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3821 * @throws SecurityException if missing the appropriate permissions.
3822 * @throws RuntimeException if the app already has too many callbacks registered.
3823 */
3824 public void requestNetwork(@NonNull NetworkRequest request,
3825 @NonNull NetworkCallback networkCallback) {
3826 requestNetwork(request, networkCallback, getDefaultHandler());
3827 }
3828
3829 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003830 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003831 *
3832 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3833 * but runs all the callbacks on the passed Handler.
3834 *
3835 * <p>This method has the same permission requirements as
3836 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3837 * and throws the same exceptions in the same conditions.
3838 *
3839 * @param request {@link NetworkRequest} describing this request.
3840 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3841 * the callback must not be shared - it uniquely specifies this request.
3842 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3843 */
3844 public void requestNetwork(@NonNull NetworkRequest request,
3845 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
3846 CallbackHandler cbHandler = new CallbackHandler(handler);
3847 NetworkCapabilities nc = request.networkCapabilities;
3848 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
3849 }
3850
3851 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003852 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003853 * by a timeout.
3854 *
3855 * This function behaves identically to the non-timed-out version
3856 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3857 * is not found within the given time (in milliseconds) the
3858 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3859 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3860 * not have to be released if timed-out (it is automatically released). Unregistering a
3861 * request that timed out is not an error.
3862 *
3863 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3864 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3865 * for that purpose. Calling this method will attempt to bring up the requested network.
3866 *
3867 * <p>This method has the same permission requirements as
3868 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3869 * and throws the same exceptions in the same conditions.
3870 *
3871 * @param request {@link NetworkRequest} describing this request.
3872 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3873 * the callback must not be shared - it uniquely specifies this request.
3874 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3875 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3876 * be a positive value (i.e. >0).
3877 */
3878 public void requestNetwork(@NonNull NetworkRequest request,
3879 @NonNull NetworkCallback networkCallback, int timeoutMs) {
3880 checkTimeout(timeoutMs);
3881 NetworkCapabilities nc = request.networkCapabilities;
3882 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3883 getDefaultHandler());
3884 }
3885
3886 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003887 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003888 * by a timeout.
3889 *
3890 * This method behaves identically to
3891 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3892 * on the passed Handler.
3893 *
3894 * <p>This method has the same permission requirements as
3895 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3896 * and throws the same exceptions in the same conditions.
3897 *
3898 * @param request {@link NetworkRequest} describing this request.
3899 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3900 * the callback must not be shared - it uniquely specifies this request.
3901 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3902 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3903 * before {@link NetworkCallback#onUnavailable} is called.
3904 */
3905 public void requestNetwork(@NonNull NetworkRequest request,
3906 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
3907 checkTimeout(timeoutMs);
3908 CallbackHandler cbHandler = new CallbackHandler(handler);
3909 NetworkCapabilities nc = request.networkCapabilities;
3910 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
3911 }
3912
3913 /**
3914 * The lookup key for a {@link Network} object included with the intent after
3915 * successfully finding a network for the applications request. Retrieve it with
3916 * {@link android.content.Intent#getParcelableExtra(String)}.
3917 * <p>
3918 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3919 * then you must get a ConnectivityManager instance before doing so.
3920 */
3921 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
3922
3923 /**
3924 * The lookup key for a {@link NetworkRequest} object included with the intent after
3925 * successfully finding a network for the applications request. Retrieve it with
3926 * {@link android.content.Intent#getParcelableExtra(String)}.
3927 */
3928 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
3929
3930
3931 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003932 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003933 *
3934 * This function behaves identically to the version that takes a NetworkCallback, but instead
3935 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3936 * the request may outlive the calling application and get called back when a suitable
3937 * network is found.
3938 * <p>
3939 * The operation is an Intent broadcast that goes to a broadcast receiver that
3940 * you registered with {@link Context#registerReceiver} or through the
3941 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3942 * <p>
3943 * The operation Intent is delivered with two extras, a {@link Network} typed
3944 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3945 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3946 * the original requests parameters. It is important to create a new,
3947 * {@link NetworkCallback} based request before completing the processing of the
3948 * Intent to reserve the network or it will be released shortly after the Intent
3949 * is processed.
3950 * <p>
3951 * If there is already a request for this Intent registered (with the equality of
3952 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3953 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3954 * <p>
3955 * The request may be released normally by calling
3956 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
3957 * <p>It is presently unsupported to request a network with either
3958 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3959 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3960 * as these {@code NetworkCapabilities} represent states that a particular
3961 * network may never attain, and whether a network will attain these states
3962 * is unknown prior to bringing up the network so the framework does not
3963 * know how to go about satisfying a request with these capabilities.
3964 *
3965 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3966 * number of outstanding requests to 100 per app (identified by their UID), shared with
3967 * all variants of this method, of {@link #registerNetworkCallback} as well as
3968 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3969 * Requesting a network with this method will count toward this limit. If this limit is
3970 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3971 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3972 * or {@link #releaseNetworkRequest(PendingIntent)}.
3973 *
3974 * <p>This method requires the caller to hold either the
3975 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3976 * or the ability to modify system settings as determined by
3977 * {@link android.provider.Settings.System#canWrite}.</p>
3978 *
3979 * @param request {@link NetworkRequest} describing this request.
3980 * @param operation Action to perform when the network is available (corresponds
3981 * to the {@link NetworkCallback#onAvailable} call. Typically
3982 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3983 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3984 * @throws SecurityException if missing the appropriate permissions.
3985 * @throws RuntimeException if the app already has too many callbacks registered.
3986 */
3987 public void requestNetwork(@NonNull NetworkRequest request,
3988 @NonNull PendingIntent operation) {
3989 printStackTrace();
3990 checkPendingIntentNotNull(operation);
3991 try {
3992 mService.pendingRequestForNetwork(
3993 request.networkCapabilities, operation, mContext.getOpPackageName(),
3994 getAttributionTag());
3995 } catch (RemoteException e) {
3996 throw e.rethrowFromSystemServer();
3997 } catch (ServiceSpecificException e) {
3998 throw convertServiceException(e);
3999 }
4000 }
4001
4002 /**
4003 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4004 * <p>
4005 * This method has the same behavior as
4006 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4007 * releasing network resources and disconnecting.
4008 *
4009 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4010 * PendingIntent passed to
4011 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4012 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4013 */
4014 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4015 printStackTrace();
4016 checkPendingIntentNotNull(operation);
4017 try {
4018 mService.releasePendingNetworkRequest(operation);
4019 } catch (RemoteException e) {
4020 throw e.rethrowFromSystemServer();
4021 }
4022 }
4023
4024 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN3f0e7dd2021-03-15 07:27:44 +00004025 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004026 }
4027
4028 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN3f0e7dd2021-03-15 07:27:44 +00004029 Preconditions.checkNotNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004030 }
4031
4032 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN3f0e7dd2021-03-15 07:27:44 +00004033 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004034 }
4035
4036 /**
4037 * Registers to receive notifications about all networks which satisfy the given
4038 * {@link NetworkRequest}. The callbacks will continue to be called until
4039 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4040 * called.
4041 *
4042 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4043 * number of outstanding requests to 100 per app (identified by their UID), shared with
4044 * all variants of this method, of {@link #requestNetwork} as well as
4045 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4046 * Requesting a network with this method will count toward this limit. If this limit is
4047 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4048 * make sure to unregister the callbacks with
4049 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4050 *
4051 * @param request {@link NetworkRequest} describing this request.
4052 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4053 * networks change state.
4054 * The callback is invoked on the default internal Handler.
4055 * @throws RuntimeException if the app already has too many callbacks registered.
4056 */
4057 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4058 public void registerNetworkCallback(@NonNull NetworkRequest request,
4059 @NonNull NetworkCallback networkCallback) {
4060 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4061 }
4062
4063 /**
4064 * Registers to receive notifications about all networks which satisfy the given
4065 * {@link NetworkRequest}. The callbacks will continue to be called until
4066 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4067 * called.
4068 *
4069 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4070 * number of outstanding requests to 100 per app (identified by their UID), shared with
4071 * all variants of this method, of {@link #requestNetwork} as well as
4072 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4073 * Requesting a network with this method will count toward this limit. If this limit is
4074 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4075 * make sure to unregister the callbacks with
4076 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4077 *
4078 *
4079 * @param request {@link NetworkRequest} describing this request.
4080 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4081 * networks change state.
4082 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4083 * @throws RuntimeException if the app already has too many callbacks registered.
4084 */
4085 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4086 public void registerNetworkCallback(@NonNull NetworkRequest request,
4087 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4088 CallbackHandler cbHandler = new CallbackHandler(handler);
4089 NetworkCapabilities nc = request.networkCapabilities;
4090 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4091 }
4092
4093 /**
4094 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4095 * {@link NetworkRequest}.
4096 *
4097 * This function behaves identically to the version that takes a NetworkCallback, but instead
4098 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4099 * the request may outlive the calling application and get called back when a suitable
4100 * network is found.
4101 * <p>
4102 * The operation is an Intent broadcast that goes to a broadcast receiver that
4103 * you registered with {@link Context#registerReceiver} or through the
4104 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4105 * <p>
4106 * The operation Intent is delivered with two extras, a {@link Network} typed
4107 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4108 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4109 * the original requests parameters.
4110 * <p>
4111 * If there is already a request for this Intent registered (with the equality of
4112 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4113 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4114 * <p>
4115 * The request may be released normally by calling
4116 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4117 *
4118 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4119 * number of outstanding requests to 100 per app (identified by their UID), shared with
4120 * all variants of this method, of {@link #requestNetwork} as well as
4121 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4122 * Requesting a network with this method will count toward this limit. If this limit is
4123 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4124 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4125 * or {@link #releaseNetworkRequest(PendingIntent)}.
4126 *
4127 * @param request {@link NetworkRequest} describing this request.
4128 * @param operation Action to perform when the network is available (corresponds
4129 * to the {@link NetworkCallback#onAvailable} call. Typically
4130 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4131 * @throws RuntimeException if the app already has too many callbacks registered.
4132 */
4133 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4134 public void registerNetworkCallback(@NonNull NetworkRequest request,
4135 @NonNull PendingIntent operation) {
4136 printStackTrace();
4137 checkPendingIntentNotNull(operation);
4138 try {
4139 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004140 request.networkCapabilities, operation, mContext.getOpPackageName(),
4141 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004142 } catch (RemoteException e) {
4143 throw e.rethrowFromSystemServer();
4144 } catch (ServiceSpecificException e) {
4145 throw convertServiceException(e);
4146 }
4147 }
4148
4149 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004150 * Registers to receive notifications about changes in the application's default network. This
4151 * may be a physical network or a virtual network, such as a VPN that applies to the
4152 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004153 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4154 *
4155 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4156 * number of outstanding requests to 100 per app (identified by their UID), shared with
4157 * all variants of this method, of {@link #requestNetwork} as well as
4158 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4159 * Requesting a network with this method will count toward this limit. If this limit is
4160 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4161 * make sure to unregister the callbacks with
4162 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4163 *
4164 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004165 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004166 * The callback is invoked on the default internal Handler.
4167 * @throws RuntimeException if the app already has too many callbacks registered.
4168 */
4169 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4170 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4171 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4172 }
4173
4174 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004175 * Registers to receive notifications about changes in the application's default network. This
4176 * may be a physical network or a virtual network, such as a VPN that applies to the
4177 * application. The callbacks will continue to be called until either the application exits or
4178 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4179 *
4180 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4181 * number of outstanding requests to 100 per app (identified by their UID), shared with
4182 * all variants of this method, of {@link #requestNetwork} as well as
4183 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4184 * Requesting a network with this method will count toward this limit. If this limit is
4185 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4186 * make sure to unregister the callbacks with
4187 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4188 *
4189 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4190 * application's default network changes.
4191 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4192 * @throws RuntimeException if the app already has too many callbacks registered.
4193 */
4194 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4195 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4196 @NonNull Handler handler) {
4197 CallbackHandler cbHandler = new CallbackHandler(handler);
4198 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4199 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4200 }
4201
4202 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004203 * Registers to receive notifications about changes in the system default network. The callbacks
4204 * will continue to be called until either the application exits or
4205 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4206 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004207 * This method should not be used to determine networking state seen by applications, because in
4208 * many cases, most or even all application traffic may not use the default network directly,
4209 * and traffic from different applications may go on different networks by default. As an
4210 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4211 * and not onto the system default network. Applications or system components desiring to do
4212 * determine network state as seen by applications should use other methods such as
4213 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4214 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004215 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4216 * number of outstanding requests to 100 per app (identified by their UID), shared with
4217 * all variants of this method, of {@link #requestNetwork} as well as
4218 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4219 * Requesting a network with this method will count toward this limit. If this limit is
4220 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4221 * make sure to unregister the callbacks with
4222 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4223 *
4224 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4225 * system default network changes.
4226 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4227 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004228 *
4229 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004230 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004231 @SystemApi(client = MODULE_LIBRARIES)
4232 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4233 @RequiresPermission(anyOf = {
4234 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4235 android.Manifest.permission.NETWORK_SETTINGS})
4236 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004237 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004238 CallbackHandler cbHandler = new CallbackHandler(handler);
4239 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004240 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004241 }
4242
4243 /**
junyulai5a5c99b2021-03-05 15:51:17 +08004244 * @hide
4245 */
4246 // TODO: Make it public api.
4247 @SuppressLint("ExecutorRegistration")
4248 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4249 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4250 final NetworkCapabilities nc = request.networkCapabilities;
4251 final CallbackHandler cbHandler = new CallbackHandler(handler);
4252 sendRequestForNetwork(nc, networkCallback, 0, TRACK_BEST, TYPE_NONE, cbHandler);
4253 }
4254
4255 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004256 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4257 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4258 * network connection for updated bandwidth information. The caller will be notified via
4259 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4260 * method assumes that the caller has previously called
4261 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4262 * changes.
4263 *
4264 * @param network {@link Network} specifying which network you're interested.
4265 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4266 */
4267 public boolean requestBandwidthUpdate(@NonNull Network network) {
4268 try {
4269 return mService.requestBandwidthUpdate(network);
4270 } catch (RemoteException e) {
4271 throw e.rethrowFromSystemServer();
4272 }
4273 }
4274
4275 /**
4276 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4277 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4278 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4279 * If the given {@code NetworkCallback} had previously been used with
4280 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4281 * will be disconnected.
4282 *
4283 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4284 * triggering it as soon as this call returns.
4285 *
4286 * @param networkCallback The {@link NetworkCallback} used when making the request.
4287 */
4288 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4289 printStackTrace();
4290 checkCallbackNotNull(networkCallback);
4291 final List<NetworkRequest> reqs = new ArrayList<>();
4292 // Find all requests associated to this callback and stop callback triggers immediately.
4293 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4294 synchronized (sCallbacks) {
Remi NGUYEN VAN3f0e7dd2021-03-15 07:27:44 +00004295 Preconditions.checkArgument(networkCallback.networkRequest != null,
4296 "NetworkCallback was not registered");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004297 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4298 Log.d(TAG, "NetworkCallback was already unregistered");
4299 return;
4300 }
4301 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4302 if (e.getValue() == networkCallback) {
4303 reqs.add(e.getKey());
4304 }
4305 }
4306 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4307 for (NetworkRequest r : reqs) {
4308 try {
4309 mService.releaseNetworkRequest(r);
4310 } catch (RemoteException e) {
4311 throw e.rethrowFromSystemServer();
4312 }
4313 // Only remove mapping if rpc was successful.
4314 sCallbacks.remove(r);
4315 }
4316 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4317 }
4318 }
4319
4320 /**
4321 * Unregisters a callback previously registered via
4322 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4323 *
4324 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4325 * PendingIntent passed to
4326 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4327 * Cannot be null.
4328 */
4329 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4330 releaseNetworkRequest(operation);
4331 }
4332
4333 /**
4334 * Informs the system whether it should switch to {@code network} regardless of whether it is
4335 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4336 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4337 * the system default network regardless of any other network that's currently connected. If
4338 * {@code always} is true, then the choice is remembered, so that the next time the user
4339 * connects to this network, the system will switch to it.
4340 *
4341 * @param network The network to accept.
4342 * @param accept Whether to accept the network even if unvalidated.
4343 * @param always Whether to remember this choice in the future.
4344 *
4345 * @hide
4346 */
4347 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4348 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4349 try {
4350 mService.setAcceptUnvalidated(network, accept, always);
4351 } catch (RemoteException e) {
4352 throw e.rethrowFromSystemServer();
4353 }
4354 }
4355
4356 /**
4357 * Informs the system whether it should consider the network as validated even if it only has
4358 * partial connectivity. If {@code accept} is true, then the network will be considered as
4359 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4360 * is remembered, so that the next time the user connects to this network, the system will
4361 * switch to it.
4362 *
4363 * @param network The network to accept.
4364 * @param accept Whether to consider the network as validated even if it has partial
4365 * connectivity.
4366 * @param always Whether to remember this choice in the future.
4367 *
4368 * @hide
4369 */
4370 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4371 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4372 try {
4373 mService.setAcceptPartialConnectivity(network, accept, always);
4374 } catch (RemoteException e) {
4375 throw e.rethrowFromSystemServer();
4376 }
4377 }
4378
4379 /**
4380 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4381 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4382 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4383 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4384 *
4385 * @param network The network to accept.
4386 *
4387 * @hide
4388 */
4389 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4390 public void setAvoidUnvalidated(Network network) {
4391 try {
4392 mService.setAvoidUnvalidated(network);
4393 } catch (RemoteException e) {
4394 throw e.rethrowFromSystemServer();
4395 }
4396 }
4397
4398 /**
4399 * Requests that the system open the captive portal app on the specified network.
4400 *
4401 * @param network The network to log into.
4402 *
4403 * @hide
4404 */
4405 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4406 public void startCaptivePortalApp(Network network) {
4407 try {
4408 mService.startCaptivePortalApp(network);
4409 } catch (RemoteException e) {
4410 throw e.rethrowFromSystemServer();
4411 }
4412 }
4413
4414 /**
4415 * Requests that the system open the captive portal app with the specified extras.
4416 *
4417 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4418 * corresponding permission.
4419 * @param network Network on which the captive portal was detected.
4420 * @param appExtras Extras to include in the app start intent.
4421 * @hide
4422 */
4423 @SystemApi
4424 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4425 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4426 try {
4427 mService.startCaptivePortalAppInternal(network, appExtras);
4428 } catch (RemoteException e) {
4429 throw e.rethrowFromSystemServer();
4430 }
4431 }
4432
4433 /**
4434 * Determine whether the device is configured to avoid bad wifi.
4435 * @hide
4436 */
4437 @SystemApi
4438 @RequiresPermission(anyOf = {
4439 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4440 android.Manifest.permission.NETWORK_STACK})
4441 public boolean shouldAvoidBadWifi() {
4442 try {
4443 return mService.shouldAvoidBadWifi();
4444 } catch (RemoteException e) {
4445 throw e.rethrowFromSystemServer();
4446 }
4447 }
4448
4449 /**
4450 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4451 * time-sensitive user-facing operations when the system default network is temporarily
4452 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4453 * this method), and the operation should be infrequent to ensure that data usage is limited.
4454 *
4455 * An example of such an operation might be a time-sensitive foreground activity, such as a
4456 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4457 */
4458 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4459
4460 /**
4461 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4462 * a backup channel for traffic that is primarily going over another network.
4463 *
4464 * An example might be maintaining backup connections to peers or servers for the purpose of
4465 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4466 * on backup paths should be negligible compared to the traffic on the main path.
4467 */
4468 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4469
4470 /**
4471 * It is acceptable to use metered data to improve network latency and performance.
4472 */
4473 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4474
4475 /**
4476 * Return value to use for unmetered networks. On such networks we currently set all the flags
4477 * to true.
4478 * @hide
4479 */
4480 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4481 MULTIPATH_PREFERENCE_HANDOVER |
4482 MULTIPATH_PREFERENCE_RELIABILITY |
4483 MULTIPATH_PREFERENCE_PERFORMANCE;
4484
4485 /** @hide */
4486 @Retention(RetentionPolicy.SOURCE)
4487 @IntDef(flag = true, value = {
4488 MULTIPATH_PREFERENCE_HANDOVER,
4489 MULTIPATH_PREFERENCE_RELIABILITY,
4490 MULTIPATH_PREFERENCE_PERFORMANCE,
4491 })
4492 public @interface MultipathPreference {
4493 }
4494
4495 /**
4496 * Provides a hint to the calling application on whether it is desirable to use the
4497 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4498 * for multipath data transfer on this network when it is not the system default network.
4499 * Applications desiring to use multipath network protocols should call this method before
4500 * each such operation.
4501 *
4502 * @param network The network on which the application desires to use multipath data.
4503 * If {@code null}, this method will return the a preference that will generally
4504 * apply to metered networks.
4505 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4506 */
4507 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4508 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
4509 try {
4510 return mService.getMultipathPreference(network);
4511 } catch (RemoteException e) {
4512 throw e.rethrowFromSystemServer();
4513 }
4514 }
4515
4516 /**
4517 * Resets all connectivity manager settings back to factory defaults.
4518 * @hide
4519 */
4520 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4521 public void factoryReset() {
4522 try {
4523 mService.factoryReset();
4524 mTetheringManager.stopAllTethering();
4525 } catch (RemoteException e) {
4526 throw e.rethrowFromSystemServer();
4527 }
4528 }
4529
4530 /**
4531 * Binds the current process to {@code network}. All Sockets created in the future
4532 * (and not explicitly bound via a bound SocketFactory from
4533 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4534 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4535 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4536 * work and all host name resolutions will fail. This is by design so an application doesn't
4537 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4538 * To clear binding pass {@code null} for {@code network}. Using individually bound
4539 * Sockets created by Network.getSocketFactory().createSocket() and
4540 * performing network-specific host name resolutions via
4541 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4542 * {@code bindProcessToNetwork}.
4543 *
4544 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4545 * the current binding.
4546 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4547 */
4548 public boolean bindProcessToNetwork(@Nullable Network network) {
4549 // Forcing callers to call through non-static function ensures ConnectivityManager
4550 // instantiated.
4551 return setProcessDefaultNetwork(network);
4552 }
4553
4554 /**
4555 * Binds the current process to {@code network}. All Sockets created in the future
4556 * (and not explicitly bound via a bound SocketFactory from
4557 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4558 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4559 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4560 * work and all host name resolutions will fail. This is by design so an application doesn't
4561 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4562 * To clear binding pass {@code null} for {@code network}. Using individually bound
4563 * Sockets created by Network.getSocketFactory().createSocket() and
4564 * performing network-specific host name resolutions via
4565 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4566 * {@code setProcessDefaultNetwork}.
4567 *
4568 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4569 * the current binding.
4570 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4571 * @deprecated This function can throw {@link IllegalStateException}. Use
4572 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4573 * is a direct replacement.
4574 */
4575 @Deprecated
4576 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
4577 int netId = (network == null) ? NETID_UNSET : network.netId;
4578 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4579
4580 if (netId != NETID_UNSET) {
4581 netId = network.getNetIdForResolv();
4582 }
4583
4584 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4585 return false;
4586 }
4587
4588 if (!isSameNetId) {
4589 // Set HTTP proxy system properties to match network.
4590 // TODO: Deprecate this static method and replace it with a non-static version.
4591 try {
Remi NGUYEN VAN345c2df2021-02-03 10:18:20 +09004592 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004593 } catch (SecurityException e) {
4594 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4595 Log.e(TAG, "Can't set proxy properties", e);
4596 }
4597 // Must flush DNS cache as new network may have different DNS resolutions.
4598 InetAddress.clearDnsCache();
4599 // Must flush socket pool as idle sockets will be bound to previous network and may
4600 // cause subsequent fetches to be performed on old network.
4601 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
4602 }
4603
4604 return true;
4605 }
4606
4607 /**
4608 * Returns the {@link Network} currently bound to this process via
4609 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4610 *
4611 * @return {@code Network} to which this process is bound, or {@code null}.
4612 */
4613 @Nullable
4614 public Network getBoundNetworkForProcess() {
4615 // Forcing callers to call thru non-static function ensures ConnectivityManager
4616 // instantiated.
4617 return getProcessDefaultNetwork();
4618 }
4619
4620 /**
4621 * Returns the {@link Network} currently bound to this process via
4622 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4623 *
4624 * @return {@code Network} to which this process is bound, or {@code null}.
4625 * @deprecated Using this function can lead to other functions throwing
4626 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4627 * {@code getBoundNetworkForProcess} is a direct replacement.
4628 */
4629 @Deprecated
4630 @Nullable
4631 public static Network getProcessDefaultNetwork() {
4632 int netId = NetworkUtils.getBoundNetworkForProcess();
4633 if (netId == NETID_UNSET) return null;
4634 return new Network(netId);
4635 }
4636
4637 private void unsupportedStartingFrom(int version) {
4638 if (Process.myUid() == Process.SYSTEM_UID) {
4639 // The getApplicationInfo() call we make below is not supported in system context. Let
4640 // the call through here, and rely on the fact that ConnectivityService will refuse to
4641 // allow the system to use these APIs anyway.
4642 return;
4643 }
4644
4645 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4646 throw new UnsupportedOperationException(
4647 "This method is not supported in target SDK version " + version + " and above");
4648 }
4649 }
4650
4651 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4652 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
4653 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
4654 // remove these exemptions. Note that this check is not secure, and apps can still access these
4655 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4656 // so is unsupported and may break in the future. http://b/22728205
4657 private void checkLegacyRoutingApiAccess() {
4658 unsupportedStartingFrom(VERSION_CODES.M);
4659 }
4660
4661 /**
4662 * Binds host resolutions performed by this process to {@code network}.
4663 * {@link #bindProcessToNetwork} takes precedence over this setting.
4664 *
4665 * @param network The {@link Network} to bind host resolutions from the current process to, or
4666 * {@code null} to clear the current binding.
4667 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4668 * @hide
4669 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4670 */
4671 @Deprecated
4672 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4673 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
4674 return NetworkUtils.bindProcessToNetworkForHostResolution(
4675 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
4676 }
4677
4678 /**
4679 * Device is not restricting metered network activity while application is running on
4680 * background.
4681 */
4682 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4683
4684 /**
4685 * Device is restricting metered network activity while application is running on background,
4686 * but application is allowed to bypass it.
4687 * <p>
4688 * In this state, application should take action to mitigate metered network access.
4689 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4690 */
4691 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4692
4693 /**
4694 * Device is restricting metered network activity while application is running on background.
4695 * <p>
4696 * In this state, application should not try to use the network while running on background,
4697 * because it would be denied.
4698 */
4699 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4700
4701 /**
4702 * A change in the background metered network activity restriction has occurred.
4703 * <p>
4704 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4705 * applies to them.
4706 * <p>
4707 * This is only sent to registered receivers, not manifest receivers.
4708 */
4709 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4710 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4711 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4712
4713 /** @hide */
4714 @Retention(RetentionPolicy.SOURCE)
4715 @IntDef(flag = false, value = {
4716 RESTRICT_BACKGROUND_STATUS_DISABLED,
4717 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4718 RESTRICT_BACKGROUND_STATUS_ENABLED,
4719 })
4720 public @interface RestrictBackgroundStatus {
4721 }
4722
4723 private INetworkPolicyManager getNetworkPolicyManager() {
4724 synchronized (this) {
4725 if (mNPManager != null) {
4726 return mNPManager;
4727 }
4728 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4729 .getService(Context.NETWORK_POLICY_SERVICE));
4730 return mNPManager;
4731 }
4732 }
4733
4734 /**
4735 * Determines if the calling application is subject to metered network restrictions while
4736 * running on background.
4737 *
4738 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4739 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4740 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
4741 */
4742 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4743 try {
4744 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4745 } catch (RemoteException e) {
4746 throw e.rethrowFromSystemServer();
4747 }
4748 }
4749
4750 /**
4751 * The network watchlist is a list of domains and IP addresses that are associated with
4752 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4753 * currently used by the system for validation purposes.
4754 *
4755 * @return Hash of network watchlist config file. Null if config does not exist.
4756 */
4757 @Nullable
4758 public byte[] getNetworkWatchlistConfigHash() {
4759 try {
4760 return mService.getNetworkWatchlistConfigHash();
4761 } catch (RemoteException e) {
4762 Log.e(TAG, "Unable to get watchlist config hash");
4763 throw e.rethrowFromSystemServer();
4764 }
4765 }
4766
4767 /**
4768 * Returns the {@code uid} of the owner of a network connection.
4769 *
4770 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4771 * IPPROTO_UDP} currently supported.
4772 * @param local The local {@link InetSocketAddress} of a connection.
4773 * @param remote The remote {@link InetSocketAddress} of a connection.
4774 * @return {@code uid} if the connection is found and the app has permission to observe it
4775 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4776 * android.os.Process#INVALID_UID} if the connection is not found.
4777 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4778 * user.
4779 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
4780 */
4781 public int getConnectionOwnerUid(
4782 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
4783 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4784 try {
4785 return mService.getConnectionOwnerUid(connectionInfo);
4786 } catch (RemoteException e) {
4787 throw e.rethrowFromSystemServer();
4788 }
4789 }
4790
4791 private void printStackTrace() {
4792 if (DEBUG) {
4793 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4794 final StringBuffer sb = new StringBuffer();
4795 for (int i = 3; i < callStack.length; i++) {
4796 final String stackTrace = callStack[i].toString();
4797 if (stackTrace == null || stackTrace.contains("android.os")) {
4798 break;
4799 }
4800 sb.append(" [").append(stackTrace).append("]");
4801 }
4802 Log.d(TAG, "StackLog:" + sb.toString());
4803 }
4804 }
4805
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09004806 /** @hide */
4807 public TestNetworkManager startOrGetTestNetworkManager() {
4808 final IBinder tnBinder;
4809 try {
4810 tnBinder = mService.startOrGetTestNetworkService();
4811 } catch (RemoteException e) {
4812 throw e.rethrowFromSystemServer();
4813 }
4814
4815 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4816 }
4817
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09004818 /** @hide */
4819 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4820 return new ConnectivityDiagnosticsManager(mContext, mService);
4821 }
4822
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004823 /**
4824 * Simulates a Data Stall for the specified Network.
4825 *
4826 * <p>This method should only be used for tests.
4827 *
4828 * <p>The caller must be the owner of the specified Network.
4829 *
4830 * @param detectionMethod The detection method used to identify the Data Stall.
4831 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4832 * @param network The Network for which a Data Stall is being simluated.
4833 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4834 * @throws SecurityException if the caller is not the owner of the given network.
4835 * @hide
4836 */
4837 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4838 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4839 android.Manifest.permission.NETWORK_STACK})
4840 public void simulateDataStall(int detectionMethod, long timestampMillis,
4841 @NonNull Network network, @NonNull PersistableBundle extras) {
4842 try {
4843 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4844 } catch (RemoteException e) {
4845 e.rethrowFromSystemServer();
4846 }
4847 }
4848
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004849 @NonNull
4850 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4851
4852 /**
4853 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4854 * receive available QoS events related to the {@link Network} and local ip + port
4855 * specified within socketInfo.
4856 * <p/>
4857 * The same {@link QosCallback} must be unregistered before being registered a second time,
4858 * otherwise {@link QosCallbackRegistrationException} is thrown.
4859 * <p/>
4860 * This API does not, in itself, require any permission if called with a network that is not
4861 * restricted. However, the underlying implementation currently only supports the IMS network,
4862 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4863 * useful, because they'd never be called back on networks that they would have access to.
4864 *
4865 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4866 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4867 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4868 * @throws RuntimeException if the app already has too many callbacks registered.
4869 *
4870 * Exceptions after the time of registration is passed through
4871 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4872 *
4873 * @param socketInfo the socket information used to match QoS events
4874 * @param callback receives qos events that satisfy socketInfo
4875 * @param executor The executor on which the callback will be invoked. The provided
4876 * {@link Executor} must run callback sequentially, otherwise the order of
4877 * callbacks cannot be guaranteed.
4878 *
4879 * @hide
4880 */
4881 @SystemApi
4882 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4883 @NonNull final QosCallback callback,
4884 @CallbackExecutor @NonNull final Executor executor) {
4885 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4886 Objects.requireNonNull(callback, "callback must be non-null");
4887 Objects.requireNonNull(executor, "executor must be non-null");
4888
4889 try {
4890 synchronized (mQosCallbackConnections) {
4891 if (getQosCallbackConnection(callback) == null) {
4892 final QosCallbackConnection connection =
4893 new QosCallbackConnection(this, callback, executor);
4894 mQosCallbackConnections.add(connection);
4895 mService.registerQosSocketCallback(socketInfo, connection);
4896 } else {
4897 Log.e(TAG, "registerQosCallback: Callback already registered");
4898 throw new QosCallbackRegistrationException();
4899 }
4900 }
4901 } catch (final RemoteException e) {
4902 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4903
4904 // The same unregister method method is called for consistency even though nothing
4905 // will be sent to the ConnectivityService since the callback was never successfully
4906 // registered.
4907 unregisterQosCallback(callback);
4908 e.rethrowFromSystemServer();
4909 } catch (final ServiceSpecificException e) {
4910 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4911 unregisterQosCallback(callback);
4912 throw convertServiceException(e);
4913 }
4914 }
4915
4916 /**
4917 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4918 * events once unregistered and can be registered a second time.
4919 * <p/>
4920 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4921 *
4922 * @param callback the callback being unregistered
4923 *
4924 * @hide
4925 */
4926 @SystemApi
4927 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4928 Objects.requireNonNull(callback, "The callback must be non-null");
4929 try {
4930 synchronized (mQosCallbackConnections) {
4931 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4932 if (connection != null) {
4933 connection.stopReceivingMessages();
4934 mService.unregisterQosCallback(connection);
4935 mQosCallbackConnections.remove(connection);
4936 } else {
4937 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4938 }
4939 }
4940 } catch (final RemoteException e) {
4941 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4942 e.rethrowFromSystemServer();
4943 }
4944 }
4945
4946 /**
4947 * Gets the connection related to the callback.
4948 *
4949 * @param callback the callback to look up
4950 * @return the related connection
4951 */
4952 @Nullable
4953 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4954 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4955 // Checking by reference here is intentional
4956 if (connection.getCallback() == callback) {
4957 return connection;
4958 }
4959 }
4960 return null;
4961 }
4962
4963 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004964 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004965 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4966 * be used to request that the system provide a network without causing the network to be
4967 * in the foreground.
4968 *
4969 * <p>This method will attempt to find the best network that matches the passed
4970 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4971 * criteria. The platform will evaluate which network is the best at its own discretion.
4972 * Throughput, latency, cost per byte, policy, user preference and other considerations
4973 * may be factored in the decision of what is considered the best network.
4974 *
4975 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4976 * matching this request, while always attempting to match the request to a better network if
4977 * possible. If a better match is found, the platform will switch this request to the now-best
4978 * network and inform the app of the newly best network by invoking
4979 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4980 * will not try to maintain any other network than the best one currently matching the request:
4981 * a network not matching any network request may be disconnected at any time.
4982 *
4983 * <p>For example, an application could use this method to obtain a connected cellular network
4984 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4985 * radio to consume additional power. Or, an application could inform the system that it wants
4986 * a network supporting sending MMSes and have the system let it know about the currently best
4987 * MMS-supporting network through the provided {@link NetworkCallback}.
4988 *
4989 * <p>The status of the request can be followed by listening to the various callbacks described
4990 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4991 * used to direct traffic to the network (although accessing some networks may be subject to
4992 * holding specific permissions). Callers will learn about the specific characteristics of the
4993 * network through
4994 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4995 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4996 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4997 * matching the request at any given time; therefore when a better network matching the request
4998 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4999 * with the new network after which no further updates are given about the previously-best
5000 * network, unless it becomes the best again at some later time. All callbacks are invoked
5001 * in order on the same thread, which by default is a thread created by the framework running
5002 * in the app.
5003 *
5004 * <p>This{@link NetworkRequest} will live until released via
5005 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5006 * which point the system may let go of the network at any time.
5007 *
5008 * <p>It is presently unsupported to request a network with mutable
5009 * {@link NetworkCapabilities} such as
5010 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5011 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5012 * as these {@code NetworkCapabilities} represent states that a particular
5013 * network may never attain, and whether a network will attain these states
5014 * is unknown prior to bringing up the network so the framework does not
5015 * know how to go about satisfying a request with these capabilities.
5016 *
5017 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5018 * number of outstanding requests to 100 per app (identified by their UID), shared with
5019 * all variants of this method, of {@link #registerNetworkCallback} as well as
5020 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5021 * Requesting a network with this method will count toward this limit. If this limit is
5022 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5023 * make sure to unregister the callbacks with
5024 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5025 *
5026 * @param request {@link NetworkRequest} describing this request.
5027 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5028 * If null, the callback is invoked on the default internal Handler.
5029 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5030 * the callback must not be shared - it uniquely specifies this request.
5031 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5032 * @throws SecurityException if missing the appropriate permissions.
5033 * @throws RuntimeException if the app already has too many callbacks registered.
5034 *
5035 * @hide
5036 */
5037 @SystemApi(client = MODULE_LIBRARIES)
5038 @SuppressLint("ExecutorRegistration")
5039 @RequiresPermission(anyOf = {
5040 android.Manifest.permission.NETWORK_SETTINGS,
5041 android.Manifest.permission.NETWORK_STACK,
5042 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5043 })
5044 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaidbb70462021-03-09 20:49:48 +08005045 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005046 final NetworkCapabilities nc = request.networkCapabilities;
5047 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005048 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005049 }
James Mattis12aeab82021-01-10 14:24:24 -08005050
5051 /**
5052 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
5053 * OnSetOemNetworkPreferenceListener)}.
James Mattis6e2d7022021-01-26 16:23:52 -08005054 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005055 */
James Mattis6e2d7022021-01-26 16:23:52 -08005056 @SystemApi
5057 public interface OnSetOemNetworkPreferenceListener {
James Mattis12aeab82021-01-10 14:24:24 -08005058 /**
5059 * Called when setOemNetworkPreference() successfully completes.
5060 */
5061 void onComplete();
5062 }
5063
5064 /**
5065 * Used by automotive devices to set the network preferences used to direct traffic at an
5066 * application level as per the given OemNetworkPreferences. An example use-case would be an
5067 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5068 * vehicle via a particular network.
5069 *
5070 * Calling this will overwrite the existing preference.
5071 *
5072 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5073 * @param executor the executor on which listener will be invoked.
5074 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5075 * communicate completion of setOemNetworkPreference(). This will only be
5076 * called once upon successful completion of setOemNetworkPreference().
5077 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5078 * @throws SecurityException if missing the appropriate permissions.
5079 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005080 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005081 */
James Mattis6e2d7022021-01-26 16:23:52 -08005082 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005083 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005084 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005085 @Nullable @CallbackExecutor final Executor executor,
5086 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5087 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5088 if (null != listener) {
5089 Objects.requireNonNull(executor, "Executor must be non-null");
5090 }
5091 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5092 new IOnSetOemNetworkPreferenceListener.Stub() {
5093 @Override
5094 public void onComplete() {
5095 executor.execute(listener::onComplete);
5096 }
5097 };
5098
5099 try {
5100 mService.setOemNetworkPreference(preference, listenerInternal);
5101 } catch (RemoteException e) {
5102 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5103 throw e.rethrowFromSystemServer();
5104 }
5105 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005106
5107 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005108 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005109 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005110 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005111
5112 /**
5113 * Get the network ID range reserved for IPSec tunnel interfaces.
5114 *
5115 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5116 * @hide
5117 */
5118 @SystemApi(client = MODULE_LIBRARIES)
5119 @NonNull
5120 public static Range<Integer> getIpSecNetIdRange() {
5121 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5122 }
lucaslin889dcda2021-03-12 17:56:09 +08005123
5124 /**
5125 * Get private DNS mode from settings.
5126 *
5127 * @param cr The ContentResolver to query private DNS mode from settings.
5128 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5129 *
5130 * @hide
5131 */
5132 @SystemApi(client = MODULE_LIBRARIES)
5133 @NonNull
5134 @PrivateDnsMode
5135 public static String getPrivateDnsMode(@NonNull ContentResolver cr) {
5136 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5137 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5138 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5139 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5140 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5141 return mode;
5142 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005143}