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