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