blob: 6273f4bb577b12690fb3fdd29ddadcaf581791d2 [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
2248 /* TODO: These permissions checks don't belong in client-side code. Move them to
2249 * services.jar, possibly in com.android.server.net. */
2250
2251 /** {@hide} */
2252 public static final void enforceChangePermission(Context context,
2253 String callingPkg, String callingAttributionTag) {
2254 int uid = Binder.getCallingUid();
2255 checkAndNoteChangeNetworkStateOperation(context, uid, callingPkg,
2256 callingAttributionTag, true /* throwException */);
2257 }
2258
2259 /**
2260 * Check if the package is a allowed to change the network state. This also accounts that such
2261 * an access happened.
2262 *
2263 * @return {@code true} iff the package is allowed to change the network state.
2264 */
2265 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2266 private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context,
2267 int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag,
2268 boolean throwException) {
2269 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, callingPackage,
2270 throwException);
2271 }
2272
2273 /**
2274 * Check if the package is a allowed to write settings. This also accounts that such an access
2275 * happened.
2276 *
2277 * @return {@code true} iff the package is allowed to write settings.
2278 */
2279 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2280 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2281 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2282 boolean throwException) {
2283 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2284 throwException);
2285 }
2286
2287 /**
2288 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2289 * situations where a Context pointer is unavailable.
2290 * @hide
2291 */
2292 @Deprecated
2293 static ConnectivityManager getInstanceOrNull() {
2294 return sInstance;
2295 }
2296
2297 /**
2298 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2299 * situations where a Context pointer is unavailable.
2300 * @hide
2301 */
2302 @Deprecated
2303 @UnsupportedAppUsage
2304 private static ConnectivityManager getInstance() {
2305 if (getInstanceOrNull() == null) {
2306 throw new IllegalStateException("No ConnectivityManager yet constructed");
2307 }
2308 return getInstanceOrNull();
2309 }
2310
2311 /**
2312 * Get the set of tetherable, available interfaces. This list is limited by
2313 * device configuration and current interface existence.
2314 *
2315 * @return an array of 0 or more Strings of tetherable interface names.
2316 *
2317 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2318 * {@hide}
2319 */
2320 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2321 @UnsupportedAppUsage
2322 @Deprecated
2323 public String[] getTetherableIfaces() {
2324 return mTetheringManager.getTetherableIfaces();
2325 }
2326
2327 /**
2328 * Get the set of tethered interfaces.
2329 *
2330 * @return an array of 0 or more String of currently tethered interface names.
2331 *
2332 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2333 * {@hide}
2334 */
2335 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2336 @UnsupportedAppUsage
2337 @Deprecated
2338 public String[] getTetheredIfaces() {
2339 return mTetheringManager.getTetheredIfaces();
2340 }
2341
2342 /**
2343 * Get the set of interface names which attempted to tether but
2344 * failed. Re-attempting to tether may cause them to reset to the Tethered
2345 * state. Alternatively, causing the interface to be destroyed and recreated
2346 * may cause them to reset to the available state.
2347 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2348 * information on the cause of the errors.
2349 *
2350 * @return an array of 0 or more String indicating the interface names
2351 * which failed to tether.
2352 *
2353 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2354 * {@hide}
2355 */
2356 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2357 @UnsupportedAppUsage
2358 @Deprecated
2359 public String[] getTetheringErroredIfaces() {
2360 return mTetheringManager.getTetheringErroredIfaces();
2361 }
2362
2363 /**
2364 * Get the set of tethered dhcp ranges.
2365 *
2366 * @deprecated This method is not supported.
2367 * TODO: remove this function when all of clients are removed.
2368 * {@hide}
2369 */
2370 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2371 @Deprecated
2372 public String[] getTetheredDhcpRanges() {
2373 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2374 }
2375
2376 /**
2377 * Attempt to tether the named interface. This will setup a dhcp server
2378 * on the interface, forward and NAT IP packets and forward DNS requests
2379 * to the best active upstream network interface. Note that if no upstream
2380 * IP network interface is available, dhcp will still run and traffic will be
2381 * allowed between the tethered devices and this device, though upstream net
2382 * access will of course fail until an upstream network interface becomes
2383 * active.
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 tether.
2396 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2397 * @deprecated Use {@link TetheringManager#startTethering} instead
2398 *
2399 * {@hide}
2400 */
2401 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2402 @Deprecated
2403 public int tether(String iface) {
2404 return mTetheringManager.tether(iface);
2405 }
2406
2407 /**
2408 * Stop tethering the named interface.
2409 *
2410 * <p>This method requires the caller to hold either the
2411 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2412 * or the ability to modify system settings as determined by
2413 * {@link android.provider.Settings.System#canWrite}.</p>
2414 *
2415 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2416 * and WifiStateMachine which need direct access. All other clients should use
2417 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2418 * logic.</p>
2419 *
2420 * @param iface the interface name to untether.
2421 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2422 *
2423 * {@hide}
2424 */
2425 @UnsupportedAppUsage
2426 @Deprecated
2427 public int untether(String iface) {
2428 return mTetheringManager.untether(iface);
2429 }
2430
2431 /**
2432 * Check if the device allows for tethering. It may be disabled via
2433 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2434 * due to device configuration.
2435 *
2436 * <p>If this app does not have permission to use this API, it will always
2437 * return false rather than throw an exception.</p>
2438 *
2439 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2440 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2441 *
2442 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2443 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2444 *
2445 * @return a boolean - {@code true} indicating Tethering is supported.
2446 *
2447 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2448 * {@hide}
2449 */
2450 @SystemApi
2451 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2452 android.Manifest.permission.WRITE_SETTINGS})
2453 public boolean isTetheringSupported() {
2454 return mTetheringManager.isTetheringSupported();
2455 }
2456
2457 /**
2458 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2459 *
2460 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2461 * @hide
2462 */
2463 @SystemApi
2464 @Deprecated
2465 public static abstract class OnStartTetheringCallback {
2466 /**
2467 * Called when tethering has been successfully started.
2468 */
2469 public void onTetheringStarted() {}
2470
2471 /**
2472 * Called when starting tethering failed.
2473 */
2474 public void onTetheringFailed() {}
2475 }
2476
2477 /**
2478 * Convenient overload for
2479 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2480 * handler to run on the current thread's {@link Looper}.
2481 *
2482 * @deprecated Use {@link TetheringManager#startTethering} instead.
2483 * @hide
2484 */
2485 @SystemApi
2486 @Deprecated
2487 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2488 public void startTethering(int type, boolean showProvisioningUi,
2489 final OnStartTetheringCallback callback) {
2490 startTethering(type, showProvisioningUi, callback, null);
2491 }
2492
2493 /**
2494 * Runs tether provisioning for the given type if needed and then starts tethering if
2495 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2496 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2497 * schedules tether provisioning re-checks if appropriate.
2498 *
2499 * @param type The type of tethering to start. Must be one of
2500 * {@link ConnectivityManager.TETHERING_WIFI},
2501 * {@link ConnectivityManager.TETHERING_USB}, or
2502 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2503 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2504 * is one. This should be true the first time this function is called and also any time
2505 * the user can see this UI. It gives users information from their carrier about the
2506 * check failing and how they can sign up for tethering if possible.
2507 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2508 * of the result of trying to tether.
2509 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2510 *
2511 * @deprecated Use {@link TetheringManager#startTethering} instead.
2512 * @hide
2513 */
2514 @SystemApi
2515 @Deprecated
2516 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2517 public void startTethering(int type, boolean showProvisioningUi,
2518 final OnStartTetheringCallback callback, Handler handler) {
2519 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
2520
2521 final Executor executor = new Executor() {
2522 @Override
2523 public void execute(Runnable command) {
2524 if (handler == null) {
2525 command.run();
2526 } else {
2527 handler.post(command);
2528 }
2529 }
2530 };
2531
2532 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2533 @Override
2534 public void onTetheringStarted() {
2535 callback.onTetheringStarted();
2536 }
2537
2538 @Override
2539 public void onTetheringFailed(final int error) {
2540 callback.onTetheringFailed();
2541 }
2542 };
2543
2544 final TetheringRequest request = new TetheringRequest.Builder(type)
2545 .setShouldShowEntitlementUi(showProvisioningUi).build();
2546
2547 mTetheringManager.startTethering(request, executor, tetheringCallback);
2548 }
2549
2550 /**
2551 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2552 * applicable.
2553 *
2554 * @param type The type of tethering to stop. Must be one of
2555 * {@link ConnectivityManager.TETHERING_WIFI},
2556 * {@link ConnectivityManager.TETHERING_USB}, or
2557 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2558 *
2559 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2560 * @hide
2561 */
2562 @SystemApi
2563 @Deprecated
2564 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2565 public void stopTethering(int type) {
2566 mTetheringManager.stopTethering(type);
2567 }
2568
2569 /**
2570 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2571 * upstream status.
2572 *
2573 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2574 * @hide
2575 */
2576 @SystemApi
2577 @Deprecated
2578 public abstract static class OnTetheringEventCallback {
2579
2580 /**
2581 * Called when tethering upstream changed. This can be called multiple times and can be
2582 * called any time.
2583 *
2584 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2585 * have any upstream.
2586 */
2587 public void onUpstreamChanged(@Nullable Network network) {}
2588 }
2589
2590 @GuardedBy("mTetheringEventCallbacks")
2591 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2592 mTetheringEventCallbacks = new ArrayMap<>();
2593
2594 /**
2595 * Start listening to tethering change events. Any new added callback will receive the last
2596 * tethering status right away. If callback is registered when tethering has no upstream or
2597 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2598 * with a null argument. The same callback object cannot be registered twice.
2599 *
2600 * @param executor the executor on which callback will be invoked.
2601 * @param callback the callback to be called when tethering has change events.
2602 *
2603 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2604 * @hide
2605 */
2606 @SystemApi
2607 @Deprecated
2608 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2609 public void registerTetheringEventCallback(
2610 @NonNull @CallbackExecutor Executor executor,
2611 @NonNull final OnTetheringEventCallback callback) {
2612 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2613
2614 final TetheringEventCallback tetherCallback =
2615 new TetheringEventCallback() {
2616 @Override
2617 public void onUpstreamChanged(@Nullable Network network) {
2618 callback.onUpstreamChanged(network);
2619 }
2620 };
2621
2622 synchronized (mTetheringEventCallbacks) {
2623 mTetheringEventCallbacks.put(callback, tetherCallback);
2624 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
2625 }
2626 }
2627
2628 /**
2629 * Remove tethering event callback previously registered with
2630 * {@link #registerTetheringEventCallback}.
2631 *
2632 * @param callback previously registered callback.
2633 *
2634 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
2635 * @hide
2636 */
2637 @SystemApi
2638 @Deprecated
2639 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2640 public void unregisterTetheringEventCallback(
2641 @NonNull final OnTetheringEventCallback callback) {
2642 Objects.requireNonNull(callback, "The callback must be non-null");
2643 synchronized (mTetheringEventCallbacks) {
2644 final TetheringEventCallback tetherCallback =
2645 mTetheringEventCallbacks.remove(callback);
2646 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
2647 }
2648 }
2649
2650
2651 /**
2652 * Get the list of regular expressions that define any tetherable
2653 * USB network interfaces. If USB tethering is not supported by the
2654 * device, this list should be empty.
2655 *
2656 * @return an array of 0 or more regular expression Strings defining
2657 * what interfaces are considered tetherable usb interfaces.
2658 *
2659 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2660 * {@hide}
2661 */
2662 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2663 @UnsupportedAppUsage
2664 @Deprecated
2665 public String[] getTetherableUsbRegexs() {
2666 return mTetheringManager.getTetherableUsbRegexs();
2667 }
2668
2669 /**
2670 * Get the list of regular expressions that define any tetherable
2671 * Wifi network interfaces. If Wifi tethering is not supported by the
2672 * device, this list should be empty.
2673 *
2674 * @return an array of 0 or more regular expression Strings defining
2675 * what interfaces are considered tetherable wifi interfaces.
2676 *
2677 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2678 * {@hide}
2679 */
2680 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2681 @UnsupportedAppUsage
2682 @Deprecated
2683 public String[] getTetherableWifiRegexs() {
2684 return mTetheringManager.getTetherableWifiRegexs();
2685 }
2686
2687 /**
2688 * Get the list of regular expressions that define any tetherable
2689 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2690 * device, this list should be empty.
2691 *
2692 * @return an array of 0 or more regular expression Strings defining
2693 * what interfaces are considered tetherable bluetooth interfaces.
2694 *
2695 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2696 *TetheringManager.TetheringInterfaceRegexps)} instead.
2697 * {@hide}
2698 */
2699 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2700 @UnsupportedAppUsage
2701 @Deprecated
2702 public String[] getTetherableBluetoothRegexs() {
2703 return mTetheringManager.getTetherableBluetoothRegexs();
2704 }
2705
2706 /**
2707 * Attempt to both alter the mode of USB and Tethering of USB. A
2708 * utility method to deal with some of the complexity of USB - will
2709 * attempt to switch to Rndis and subsequently tether the resulting
2710 * interface on {@code true} or turn off tethering and switch off
2711 * Rndis on {@code false}.
2712 *
2713 * <p>This method requires the caller to hold either the
2714 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2715 * or the ability to modify system settings as determined by
2716 * {@link android.provider.Settings.System#canWrite}.</p>
2717 *
2718 * @param enable a boolean - {@code true} to enable tethering
2719 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2720 * @deprecated Use {@link TetheringManager#startTethering} instead
2721 *
2722 * {@hide}
2723 */
2724 @UnsupportedAppUsage
2725 @Deprecated
2726 public int setUsbTethering(boolean enable) {
2727 return mTetheringManager.setUsbTethering(enable);
2728 }
2729
2730 /**
2731 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2732 * {@hide}
2733 */
2734 @SystemApi
2735 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002736 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002737 /**
2738 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2739 * {@hide}
2740 */
2741 @Deprecated
2742 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2743 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2744 /**
2745 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2746 * {@hide}
2747 */
2748 @Deprecated
2749 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2750 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2751 /**
2752 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2753 * {@hide}
2754 */
2755 @Deprecated
2756 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2757 /**
2758 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2759 * {@hide}
2760 */
2761 @Deprecated
2762 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2763 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2764 /**
2765 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
2766 * {@hide}
2767 */
2768 @Deprecated
2769 public static final int TETHER_ERROR_MASTER_ERROR =
2770 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
2771 /**
2772 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2773 * {@hide}
2774 */
2775 @Deprecated
2776 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2777 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2778 /**
2779 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2780 * {@hide}
2781 */
2782 @Deprecated
2783 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2784 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2785 /**
2786 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
2787 * {@hide}
2788 */
2789 @Deprecated
2790 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
2791 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
2792 /**
2793 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
2794 * {@hide}
2795 */
2796 @Deprecated
2797 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
2798 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
2799 /**
2800 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2801 * {@hide}
2802 */
2803 @Deprecated
2804 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2805 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2806 /**
2807 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
2808 * {@hide}
2809 */
2810 @SystemApi
2811 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002812 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002813 /**
2814 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2815 * {@hide}
2816 */
2817 @Deprecated
2818 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2819 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2820 /**
2821 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2822 * {@hide}
2823 */
2824 @SystemApi
2825 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002826 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002827
2828 /**
2829 * Get a more detailed error code after a Tethering or Untethering
2830 * request asynchronously failed.
2831 *
2832 * @param iface The name of the interface of interest
2833 * @return error The error code of the last error tethering or untethering the named
2834 * interface
2835 *
2836 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2837 * {@hide}
2838 */
2839 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2840 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2841 @Deprecated
2842 public int getLastTetherError(String iface) {
2843 int error = mTetheringManager.getLastTetherError(iface);
2844 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2845 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2846 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2847 // instead.
2848 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2849 }
2850 return error;
2851 }
2852
2853 /** @hide */
2854 @Retention(RetentionPolicy.SOURCE)
2855 @IntDef(value = {
2856 TETHER_ERROR_NO_ERROR,
2857 TETHER_ERROR_PROVISION_FAILED,
2858 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2859 })
2860 public @interface EntitlementResultCode {
2861 }
2862
2863 /**
2864 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
2865 * entitlement succeeded.
2866 *
2867 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
2868 * @hide
2869 */
2870 @SystemApi
2871 @Deprecated
2872 public interface OnTetheringEntitlementResultListener {
2873 /**
2874 * Called to notify entitlement result.
2875 *
2876 * @param resultCode an int value of entitlement result. It may be one of
2877 * {@link #TETHER_ERROR_NO_ERROR},
2878 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2879 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2880 */
2881 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
2882 }
2883
2884 /**
2885 * Get the last value of the entitlement check on this downstream. If the cached value is
2886 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2887 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2888 * guaranteed that the UI-based entitlement check will complete in any specific time period
2889 * and may in fact never complete. Any successful entitlement check the platform performs for
2890 * any reason will update the cached value.
2891 *
2892 * @param type the downstream type of tethering. Must be one of
2893 * {@link #TETHERING_WIFI},
2894 * {@link #TETHERING_USB}, or
2895 * {@link #TETHERING_BLUETOOTH}.
2896 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
2897 * @param executor the executor on which callback will be invoked.
2898 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2899 * notify the caller of the result of entitlement check. The listener may be called zero
2900 * or one time.
2901 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
2902 * {@hide}
2903 */
2904 @SystemApi
2905 @Deprecated
2906 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2907 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2908 @NonNull @CallbackExecutor Executor executor,
2909 @NonNull final OnTetheringEntitlementResultListener listener) {
2910 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2911 ResultReceiver wrappedListener = new ResultReceiver(null) {
2912 @Override
2913 protected void onReceiveResult(int resultCode, Bundle resultData) {
2914 Binder.withCleanCallingIdentity(() ->
2915 executor.execute(() -> {
2916 listener.onTetheringEntitlementResult(resultCode);
2917 }));
2918 }
2919 };
2920
2921 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
2922 showEntitlementUi);
2923 }
2924
2925 /**
2926 * Report network connectivity status. This is currently used only
2927 * to alter status bar UI.
2928 * <p>This method requires the caller to hold the permission
2929 * {@link android.Manifest.permission#STATUS_BAR}.
2930 *
2931 * @param networkType The type of network you want to report on
2932 * @param percentage The quality of the connection 0 is bad, 100 is good
2933 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
2934 * {@hide}
2935 */
2936 public void reportInetCondition(int networkType, int percentage) {
2937 printStackTrace();
2938 try {
2939 mService.reportInetCondition(networkType, percentage);
2940 } catch (RemoteException e) {
2941 throw e.rethrowFromSystemServer();
2942 }
2943 }
2944
2945 /**
2946 * Report a problem network to the framework. This provides a hint to the system
2947 * that there might be connectivity problems on this network and may cause
2948 * the framework to re-evaluate network connectivity and/or switch to another
2949 * network.
2950 *
2951 * @param network The {@link Network} the application was attempting to use
2952 * or {@code null} to indicate the current default network.
2953 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2954 * working and non-working connectivity.
2955 */
2956 @Deprecated
2957 public void reportBadNetwork(@Nullable Network network) {
2958 printStackTrace();
2959 try {
2960 // One of these will be ignored because it matches system's current state.
2961 // The other will trigger the necessary reevaluation.
2962 mService.reportNetworkConnectivity(network, true);
2963 mService.reportNetworkConnectivity(network, false);
2964 } catch (RemoteException e) {
2965 throw e.rethrowFromSystemServer();
2966 }
2967 }
2968
2969 /**
2970 * Report to the framework whether a network has working connectivity.
2971 * This provides a hint to the system that a particular network is providing
2972 * working connectivity or not. In response the framework may re-evaluate
2973 * the network's connectivity and might take further action thereafter.
2974 *
2975 * @param network The {@link Network} the application was attempting to use
2976 * or {@code null} to indicate the current default network.
2977 * @param hasConnectivity {@code true} if the application was able to successfully access the
2978 * Internet using {@code network} or {@code false} if not.
2979 */
2980 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
2981 printStackTrace();
2982 try {
2983 mService.reportNetworkConnectivity(network, hasConnectivity);
2984 } catch (RemoteException e) {
2985 throw e.rethrowFromSystemServer();
2986 }
2987 }
2988
2989 /**
2990 * Set a network-independent global http proxy. This is not normally what you want
2991 * for typical HTTP proxies - they are general network dependent. However if you're
2992 * doing something unusual like general internal filtering this may be useful. On
2993 * a private network where the proxy is not accessible, you may break HTTP using this.
2994 *
2995 * @param p A {@link ProxyInfo} object defining the new global
2996 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
2997 * @hide
2998 */
2999 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
3000 public void setGlobalProxy(ProxyInfo p) {
3001 try {
3002 mService.setGlobalProxy(p);
3003 } catch (RemoteException e) {
3004 throw e.rethrowFromSystemServer();
3005 }
3006 }
3007
3008 /**
3009 * Retrieve any network-independent global HTTP proxy.
3010 *
3011 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3012 * if no global HTTP proxy is set.
3013 * @hide
3014 */
3015 public ProxyInfo getGlobalProxy() {
3016 try {
3017 return mService.getGlobalProxy();
3018 } catch (RemoteException e) {
3019 throw e.rethrowFromSystemServer();
3020 }
3021 }
3022
3023 /**
3024 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3025 * network-specific HTTP proxy. If {@code network} is null, the
3026 * network-specific proxy returned is the proxy of the default active
3027 * network.
3028 *
3029 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3030 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3031 * or when {@code network} is {@code null},
3032 * the {@code ProxyInfo} for the default active network. Returns
3033 * {@code null} when no proxy applies or the caller doesn't have
3034 * permission to use {@code network}.
3035 * @hide
3036 */
3037 public ProxyInfo getProxyForNetwork(Network network) {
3038 try {
3039 return mService.getProxyForNetwork(network);
3040 } catch (RemoteException e) {
3041 throw e.rethrowFromSystemServer();
3042 }
3043 }
3044
3045 /**
3046 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3047 * otherwise if this process is bound to a {@link Network} using
3048 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3049 * the default network's proxy is returned.
3050 *
3051 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3052 * HTTP proxy is active.
3053 */
3054 @Nullable
3055 public ProxyInfo getDefaultProxy() {
3056 return getProxyForNetwork(getBoundNetworkForProcess());
3057 }
3058
3059 /**
3060 * Returns true if the hardware supports the given network type
3061 * else it returns false. This doesn't indicate we have coverage
3062 * or are authorized onto a network, just whether or not the
3063 * hardware supports it. For example a GSM phone without a SIM
3064 * should still return {@code true} for mobile data, but a wifi only
3065 * tablet would return {@code false}.
3066 *
3067 * @param networkType The network type we'd like to check
3068 * @return {@code true} if supported, else {@code false}
3069 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3070 * @hide
3071 */
3072 @Deprecated
3073 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3074 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3075 public boolean isNetworkSupported(int networkType) {
3076 try {
3077 return mService.isNetworkSupported(networkType);
3078 } catch (RemoteException e) {
3079 throw e.rethrowFromSystemServer();
3080 }
3081 }
3082
3083 /**
3084 * Returns if the currently active data network is metered. A network is
3085 * classified as metered when the user is sensitive to heavy data usage on
3086 * that connection due to monetary costs, data limitations or
3087 * battery/performance issues. You should check this before doing large
3088 * data transfers, and warn the user or delay the operation until another
3089 * network is available.
3090 *
3091 * @return {@code true} if large transfers should be avoided, otherwise
3092 * {@code false}.
3093 */
3094 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3095 public boolean isActiveNetworkMetered() {
3096 try {
3097 return mService.isActiveNetworkMetered();
3098 } catch (RemoteException e) {
3099 throw e.rethrowFromSystemServer();
3100 }
3101 }
3102
3103 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003104 * Set sign in error notification to visible or invisible
3105 *
3106 * @hide
3107 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3108 */
3109 @Deprecated
3110 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3111 String action) {
3112 try {
3113 mService.setProvisioningNotificationVisible(visible, networkType, action);
3114 } catch (RemoteException e) {
3115 throw e.rethrowFromSystemServer();
3116 }
3117 }
3118
3119 /**
3120 * Set the value for enabling/disabling airplane mode
3121 *
3122 * @param enable whether to enable airplane mode or not
3123 *
3124 * @hide
3125 */
3126 @RequiresPermission(anyOf = {
3127 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3128 android.Manifest.permission.NETWORK_SETTINGS,
3129 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3130 android.Manifest.permission.NETWORK_STACK})
3131 @SystemApi
3132 public void setAirplaneMode(boolean enable) {
3133 try {
3134 mService.setAirplaneMode(enable);
3135 } catch (RemoteException e) {
3136 throw e.rethrowFromSystemServer();
3137 }
3138 }
3139
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003140 /**
3141 * Registers the specified {@link NetworkProvider}.
3142 * Each listener must only be registered once. The listener can be unregistered with
3143 * {@link #unregisterNetworkProvider}.
3144 *
3145 * @param provider the provider to register
3146 * @return the ID of the provider. This ID must be used by the provider when registering
3147 * {@link android.net.NetworkAgent}s.
3148 * @hide
3149 */
3150 @SystemApi
3151 @RequiresPermission(anyOf = {
3152 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3153 android.Manifest.permission.NETWORK_FACTORY})
3154 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3155 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3156 throw new IllegalStateException("NetworkProviders can only be registered once");
3157 }
3158
3159 try {
3160 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3161 provider.getName());
3162 provider.setProviderId(providerId);
3163 } catch (RemoteException e) {
3164 throw e.rethrowFromSystemServer();
3165 }
3166 return provider.getProviderId();
3167 }
3168
3169 /**
3170 * Unregisters the specified NetworkProvider.
3171 *
3172 * @param provider the provider to unregister
3173 * @hide
3174 */
3175 @SystemApi
3176 @RequiresPermission(anyOf = {
3177 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3178 android.Manifest.permission.NETWORK_FACTORY})
3179 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3180 try {
3181 mService.unregisterNetworkProvider(provider.getMessenger());
3182 } catch (RemoteException e) {
3183 throw e.rethrowFromSystemServer();
3184 }
3185 provider.setProviderId(NetworkProvider.ID_NONE);
3186 }
3187
3188
3189 /** @hide exposed via the NetworkProvider class. */
3190 @RequiresPermission(anyOf = {
3191 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3192 android.Manifest.permission.NETWORK_FACTORY})
3193 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3194 try {
3195 mService.declareNetworkRequestUnfulfillable(request);
3196 } catch (RemoteException e) {
3197 throw e.rethrowFromSystemServer();
3198 }
3199 }
3200
3201 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3202 // of dependent changes that would conflict throughout the automerger graph. Having this
3203 // temporarily helps with the process of going through with all these dependent changes across
3204 // the entire tree.
3205 /**
3206 * @hide
3207 * Register a NetworkAgent with ConnectivityService.
3208 * @return Network corresponding to NetworkAgent.
3209 */
3210 @RequiresPermission(anyOf = {
3211 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3212 android.Manifest.permission.NETWORK_FACTORY})
3213 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
3214 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
3215 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
3216 }
3217
3218 /**
3219 * @hide
3220 * Register a NetworkAgent with ConnectivityService.
3221 * @return Network corresponding to NetworkAgent.
3222 */
3223 @RequiresPermission(anyOf = {
3224 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3225 android.Manifest.permission.NETWORK_FACTORY})
3226 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
3227 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
3228 try {
3229 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3230 } catch (RemoteException e) {
3231 throw e.rethrowFromSystemServer();
3232 }
3233 }
3234
3235 /**
3236 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3237 * changes. Should be extended by applications wanting notifications.
3238 *
3239 * A {@code NetworkCallback} is registered by calling
3240 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3241 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3242 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3243 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3244 * A {@code NetworkCallback} should be registered at most once at any time.
3245 * A {@code NetworkCallback} that has been unregistered can be registered again.
3246 */
3247 public static class NetworkCallback {
3248 /**
3249 * Called when the framework connects to a new network to evaluate whether it satisfies this
3250 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3251 * callback. There is no guarantee that this new network will satisfy any requests, or that
3252 * the network will stay connected for longer than the time necessary to evaluate it.
3253 * <p>
3254 * Most applications <b>should not</b> act on this callback, and should instead use
3255 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3256 * the framework in properly evaluating the network &mdash; for example, an application that
3257 * can automatically log in to a captive portal without user intervention.
3258 *
3259 * @param network The {@link Network} of the network that is being evaluated.
3260 *
3261 * @hide
3262 */
3263 public void onPreCheck(@NonNull Network network) {}
3264
3265 /**
3266 * Called when the framework connects and has declared a new network ready for use.
3267 * This callback may be called more than once if the {@link Network} that is
3268 * satisfying the request changes.
3269 *
3270 * @param network The {@link Network} of the satisfying network.
3271 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3272 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3273 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3274 * @hide
3275 */
3276 public void onAvailable(@NonNull Network network,
3277 @NonNull NetworkCapabilities networkCapabilities,
3278 @NonNull LinkProperties linkProperties, boolean blocked) {
3279 // Internally only this method is called when a new network is available, and
3280 // it calls the callback in the same way and order that older versions used
3281 // to call so as not to change the behavior.
3282 onAvailable(network);
3283 if (!networkCapabilities.hasCapability(
3284 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3285 onNetworkSuspended(network);
3286 }
3287 onCapabilitiesChanged(network, networkCapabilities);
3288 onLinkPropertiesChanged(network, linkProperties);
3289 onBlockedStatusChanged(network, blocked);
3290 }
3291
3292 /**
3293 * Called when the framework connects and has declared a new network ready for use.
3294 *
3295 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3296 * be available at the same time, and onAvailable will be called for each of these as they
3297 * appear.
3298 *
3299 * <p>For callbacks registered with {@link #requestNetwork} and
3300 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3301 * is the new best network for this request and is now tracked by this callback ; this
3302 * callback will no longer receive method calls about other networks that may have been
3303 * passed to this method previously. The previously-best network may have disconnected, or
3304 * it may still be around and the newly-best network may simply be better.
3305 *
3306 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3307 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3308 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3309 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3310 *
3311 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3312 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3313 * this callback as this is prone to race conditions (there is no guarantee the objects
3314 * returned by these methods will be current). Instead, wait for a call to
3315 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3316 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3317 * to be well-ordered with respect to other callbacks.
3318 *
3319 * @param network The {@link Network} of the satisfying network.
3320 */
3321 public void onAvailable(@NonNull Network network) {}
3322
3323 /**
3324 * Called when the network is about to be lost, typically because there are no outstanding
3325 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3326 * with the new replacement network for graceful handover. This method is not guaranteed
3327 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3328 * network is suddenly disconnected.
3329 *
3330 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3331 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3332 * this callback as this is prone to race conditions ; calling these methods while in a
3333 * callback may return an outdated or even a null object.
3334 *
3335 * @param network The {@link Network} that is about to be lost.
3336 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3337 * connected for graceful handover; note that the network may still
3338 * suffer a hard loss at any time.
3339 */
3340 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3341
3342 /**
3343 * Called when a network disconnects or otherwise no longer satisfies this request or
3344 * callback.
3345 *
3346 * <p>If the callback was registered with requestNetwork() or
3347 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3348 * returned by onAvailable() when that network is lost and no other network satisfies
3349 * the criteria of the request.
3350 *
3351 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3352 * each network which no longer satisfies the criteria of the callback.
3353 *
3354 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3355 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3356 * this callback as this is prone to race conditions ; calling these methods while in a
3357 * callback may return an outdated or even a null object.
3358 *
3359 * @param network The {@link Network} lost.
3360 */
3361 public void onLost(@NonNull Network network) {}
3362
3363 /**
3364 * Called if no network is found within the timeout time specified in
3365 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3366 * requested network request cannot be fulfilled (whether or not a timeout was
3367 * specified). When this callback is invoked the associated
3368 * {@link NetworkRequest} will have already been removed and released, as if
3369 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3370 */
3371 public void onUnavailable() {}
3372
3373 /**
3374 * Called when the network corresponding to this request changes capabilities but still
3375 * satisfies the requested criteria.
3376 *
3377 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3378 * to be called immediately after {@link #onAvailable}.
3379 *
3380 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3381 * ConnectivityManager methods in this callback as this is prone to race conditions :
3382 * calling these methods while in a callback may return an outdated or even a null object.
3383 *
3384 * @param network The {@link Network} whose capabilities have changed.
3385 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3386 * network.
3387 */
3388 public void onCapabilitiesChanged(@NonNull Network network,
3389 @NonNull NetworkCapabilities networkCapabilities) {}
3390
3391 /**
3392 * Called when the network corresponding to this request changes {@link LinkProperties}.
3393 *
3394 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3395 * to be called immediately after {@link #onAvailable}.
3396 *
3397 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3398 * ConnectivityManager methods in this callback as this is prone to race conditions :
3399 * calling these methods while in a callback may return an outdated or even a null object.
3400 *
3401 * @param network The {@link Network} whose link properties have changed.
3402 * @param linkProperties The new {@link LinkProperties} for this network.
3403 */
3404 public void onLinkPropertiesChanged(@NonNull Network network,
3405 @NonNull LinkProperties linkProperties) {}
3406
3407 /**
3408 * Called when the network the framework connected to for this request suspends data
3409 * transmission temporarily.
3410 *
3411 * <p>This generally means that while the TCP connections are still live temporarily
3412 * network data fails to transfer. To give a specific example, this is used on cellular
3413 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3414 * means read operations on sockets on this network will block once the buffers are
3415 * drained, and write operations will block once the buffers are full.
3416 *
3417 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3418 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3419 * this callback as this is prone to race conditions (there is no guarantee the objects
3420 * returned by these methods will be current).
3421 *
3422 * @hide
3423 */
3424 public void onNetworkSuspended(@NonNull Network network) {}
3425
3426 /**
3427 * Called when the network the framework connected to for this request
3428 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3429 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3430
3431 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3432 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3433 * this callback as this is prone to race conditions : calling these methods while in a
3434 * callback may return an outdated or even a null object.
3435 *
3436 * @hide
3437 */
3438 public void onNetworkResumed(@NonNull Network network) {}
3439
3440 /**
3441 * Called when access to the specified network is blocked or unblocked.
3442 *
3443 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3444 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3445 * this callback as this is prone to race conditions : calling these methods while in a
3446 * callback may return an outdated or even a null object.
3447 *
3448 * @param network The {@link Network} whose blocked status has changed.
3449 * @param blocked The blocked status of this {@link Network}.
3450 */
3451 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3452
3453 private NetworkRequest networkRequest;
3454 }
3455
3456 /**
3457 * Constant error codes used by ConnectivityService to communicate about failures and errors
3458 * across a Binder boundary.
3459 * @hide
3460 */
3461 public interface Errors {
3462 int TOO_MANY_REQUESTS = 1;
3463 }
3464
3465 /** @hide */
3466 public static class TooManyRequestsException extends RuntimeException {}
3467
3468 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3469 switch (e.errorCode) {
3470 case Errors.TOO_MANY_REQUESTS:
3471 return new TooManyRequestsException();
3472 default:
3473 Log.w(TAG, "Unknown service error code " + e.errorCode);
3474 return new RuntimeException(e);
3475 }
3476 }
3477
3478 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
3479 /** @hide */
3480 public static final int CALLBACK_PRECHECK = BASE + 1;
3481 /** @hide */
3482 public static final int CALLBACK_AVAILABLE = BASE + 2;
3483 /** @hide arg1 = TTL */
3484 public static final int CALLBACK_LOSING = BASE + 3;
3485 /** @hide */
3486 public static final int CALLBACK_LOST = BASE + 4;
3487 /** @hide */
3488 public static final int CALLBACK_UNAVAIL = BASE + 5;
3489 /** @hide */
3490 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3491 /** @hide */
3492 public static final int CALLBACK_IP_CHANGED = BASE + 7;
3493 /** @hide obj = NetworkCapabilities, arg1 = seq number */
3494 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
3495 /** @hide */
3496 public static final int CALLBACK_SUSPENDED = BASE + 9;
3497 /** @hide */
3498 public static final int CALLBACK_RESUMED = BASE + 10;
3499 /** @hide */
3500 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
3501
3502 /** @hide */
3503 public static String getCallbackName(int whichCallback) {
3504 switch (whichCallback) {
3505 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3506 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3507 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3508 case CALLBACK_LOST: return "CALLBACK_LOST";
3509 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3510 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3511 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
3512 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3513 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3514 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
3515 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
3516 default:
3517 return Integer.toString(whichCallback);
3518 }
3519 }
3520
3521 private class CallbackHandler extends Handler {
3522 private static final String TAG = "ConnectivityManager.CallbackHandler";
3523 private static final boolean DBG = false;
3524
3525 CallbackHandler(Looper looper) {
3526 super(looper);
3527 }
3528
3529 CallbackHandler(Handler handler) {
3530 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
3531 }
3532
3533 @Override
3534 public void handleMessage(Message message) {
3535 if (message.what == EXPIRE_LEGACY_REQUEST) {
3536 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3537 return;
3538 }
3539
3540 final NetworkRequest request = getObject(message, NetworkRequest.class);
3541 final Network network = getObject(message, Network.class);
3542 final NetworkCallback callback;
3543 synchronized (sCallbacks) {
3544 callback = sCallbacks.get(request);
3545 if (callback == null) {
3546 Log.w(TAG,
3547 "callback not found for " + getCallbackName(message.what) + " message");
3548 return;
3549 }
3550 if (message.what == CALLBACK_UNAVAIL) {
3551 sCallbacks.remove(request);
3552 callback.networkRequest = ALREADY_UNREGISTERED;
3553 }
3554 }
3555 if (DBG) {
3556 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
3557 }
3558
3559 switch (message.what) {
3560 case CALLBACK_PRECHECK: {
3561 callback.onPreCheck(network);
3562 break;
3563 }
3564 case CALLBACK_AVAILABLE: {
3565 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3566 LinkProperties lp = getObject(message, LinkProperties.class);
3567 callback.onAvailable(network, cap, lp, message.arg1 != 0);
3568 break;
3569 }
3570 case CALLBACK_LOSING: {
3571 callback.onLosing(network, message.arg1);
3572 break;
3573 }
3574 case CALLBACK_LOST: {
3575 callback.onLost(network);
3576 break;
3577 }
3578 case CALLBACK_UNAVAIL: {
3579 callback.onUnavailable();
3580 break;
3581 }
3582 case CALLBACK_CAP_CHANGED: {
3583 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3584 callback.onCapabilitiesChanged(network, cap);
3585 break;
3586 }
3587 case CALLBACK_IP_CHANGED: {
3588 LinkProperties lp = getObject(message, LinkProperties.class);
3589 callback.onLinkPropertiesChanged(network, lp);
3590 break;
3591 }
3592 case CALLBACK_SUSPENDED: {
3593 callback.onNetworkSuspended(network);
3594 break;
3595 }
3596 case CALLBACK_RESUMED: {
3597 callback.onNetworkResumed(network);
3598 break;
3599 }
3600 case CALLBACK_BLK_CHANGED: {
3601 boolean blocked = message.arg1 != 0;
3602 callback.onBlockedStatusChanged(network, blocked);
3603 }
3604 }
3605 }
3606
3607 private <T> T getObject(Message msg, Class<T> c) {
3608 return (T) msg.getData().getParcelable(c.getSimpleName());
3609 }
3610 }
3611
3612 private CallbackHandler getDefaultHandler() {
3613 synchronized (sCallbacks) {
3614 if (sCallbackHandler == null) {
3615 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
3616 }
3617 return sCallbackHandler;
3618 }
3619 }
3620
3621 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3622 private static CallbackHandler sCallbackHandler;
3623
3624 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3625 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3626 printStackTrace();
3627 checkCallbackNotNull(callback);
3628 Preconditions.checkArgument(
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09003629 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3630 "null NetworkCapabilities");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003631 final NetworkRequest request;
3632 final String callingPackageName = mContext.getOpPackageName();
3633 try {
3634 synchronized(sCallbacks) {
3635 if (callback.networkRequest != null
3636 && callback.networkRequest != ALREADY_UNREGISTERED) {
3637 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3638 // and requests (http://b/20701525).
3639 Log.e(TAG, "NetworkCallback was already registered");
3640 }
3641 Messenger messenger = new Messenger(handler);
3642 Binder binder = new Binder();
3643 if (reqType == LISTEN) {
3644 request = mService.listenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08003645 need, messenger, binder, callingPackageName,
3646 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003647 } else {
3648 request = mService.requestNetwork(
3649 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3650 callingPackageName, getAttributionTag());
3651 }
3652 if (request != null) {
3653 sCallbacks.put(request, callback);
3654 }
3655 callback.networkRequest = request;
3656 }
3657 } catch (RemoteException e) {
3658 throw e.rethrowFromSystemServer();
3659 } catch (ServiceSpecificException e) {
3660 throw convertServiceException(e);
3661 }
3662 return request;
3663 }
3664
3665 /**
3666 * Helper function to request a network with a particular legacy type.
3667 *
3668 * This API is only for use in internal system code that requests networks with legacy type and
3669 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
3670 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
3671 *
3672 * @param request {@link NetworkRequest} describing this request.
3673 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3674 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3675 * be a positive value (i.e. >0).
3676 * @param legacyType to specify the network type(#TYPE_*).
3677 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3678 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3679 * the callback must not be shared - it uniquely specifies this request.
3680 *
3681 * @hide
3682 */
3683 @SystemApi
3684 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
3685 public void requestNetwork(@NonNull NetworkRequest request,
3686 int timeoutMs, int legacyType, @NonNull Handler handler,
3687 @NonNull NetworkCallback networkCallback) {
3688 if (legacyType == TYPE_NONE) {
3689 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3690 }
3691 CallbackHandler cbHandler = new CallbackHandler(handler);
3692 NetworkCapabilities nc = request.networkCapabilities;
3693 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
3694 }
3695
3696 /**
3697 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3698 *
3699 * <p>This method will attempt to find the best network that matches the passed
3700 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3701 * criteria. The platform will evaluate which network is the best at its own discretion.
3702 * Throughput, latency, cost per byte, policy, user preference and other considerations
3703 * may be factored in the decision of what is considered the best network.
3704 *
3705 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3706 * matching this request, while always attempting to match the request to a better network if
3707 * possible. If a better match is found, the platform will switch this request to the now-best
3708 * network and inform the app of the newly best network by invoking
3709 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3710 * will not try to maintain any other network than the best one currently matching the request:
3711 * a network not matching any network request may be disconnected at any time.
3712 *
3713 * <p>For example, an application could use this method to obtain a connected cellular network
3714 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3715 * radio to consume additional power. Or, an application could inform the system that it wants
3716 * a network supporting sending MMSes and have the system let it know about the currently best
3717 * MMS-supporting network through the provided {@link NetworkCallback}.
3718 *
3719 * <p>The status of the request can be followed by listening to the various callbacks described
3720 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3721 * used to direct traffic to the network (although accessing some networks may be subject to
3722 * holding specific permissions). Callers will learn about the specific characteristics of the
3723 * network through
3724 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3725 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3726 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3727 * matching the request at any given time; therefore when a better network matching the request
3728 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3729 * with the new network after which no further updates are given about the previously-best
3730 * network, unless it becomes the best again at some later time. All callbacks are invoked
3731 * in order on the same thread, which by default is a thread created by the framework running
3732 * in the app.
3733 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3734 * callbacks are invoked.
3735 *
3736 * <p>This{@link NetworkRequest} will live until released via
3737 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3738 * which point the system may let go of the network at any time.
3739 *
3740 * <p>A version of this method which takes a timeout is
3741 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3742 * wait for a limited amount of time for the network to become unavailable.
3743 *
3744 * <p>It is presently unsupported to request a network with mutable
3745 * {@link NetworkCapabilities} such as
3746 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3747 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3748 * as these {@code NetworkCapabilities} represent states that a particular
3749 * network may never attain, and whether a network will attain these states
3750 * is unknown prior to bringing up the network so the framework does not
3751 * know how to go about satisfying a request with these capabilities.
3752 *
3753 * <p>This method requires the caller to hold either the
3754 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3755 * or the ability to modify system settings as determined by
3756 * {@link android.provider.Settings.System#canWrite}.</p>
3757 *
3758 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3759 * number of outstanding requests to 100 per app (identified by their UID), shared with
3760 * all variants of this method, of {@link #registerNetworkCallback} as well as
3761 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3762 * Requesting a network with this method will count toward this limit. If this limit is
3763 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3764 * make sure to unregister the callbacks with
3765 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3766 *
3767 * @param request {@link NetworkRequest} describing this request.
3768 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3769 * the callback must not be shared - it uniquely specifies this request.
3770 * The callback is invoked on the default internal Handler.
3771 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3772 * @throws SecurityException if missing the appropriate permissions.
3773 * @throws RuntimeException if the app already has too many callbacks registered.
3774 */
3775 public void requestNetwork(@NonNull NetworkRequest request,
3776 @NonNull NetworkCallback networkCallback) {
3777 requestNetwork(request, networkCallback, getDefaultHandler());
3778 }
3779
3780 /**
3781 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3782 *
3783 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3784 * but runs all the callbacks on the passed Handler.
3785 *
3786 * <p>This method has the same permission requirements as
3787 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3788 * and throws the same exceptions in the same conditions.
3789 *
3790 * @param request {@link NetworkRequest} describing this request.
3791 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3792 * the callback must not be shared - it uniquely specifies this request.
3793 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3794 */
3795 public void requestNetwork(@NonNull NetworkRequest request,
3796 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
3797 CallbackHandler cbHandler = new CallbackHandler(handler);
3798 NetworkCapabilities nc = request.networkCapabilities;
3799 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
3800 }
3801
3802 /**
3803 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3804 * by a timeout.
3805 *
3806 * This function behaves identically to the non-timed-out version
3807 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3808 * is not found within the given time (in milliseconds) the
3809 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3810 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3811 * not have to be released if timed-out (it is automatically released). Unregistering a
3812 * request that timed out is not an error.
3813 *
3814 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3815 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3816 * for that purpose. Calling this method will attempt to bring up the requested network.
3817 *
3818 * <p>This method has the same permission requirements as
3819 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3820 * and throws the same exceptions in the same conditions.
3821 *
3822 * @param request {@link NetworkRequest} describing this request.
3823 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3824 * the callback must not be shared - it uniquely specifies this request.
3825 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3826 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3827 * be a positive value (i.e. >0).
3828 */
3829 public void requestNetwork(@NonNull NetworkRequest request,
3830 @NonNull NetworkCallback networkCallback, int timeoutMs) {
3831 checkTimeout(timeoutMs);
3832 NetworkCapabilities nc = request.networkCapabilities;
3833 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3834 getDefaultHandler());
3835 }
3836
3837 /**
3838 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3839 * by a timeout.
3840 *
3841 * This method behaves identically to
3842 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3843 * on the passed Handler.
3844 *
3845 * <p>This method has the same permission requirements as
3846 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3847 * and throws the same exceptions in the same conditions.
3848 *
3849 * @param request {@link NetworkRequest} describing this request.
3850 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3851 * the callback must not be shared - it uniquely specifies this request.
3852 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3853 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3854 * before {@link NetworkCallback#onUnavailable} is called.
3855 */
3856 public void requestNetwork(@NonNull NetworkRequest request,
3857 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
3858 checkTimeout(timeoutMs);
3859 CallbackHandler cbHandler = new CallbackHandler(handler);
3860 NetworkCapabilities nc = request.networkCapabilities;
3861 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
3862 }
3863
3864 /**
3865 * The lookup key for a {@link Network} object included with the intent after
3866 * successfully finding a network for the applications request. Retrieve it with
3867 * {@link android.content.Intent#getParcelableExtra(String)}.
3868 * <p>
3869 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3870 * then you must get a ConnectivityManager instance before doing so.
3871 */
3872 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
3873
3874 /**
3875 * The lookup key for a {@link NetworkRequest} object included with the intent after
3876 * successfully finding a network for the applications request. Retrieve it with
3877 * {@link android.content.Intent#getParcelableExtra(String)}.
3878 */
3879 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
3880
3881
3882 /**
3883 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3884 *
3885 * This function behaves identically to the version that takes a NetworkCallback, but instead
3886 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3887 * the request may outlive the calling application and get called back when a suitable
3888 * network is found.
3889 * <p>
3890 * The operation is an Intent broadcast that goes to a broadcast receiver that
3891 * you registered with {@link Context#registerReceiver} or through the
3892 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3893 * <p>
3894 * The operation Intent is delivered with two extras, a {@link Network} typed
3895 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3896 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3897 * the original requests parameters. It is important to create a new,
3898 * {@link NetworkCallback} based request before completing the processing of the
3899 * Intent to reserve the network or it will be released shortly after the Intent
3900 * is processed.
3901 * <p>
3902 * If there is already a request for this Intent registered (with the equality of
3903 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3904 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3905 * <p>
3906 * The request may be released normally by calling
3907 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
3908 * <p>It is presently unsupported to request a network with either
3909 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3910 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3911 * as these {@code NetworkCapabilities} represent states that a particular
3912 * network may never attain, and whether a network will attain these states
3913 * is unknown prior to bringing up the network so the framework does not
3914 * know how to go about satisfying a request with these capabilities.
3915 *
3916 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3917 * number of outstanding requests to 100 per app (identified by their UID), shared with
3918 * all variants of this method, of {@link #registerNetworkCallback} as well as
3919 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3920 * Requesting a network with this method will count toward this limit. If this limit is
3921 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3922 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3923 * or {@link #releaseNetworkRequest(PendingIntent)}.
3924 *
3925 * <p>This method requires the caller to hold either the
3926 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3927 * or the ability to modify system settings as determined by
3928 * {@link android.provider.Settings.System#canWrite}.</p>
3929 *
3930 * @param request {@link NetworkRequest} describing this request.
3931 * @param operation Action to perform when the network is available (corresponds
3932 * to the {@link NetworkCallback#onAvailable} call. Typically
3933 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3934 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3935 * @throws SecurityException if missing the appropriate permissions.
3936 * @throws RuntimeException if the app already has too many callbacks registered.
3937 */
3938 public void requestNetwork(@NonNull NetworkRequest request,
3939 @NonNull PendingIntent operation) {
3940 printStackTrace();
3941 checkPendingIntentNotNull(operation);
3942 try {
3943 mService.pendingRequestForNetwork(
3944 request.networkCapabilities, operation, mContext.getOpPackageName(),
3945 getAttributionTag());
3946 } catch (RemoteException e) {
3947 throw e.rethrowFromSystemServer();
3948 } catch (ServiceSpecificException e) {
3949 throw convertServiceException(e);
3950 }
3951 }
3952
3953 /**
3954 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3955 * <p>
3956 * This method has the same behavior as
3957 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
3958 * releasing network resources and disconnecting.
3959 *
3960 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3961 * PendingIntent passed to
3962 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3963 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3964 */
3965 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
3966 printStackTrace();
3967 checkPendingIntentNotNull(operation);
3968 try {
3969 mService.releasePendingNetworkRequest(operation);
3970 } catch (RemoteException e) {
3971 throw e.rethrowFromSystemServer();
3972 }
3973 }
3974
3975 private static void checkPendingIntentNotNull(PendingIntent intent) {
3976 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3977 }
3978
3979 private static void checkCallbackNotNull(NetworkCallback callback) {
3980 Preconditions.checkNotNull(callback, "null NetworkCallback");
3981 }
3982
3983 private static void checkTimeout(int timeoutMs) {
3984 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
3985 }
3986
3987 /**
3988 * Registers to receive notifications about all networks which satisfy the given
3989 * {@link NetworkRequest}. The callbacks will continue to be called until
3990 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3991 * called.
3992 *
3993 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3994 * number of outstanding requests to 100 per app (identified by their UID), shared with
3995 * all variants of this method, of {@link #requestNetwork} as well as
3996 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3997 * Requesting a network with this method will count toward this limit. If this limit is
3998 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3999 * make sure to unregister the callbacks with
4000 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4001 *
4002 * @param request {@link NetworkRequest} describing this request.
4003 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4004 * networks change state.
4005 * The callback is invoked on the default internal Handler.
4006 * @throws RuntimeException if the app already has too many callbacks registered.
4007 */
4008 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4009 public void registerNetworkCallback(@NonNull NetworkRequest request,
4010 @NonNull NetworkCallback networkCallback) {
4011 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4012 }
4013
4014 /**
4015 * Registers to receive notifications about all networks which satisfy the given
4016 * {@link NetworkRequest}. The callbacks will continue to be called until
4017 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4018 * called.
4019 *
4020 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4021 * number of outstanding requests to 100 per app (identified by their UID), shared with
4022 * all variants of this method, of {@link #requestNetwork} as well as
4023 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4024 * Requesting a network with this method will count toward this limit. If this limit is
4025 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4026 * make sure to unregister the callbacks with
4027 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4028 *
4029 *
4030 * @param request {@link NetworkRequest} describing this request.
4031 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4032 * networks change state.
4033 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4034 * @throws RuntimeException if the app already has too many callbacks registered.
4035 */
4036 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4037 public void registerNetworkCallback(@NonNull NetworkRequest request,
4038 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4039 CallbackHandler cbHandler = new CallbackHandler(handler);
4040 NetworkCapabilities nc = request.networkCapabilities;
4041 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4042 }
4043
4044 /**
4045 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4046 * {@link NetworkRequest}.
4047 *
4048 * This function behaves identically to the version that takes a NetworkCallback, but instead
4049 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4050 * the request may outlive the calling application and get called back when a suitable
4051 * network is found.
4052 * <p>
4053 * The operation is an Intent broadcast that goes to a broadcast receiver that
4054 * you registered with {@link Context#registerReceiver} or through the
4055 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4056 * <p>
4057 * The operation Intent is delivered with two extras, a {@link Network} typed
4058 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4059 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4060 * the original requests parameters.
4061 * <p>
4062 * If there is already a request for this Intent registered (with the equality of
4063 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4064 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4065 * <p>
4066 * The request may be released normally by calling
4067 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4068 *
4069 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4070 * number of outstanding requests to 100 per app (identified by their UID), shared with
4071 * all variants of this method, of {@link #requestNetwork} as well as
4072 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4073 * Requesting a network with this method will count toward this limit. If this limit is
4074 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4075 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4076 * or {@link #releaseNetworkRequest(PendingIntent)}.
4077 *
4078 * @param request {@link NetworkRequest} describing this request.
4079 * @param operation Action to perform when the network is available (corresponds
4080 * to the {@link NetworkCallback#onAvailable} call. Typically
4081 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4082 * @throws RuntimeException if the app already has too many callbacks registered.
4083 */
4084 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4085 public void registerNetworkCallback(@NonNull NetworkRequest request,
4086 @NonNull PendingIntent operation) {
4087 printStackTrace();
4088 checkPendingIntentNotNull(operation);
4089 try {
4090 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004091 request.networkCapabilities, operation, mContext.getOpPackageName(),
4092 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004093 } catch (RemoteException e) {
4094 throw e.rethrowFromSystemServer();
4095 } catch (ServiceSpecificException e) {
4096 throw convertServiceException(e);
4097 }
4098 }
4099
4100 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004101 * Registers to receive notifications about changes in the application's default network. This
4102 * may be a physical network or a virtual network, such as a VPN that applies to the
4103 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004104 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4105 *
4106 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4107 * number of outstanding requests to 100 per app (identified by their UID), shared with
4108 * all variants of this method, of {@link #requestNetwork} as well as
4109 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4110 * Requesting a network with this method will count toward this limit. If this limit is
4111 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4112 * make sure to unregister the callbacks with
4113 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4114 *
4115 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004116 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004117 * The callback is invoked on the default internal Handler.
4118 * @throws RuntimeException if the app already has too many callbacks registered.
4119 */
4120 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4121 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4122 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4123 }
4124
4125 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004126 * Registers to receive notifications about changes in the application's default network. This
4127 * may be a physical network or a virtual network, such as a VPN that applies to the
4128 * application. The callbacks will continue to be called until either the application exits or
4129 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4130 *
4131 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4132 * number of outstanding requests to 100 per app (identified by their UID), shared with
4133 * all variants of this method, of {@link #requestNetwork} as well as
4134 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4135 * Requesting a network with this method will count toward this limit. If this limit is
4136 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4137 * make sure to unregister the callbacks with
4138 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4139 *
4140 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4141 * application's default network changes.
4142 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4143 * @throws RuntimeException if the app already has too many callbacks registered.
4144 */
4145 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4146 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4147 @NonNull Handler handler) {
4148 CallbackHandler cbHandler = new CallbackHandler(handler);
4149 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4150 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4151 }
4152
4153 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004154 * Registers to receive notifications about changes in the system default network. The callbacks
4155 * will continue to be called until either the application exits or
4156 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4157 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004158 * This method should not be used to determine networking state seen by applications, because in
4159 * many cases, most or even all application traffic may not use the default network directly,
4160 * and traffic from different applications may go on different networks by default. As an
4161 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4162 * and not onto the system default network. Applications or system components desiring to do
4163 * determine network state as seen by applications should use other methods such as
4164 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4165 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004166 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4167 * number of outstanding requests to 100 per app (identified by their UID), shared with
4168 * all variants of this method, of {@link #requestNetwork} as well as
4169 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4170 * Requesting a network with this method will count toward this limit. If this limit is
4171 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4172 * make sure to unregister the callbacks with
4173 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4174 *
4175 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4176 * system default network changes.
4177 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4178 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004179 *
4180 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004181 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004182 @SystemApi(client = MODULE_LIBRARIES)
4183 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4184 @RequiresPermission(anyOf = {
4185 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4186 android.Manifest.permission.NETWORK_SETTINGS})
4187 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004188 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004189 CallbackHandler cbHandler = new CallbackHandler(handler);
4190 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004191 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004192 }
4193
4194 /**
4195 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4196 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4197 * network connection for updated bandwidth information. The caller will be notified via
4198 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4199 * method assumes that the caller has previously called
4200 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4201 * changes.
4202 *
4203 * @param network {@link Network} specifying which network you're interested.
4204 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4205 */
4206 public boolean requestBandwidthUpdate(@NonNull Network network) {
4207 try {
4208 return mService.requestBandwidthUpdate(network);
4209 } catch (RemoteException e) {
4210 throw e.rethrowFromSystemServer();
4211 }
4212 }
4213
4214 /**
4215 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4216 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4217 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4218 * If the given {@code NetworkCallback} had previously been used with
4219 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4220 * will be disconnected.
4221 *
4222 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4223 * triggering it as soon as this call returns.
4224 *
4225 * @param networkCallback The {@link NetworkCallback} used when making the request.
4226 */
4227 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4228 printStackTrace();
4229 checkCallbackNotNull(networkCallback);
4230 final List<NetworkRequest> reqs = new ArrayList<>();
4231 // Find all requests associated to this callback and stop callback triggers immediately.
4232 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4233 synchronized (sCallbacks) {
4234 Preconditions.checkArgument(networkCallback.networkRequest != null,
4235 "NetworkCallback was not registered");
4236 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4237 Log.d(TAG, "NetworkCallback was already unregistered");
4238 return;
4239 }
4240 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4241 if (e.getValue() == networkCallback) {
4242 reqs.add(e.getKey());
4243 }
4244 }
4245 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4246 for (NetworkRequest r : reqs) {
4247 try {
4248 mService.releaseNetworkRequest(r);
4249 } catch (RemoteException e) {
4250 throw e.rethrowFromSystemServer();
4251 }
4252 // Only remove mapping if rpc was successful.
4253 sCallbacks.remove(r);
4254 }
4255 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4256 }
4257 }
4258
4259 /**
4260 * Unregisters a callback previously registered via
4261 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4262 *
4263 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4264 * PendingIntent passed to
4265 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4266 * Cannot be null.
4267 */
4268 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4269 releaseNetworkRequest(operation);
4270 }
4271
4272 /**
4273 * Informs the system whether it should switch to {@code network} regardless of whether it is
4274 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4275 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4276 * the system default network regardless of any other network that's currently connected. If
4277 * {@code always} is true, then the choice is remembered, so that the next time the user
4278 * connects to this network, the system will switch to it.
4279 *
4280 * @param network The network to accept.
4281 * @param accept Whether to accept the network even if unvalidated.
4282 * @param always Whether to remember this choice in the future.
4283 *
4284 * @hide
4285 */
4286 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4287 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4288 try {
4289 mService.setAcceptUnvalidated(network, accept, always);
4290 } catch (RemoteException e) {
4291 throw e.rethrowFromSystemServer();
4292 }
4293 }
4294
4295 /**
4296 * Informs the system whether it should consider the network as validated even if it only has
4297 * partial connectivity. If {@code accept} is true, then the network will be considered as
4298 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4299 * is remembered, so that the next time the user connects to this network, the system will
4300 * switch to it.
4301 *
4302 * @param network The network to accept.
4303 * @param accept Whether to consider the network as validated even if it has partial
4304 * connectivity.
4305 * @param always Whether to remember this choice in the future.
4306 *
4307 * @hide
4308 */
4309 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4310 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4311 try {
4312 mService.setAcceptPartialConnectivity(network, accept, always);
4313 } catch (RemoteException e) {
4314 throw e.rethrowFromSystemServer();
4315 }
4316 }
4317
4318 /**
4319 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4320 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4321 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4322 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4323 *
4324 * @param network The network to accept.
4325 *
4326 * @hide
4327 */
4328 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4329 public void setAvoidUnvalidated(Network network) {
4330 try {
4331 mService.setAvoidUnvalidated(network);
4332 } catch (RemoteException e) {
4333 throw e.rethrowFromSystemServer();
4334 }
4335 }
4336
4337 /**
4338 * Requests that the system open the captive portal app on the specified network.
4339 *
4340 * @param network The network to log into.
4341 *
4342 * @hide
4343 */
4344 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4345 public void startCaptivePortalApp(Network network) {
4346 try {
4347 mService.startCaptivePortalApp(network);
4348 } catch (RemoteException e) {
4349 throw e.rethrowFromSystemServer();
4350 }
4351 }
4352
4353 /**
4354 * Requests that the system open the captive portal app with the specified extras.
4355 *
4356 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4357 * corresponding permission.
4358 * @param network Network on which the captive portal was detected.
4359 * @param appExtras Extras to include in the app start intent.
4360 * @hide
4361 */
4362 @SystemApi
4363 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4364 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4365 try {
4366 mService.startCaptivePortalAppInternal(network, appExtras);
4367 } catch (RemoteException e) {
4368 throw e.rethrowFromSystemServer();
4369 }
4370 }
4371
4372 /**
4373 * Determine whether the device is configured to avoid bad wifi.
4374 * @hide
4375 */
4376 @SystemApi
4377 @RequiresPermission(anyOf = {
4378 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4379 android.Manifest.permission.NETWORK_STACK})
4380 public boolean shouldAvoidBadWifi() {
4381 try {
4382 return mService.shouldAvoidBadWifi();
4383 } catch (RemoteException e) {
4384 throw e.rethrowFromSystemServer();
4385 }
4386 }
4387
4388 /**
4389 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4390 * time-sensitive user-facing operations when the system default network is temporarily
4391 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4392 * this method), and the operation should be infrequent to ensure that data usage is limited.
4393 *
4394 * An example of such an operation might be a time-sensitive foreground activity, such as a
4395 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4396 */
4397 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4398
4399 /**
4400 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4401 * a backup channel for traffic that is primarily going over another network.
4402 *
4403 * An example might be maintaining backup connections to peers or servers for the purpose of
4404 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4405 * on backup paths should be negligible compared to the traffic on the main path.
4406 */
4407 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4408
4409 /**
4410 * It is acceptable to use metered data to improve network latency and performance.
4411 */
4412 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4413
4414 /**
4415 * Return value to use for unmetered networks. On such networks we currently set all the flags
4416 * to true.
4417 * @hide
4418 */
4419 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4420 MULTIPATH_PREFERENCE_HANDOVER |
4421 MULTIPATH_PREFERENCE_RELIABILITY |
4422 MULTIPATH_PREFERENCE_PERFORMANCE;
4423
4424 /** @hide */
4425 @Retention(RetentionPolicy.SOURCE)
4426 @IntDef(flag = true, value = {
4427 MULTIPATH_PREFERENCE_HANDOVER,
4428 MULTIPATH_PREFERENCE_RELIABILITY,
4429 MULTIPATH_PREFERENCE_PERFORMANCE,
4430 })
4431 public @interface MultipathPreference {
4432 }
4433
4434 /**
4435 * Provides a hint to the calling application on whether it is desirable to use the
4436 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4437 * for multipath data transfer on this network when it is not the system default network.
4438 * Applications desiring to use multipath network protocols should call this method before
4439 * each such operation.
4440 *
4441 * @param network The network on which the application desires to use multipath data.
4442 * If {@code null}, this method will return the a preference that will generally
4443 * apply to metered networks.
4444 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4445 */
4446 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4447 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
4448 try {
4449 return mService.getMultipathPreference(network);
4450 } catch (RemoteException e) {
4451 throw e.rethrowFromSystemServer();
4452 }
4453 }
4454
4455 /**
4456 * Resets all connectivity manager settings back to factory defaults.
4457 * @hide
4458 */
4459 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
4460 public void factoryReset() {
4461 try {
4462 mService.factoryReset();
4463 mTetheringManager.stopAllTethering();
4464 } catch (RemoteException e) {
4465 throw e.rethrowFromSystemServer();
4466 }
4467 }
4468
4469 /**
4470 * Binds the current process to {@code network}. All Sockets created in the future
4471 * (and not explicitly bound via a bound SocketFactory from
4472 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4473 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4474 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4475 * work and all host name resolutions will fail. This is by design so an application doesn't
4476 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4477 * To clear binding pass {@code null} for {@code network}. Using individually bound
4478 * Sockets created by Network.getSocketFactory().createSocket() and
4479 * performing network-specific host name resolutions via
4480 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4481 * {@code bindProcessToNetwork}.
4482 *
4483 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4484 * the current binding.
4485 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4486 */
4487 public boolean bindProcessToNetwork(@Nullable Network network) {
4488 // Forcing callers to call through non-static function ensures ConnectivityManager
4489 // instantiated.
4490 return setProcessDefaultNetwork(network);
4491 }
4492
4493 /**
4494 * Binds the current process to {@code network}. All Sockets created in the future
4495 * (and not explicitly bound via a bound SocketFactory from
4496 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4497 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4498 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4499 * work and all host name resolutions will fail. This is by design so an application doesn't
4500 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4501 * To clear binding pass {@code null} for {@code network}. Using individually bound
4502 * Sockets created by Network.getSocketFactory().createSocket() and
4503 * performing network-specific host name resolutions via
4504 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4505 * {@code setProcessDefaultNetwork}.
4506 *
4507 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4508 * the current binding.
4509 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4510 * @deprecated This function can throw {@link IllegalStateException}. Use
4511 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4512 * is a direct replacement.
4513 */
4514 @Deprecated
4515 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
4516 int netId = (network == null) ? NETID_UNSET : network.netId;
4517 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4518
4519 if (netId != NETID_UNSET) {
4520 netId = network.getNetIdForResolv();
4521 }
4522
4523 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4524 return false;
4525 }
4526
4527 if (!isSameNetId) {
4528 // Set HTTP proxy system properties to match network.
4529 // TODO: Deprecate this static method and replace it with a non-static version.
4530 try {
Remi NGUYEN VAN345c2df2021-02-03 10:18:20 +09004531 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004532 } catch (SecurityException e) {
4533 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4534 Log.e(TAG, "Can't set proxy properties", e);
4535 }
4536 // Must flush DNS cache as new network may have different DNS resolutions.
4537 InetAddress.clearDnsCache();
4538 // Must flush socket pool as idle sockets will be bound to previous network and may
4539 // cause subsequent fetches to be performed on old network.
4540 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
4541 }
4542
4543 return true;
4544 }
4545
4546 /**
4547 * Returns the {@link Network} currently bound to this process via
4548 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4549 *
4550 * @return {@code Network} to which this process is bound, or {@code null}.
4551 */
4552 @Nullable
4553 public Network getBoundNetworkForProcess() {
4554 // Forcing callers to call thru non-static function ensures ConnectivityManager
4555 // instantiated.
4556 return getProcessDefaultNetwork();
4557 }
4558
4559 /**
4560 * Returns the {@link Network} currently bound to this process via
4561 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4562 *
4563 * @return {@code Network} to which this process is bound, or {@code null}.
4564 * @deprecated Using this function can lead to other functions throwing
4565 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4566 * {@code getBoundNetworkForProcess} is a direct replacement.
4567 */
4568 @Deprecated
4569 @Nullable
4570 public static Network getProcessDefaultNetwork() {
4571 int netId = NetworkUtils.getBoundNetworkForProcess();
4572 if (netId == NETID_UNSET) return null;
4573 return new Network(netId);
4574 }
4575
4576 private void unsupportedStartingFrom(int version) {
4577 if (Process.myUid() == Process.SYSTEM_UID) {
4578 // The getApplicationInfo() call we make below is not supported in system context. Let
4579 // the call through here, and rely on the fact that ConnectivityService will refuse to
4580 // allow the system to use these APIs anyway.
4581 return;
4582 }
4583
4584 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4585 throw new UnsupportedOperationException(
4586 "This method is not supported in target SDK version " + version + " and above");
4587 }
4588 }
4589
4590 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4591 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
4592 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
4593 // remove these exemptions. Note that this check is not secure, and apps can still access these
4594 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4595 // so is unsupported and may break in the future. http://b/22728205
4596 private void checkLegacyRoutingApiAccess() {
4597 unsupportedStartingFrom(VERSION_CODES.M);
4598 }
4599
4600 /**
4601 * Binds host resolutions performed by this process to {@code network}.
4602 * {@link #bindProcessToNetwork} takes precedence over this setting.
4603 *
4604 * @param network The {@link Network} to bind host resolutions from the current process to, or
4605 * {@code null} to clear the current binding.
4606 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4607 * @hide
4608 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4609 */
4610 @Deprecated
4611 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4612 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
4613 return NetworkUtils.bindProcessToNetworkForHostResolution(
4614 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
4615 }
4616
4617 /**
4618 * Device is not restricting metered network activity while application is running on
4619 * background.
4620 */
4621 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4622
4623 /**
4624 * Device is restricting metered network activity while application is running on background,
4625 * but application is allowed to bypass it.
4626 * <p>
4627 * In this state, application should take action to mitigate metered network access.
4628 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4629 */
4630 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4631
4632 /**
4633 * Device is restricting metered network activity while application is running on background.
4634 * <p>
4635 * In this state, application should not try to use the network while running on background,
4636 * because it would be denied.
4637 */
4638 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4639
4640 /**
4641 * A change in the background metered network activity restriction has occurred.
4642 * <p>
4643 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4644 * applies to them.
4645 * <p>
4646 * This is only sent to registered receivers, not manifest receivers.
4647 */
4648 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4649 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4650 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4651
4652 /** @hide */
4653 @Retention(RetentionPolicy.SOURCE)
4654 @IntDef(flag = false, value = {
4655 RESTRICT_BACKGROUND_STATUS_DISABLED,
4656 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4657 RESTRICT_BACKGROUND_STATUS_ENABLED,
4658 })
4659 public @interface RestrictBackgroundStatus {
4660 }
4661
4662 private INetworkPolicyManager getNetworkPolicyManager() {
4663 synchronized (this) {
4664 if (mNPManager != null) {
4665 return mNPManager;
4666 }
4667 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4668 .getService(Context.NETWORK_POLICY_SERVICE));
4669 return mNPManager;
4670 }
4671 }
4672
4673 /**
4674 * Determines if the calling application is subject to metered network restrictions while
4675 * running on background.
4676 *
4677 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4678 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4679 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
4680 */
4681 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4682 try {
4683 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4684 } catch (RemoteException e) {
4685 throw e.rethrowFromSystemServer();
4686 }
4687 }
4688
4689 /**
4690 * The network watchlist is a list of domains and IP addresses that are associated with
4691 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4692 * currently used by the system for validation purposes.
4693 *
4694 * @return Hash of network watchlist config file. Null if config does not exist.
4695 */
4696 @Nullable
4697 public byte[] getNetworkWatchlistConfigHash() {
4698 try {
4699 return mService.getNetworkWatchlistConfigHash();
4700 } catch (RemoteException e) {
4701 Log.e(TAG, "Unable to get watchlist config hash");
4702 throw e.rethrowFromSystemServer();
4703 }
4704 }
4705
4706 /**
4707 * Returns the {@code uid} of the owner of a network connection.
4708 *
4709 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4710 * IPPROTO_UDP} currently supported.
4711 * @param local The local {@link InetSocketAddress} of a connection.
4712 * @param remote The remote {@link InetSocketAddress} of a connection.
4713 * @return {@code uid} if the connection is found and the app has permission to observe it
4714 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4715 * android.os.Process#INVALID_UID} if the connection is not found.
4716 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4717 * user.
4718 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
4719 */
4720 public int getConnectionOwnerUid(
4721 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
4722 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4723 try {
4724 return mService.getConnectionOwnerUid(connectionInfo);
4725 } catch (RemoteException e) {
4726 throw e.rethrowFromSystemServer();
4727 }
4728 }
4729
4730 private void printStackTrace() {
4731 if (DEBUG) {
4732 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4733 final StringBuffer sb = new StringBuffer();
4734 for (int i = 3; i < callStack.length; i++) {
4735 final String stackTrace = callStack[i].toString();
4736 if (stackTrace == null || stackTrace.contains("android.os")) {
4737 break;
4738 }
4739 sb.append(" [").append(stackTrace).append("]");
4740 }
4741 Log.d(TAG, "StackLog:" + sb.toString());
4742 }
4743 }
4744
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09004745 /** @hide */
4746 public TestNetworkManager startOrGetTestNetworkManager() {
4747 final IBinder tnBinder;
4748 try {
4749 tnBinder = mService.startOrGetTestNetworkService();
4750 } catch (RemoteException e) {
4751 throw e.rethrowFromSystemServer();
4752 }
4753
4754 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4755 }
4756
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09004757 /** @hide */
4758 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4759 return new ConnectivityDiagnosticsManager(mContext, mService);
4760 }
4761
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004762 /**
4763 * Simulates a Data Stall for the specified Network.
4764 *
4765 * <p>This method should only be used for tests.
4766 *
4767 * <p>The caller must be the owner of the specified Network.
4768 *
4769 * @param detectionMethod The detection method used to identify the Data Stall.
4770 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4771 * @param network The Network for which a Data Stall is being simluated.
4772 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4773 * @throws SecurityException if the caller is not the owner of the given network.
4774 * @hide
4775 */
4776 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4777 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4778 android.Manifest.permission.NETWORK_STACK})
4779 public void simulateDataStall(int detectionMethod, long timestampMillis,
4780 @NonNull Network network, @NonNull PersistableBundle extras) {
4781 try {
4782 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4783 } catch (RemoteException e) {
4784 e.rethrowFromSystemServer();
4785 }
4786 }
4787
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004788 @NonNull
4789 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4790
4791 /**
4792 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4793 * receive available QoS events related to the {@link Network} and local ip + port
4794 * specified within socketInfo.
4795 * <p/>
4796 * The same {@link QosCallback} must be unregistered before being registered a second time,
4797 * otherwise {@link QosCallbackRegistrationException} is thrown.
4798 * <p/>
4799 * This API does not, in itself, require any permission if called with a network that is not
4800 * restricted. However, the underlying implementation currently only supports the IMS network,
4801 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4802 * useful, because they'd never be called back on networks that they would have access to.
4803 *
4804 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4805 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4806 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4807 * @throws RuntimeException if the app already has too many callbacks registered.
4808 *
4809 * Exceptions after the time of registration is passed through
4810 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4811 *
4812 * @param socketInfo the socket information used to match QoS events
4813 * @param callback receives qos events that satisfy socketInfo
4814 * @param executor The executor on which the callback will be invoked. The provided
4815 * {@link Executor} must run callback sequentially, otherwise the order of
4816 * callbacks cannot be guaranteed.
4817 *
4818 * @hide
4819 */
4820 @SystemApi
4821 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4822 @NonNull final QosCallback callback,
4823 @CallbackExecutor @NonNull final Executor executor) {
4824 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4825 Objects.requireNonNull(callback, "callback must be non-null");
4826 Objects.requireNonNull(executor, "executor must be non-null");
4827
4828 try {
4829 synchronized (mQosCallbackConnections) {
4830 if (getQosCallbackConnection(callback) == null) {
4831 final QosCallbackConnection connection =
4832 new QosCallbackConnection(this, callback, executor);
4833 mQosCallbackConnections.add(connection);
4834 mService.registerQosSocketCallback(socketInfo, connection);
4835 } else {
4836 Log.e(TAG, "registerQosCallback: Callback already registered");
4837 throw new QosCallbackRegistrationException();
4838 }
4839 }
4840 } catch (final RemoteException e) {
4841 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4842
4843 // The same unregister method method is called for consistency even though nothing
4844 // will be sent to the ConnectivityService since the callback was never successfully
4845 // registered.
4846 unregisterQosCallback(callback);
4847 e.rethrowFromSystemServer();
4848 } catch (final ServiceSpecificException e) {
4849 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4850 unregisterQosCallback(callback);
4851 throw convertServiceException(e);
4852 }
4853 }
4854
4855 /**
4856 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4857 * events once unregistered and can be registered a second time.
4858 * <p/>
4859 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4860 *
4861 * @param callback the callback being unregistered
4862 *
4863 * @hide
4864 */
4865 @SystemApi
4866 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4867 Objects.requireNonNull(callback, "The callback must be non-null");
4868 try {
4869 synchronized (mQosCallbackConnections) {
4870 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4871 if (connection != null) {
4872 connection.stopReceivingMessages();
4873 mService.unregisterQosCallback(connection);
4874 mQosCallbackConnections.remove(connection);
4875 } else {
4876 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4877 }
4878 }
4879 } catch (final RemoteException e) {
4880 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4881 e.rethrowFromSystemServer();
4882 }
4883 }
4884
4885 /**
4886 * Gets the connection related to the callback.
4887 *
4888 * @param callback the callback to look up
4889 * @return the related connection
4890 */
4891 @Nullable
4892 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4893 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4894 // Checking by reference here is intentional
4895 if (connection.getCallback() == callback) {
4896 return connection;
4897 }
4898 }
4899 return null;
4900 }
4901
4902 /**
4903 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4904 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4905 * be used to request that the system provide a network without causing the network to be
4906 * in the foreground.
4907 *
4908 * <p>This method will attempt to find the best network that matches the passed
4909 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4910 * criteria. The platform will evaluate which network is the best at its own discretion.
4911 * Throughput, latency, cost per byte, policy, user preference and other considerations
4912 * may be factored in the decision of what is considered the best network.
4913 *
4914 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4915 * matching this request, while always attempting to match the request to a better network if
4916 * possible. If a better match is found, the platform will switch this request to the now-best
4917 * network and inform the app of the newly best network by invoking
4918 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4919 * will not try to maintain any other network than the best one currently matching the request:
4920 * a network not matching any network request may be disconnected at any time.
4921 *
4922 * <p>For example, an application could use this method to obtain a connected cellular network
4923 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4924 * radio to consume additional power. Or, an application could inform the system that it wants
4925 * a network supporting sending MMSes and have the system let it know about the currently best
4926 * MMS-supporting network through the provided {@link NetworkCallback}.
4927 *
4928 * <p>The status of the request can be followed by listening to the various callbacks described
4929 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4930 * used to direct traffic to the network (although accessing some networks may be subject to
4931 * holding specific permissions). Callers will learn about the specific characteristics of the
4932 * network through
4933 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4934 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4935 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4936 * matching the request at any given time; therefore when a better network matching the request
4937 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4938 * with the new network after which no further updates are given about the previously-best
4939 * network, unless it becomes the best again at some later time. All callbacks are invoked
4940 * in order on the same thread, which by default is a thread created by the framework running
4941 * in the app.
4942 *
4943 * <p>This{@link NetworkRequest} will live until released via
4944 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4945 * which point the system may let go of the network at any time.
4946 *
4947 * <p>It is presently unsupported to request a network with mutable
4948 * {@link NetworkCapabilities} such as
4949 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4950 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4951 * as these {@code NetworkCapabilities} represent states that a particular
4952 * network may never attain, and whether a network will attain these states
4953 * is unknown prior to bringing up the network so the framework does not
4954 * know how to go about satisfying a request with these capabilities.
4955 *
4956 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4957 * number of outstanding requests to 100 per app (identified by their UID), shared with
4958 * all variants of this method, of {@link #registerNetworkCallback} as well as
4959 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4960 * Requesting a network with this method will count toward this limit. If this limit is
4961 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4962 * make sure to unregister the callbacks with
4963 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4964 *
4965 * @param request {@link NetworkRequest} describing this request.
4966 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4967 * If null, the callback is invoked on the default internal Handler.
4968 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4969 * the callback must not be shared - it uniquely specifies this request.
4970 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4971 * @throws SecurityException if missing the appropriate permissions.
4972 * @throws RuntimeException if the app already has too many callbacks registered.
4973 *
4974 * @hide
4975 */
4976 @SystemApi(client = MODULE_LIBRARIES)
4977 @SuppressLint("ExecutorRegistration")
4978 @RequiresPermission(anyOf = {
4979 android.Manifest.permission.NETWORK_SETTINGS,
4980 android.Manifest.permission.NETWORK_STACK,
4981 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4982 })
4983 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
4984 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
4985 final NetworkCapabilities nc = request.networkCapabilities;
4986 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
4987 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
4988 }
James Mattis12aeab82021-01-10 14:24:24 -08004989
4990 /**
4991 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
4992 * OnSetOemNetworkPreferenceListener)}.
James Mattis6e2d7022021-01-26 16:23:52 -08004993 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08004994 */
James Mattis6e2d7022021-01-26 16:23:52 -08004995 @SystemApi
4996 public interface OnSetOemNetworkPreferenceListener {
James Mattis12aeab82021-01-10 14:24:24 -08004997 /**
4998 * Called when setOemNetworkPreference() successfully completes.
4999 */
5000 void onComplete();
5001 }
5002
5003 /**
5004 * Used by automotive devices to set the network preferences used to direct traffic at an
5005 * application level as per the given OemNetworkPreferences. An example use-case would be an
5006 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5007 * vehicle via a particular network.
5008 *
5009 * Calling this will overwrite the existing preference.
5010 *
5011 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5012 * @param executor the executor on which listener will be invoked.
5013 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5014 * communicate completion of setOemNetworkPreference(). This will only be
5015 * called once upon successful completion of setOemNetworkPreference().
5016 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5017 * @throws SecurityException if missing the appropriate permissions.
5018 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005019 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005020 */
James Mattis6e2d7022021-01-26 16:23:52 -08005021 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005022 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005023 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005024 @Nullable @CallbackExecutor final Executor executor,
5025 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5026 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5027 if (null != listener) {
5028 Objects.requireNonNull(executor, "Executor must be non-null");
5029 }
5030 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5031 new IOnSetOemNetworkPreferenceListener.Stub() {
5032 @Override
5033 public void onComplete() {
5034 executor.execute(listener::onComplete);
5035 }
5036 };
5037
5038 try {
5039 mService.setOemNetworkPreference(preference, listenerInternal);
5040 } catch (RemoteException e) {
5041 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5042 throw e.rethrowFromSystemServer();
5043 }
5044 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005045}