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