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