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