blob: cb3f41c66a542bb17d30105861dce7812123e5ac [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,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900924 BLOCKED_REASON_LOCKDOWN_VPN,
Sudheer Shankaf1520bb2021-03-23 08:12:28 +0000925 BLOCKED_METERED_REASON_DATA_SAVER,
926 BLOCKED_METERED_REASON_USER_RESTRICTED,
927 BLOCKED_METERED_REASON_ADMIN_DISABLED,
928 })
929 public @interface BlockedReason {}
930
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900931 /**
932 * Set of blocked reasons that are only applicable on metered networks.
933 *
934 * @hide
935 */
936 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
937 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
938
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900939 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
940 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900941
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900942 /**
943 * A kludge to facilitate static access where a Context pointer isn't available, like in the
944 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
945 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
946 * methods that take a Context argument.
947 */
948 private static ConnectivityManager sInstance;
949
950 private final Context mContext;
951
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900952 private final TetheringManager mTetheringManager;
953
954 /**
955 * Tests if a given integer represents a valid network type.
956 * @param networkType the type to be tested
957 * @return a boolean. {@code true} if the type is valid, else {@code false}
958 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
959 * validate a network type.
960 */
961 @Deprecated
962 public static boolean isNetworkTypeValid(int networkType) {
963 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
964 }
965
966 /**
967 * Returns a non-localized string representing a given network type.
968 * ONLY used for debugging output.
969 * @param type the type needing naming
970 * @return a String for the given type, or a string version of the type ("87")
971 * if no name is known.
972 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
973 * {@hide}
974 */
975 @Deprecated
976 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
977 public static String getNetworkTypeName(int type) {
978 switch (type) {
979 case TYPE_NONE:
980 return "NONE";
981 case TYPE_MOBILE:
982 return "MOBILE";
983 case TYPE_WIFI:
984 return "WIFI";
985 case TYPE_MOBILE_MMS:
986 return "MOBILE_MMS";
987 case TYPE_MOBILE_SUPL:
988 return "MOBILE_SUPL";
989 case TYPE_MOBILE_DUN:
990 return "MOBILE_DUN";
991 case TYPE_MOBILE_HIPRI:
992 return "MOBILE_HIPRI";
993 case TYPE_WIMAX:
994 return "WIMAX";
995 case TYPE_BLUETOOTH:
996 return "BLUETOOTH";
997 case TYPE_DUMMY:
998 return "DUMMY";
999 case TYPE_ETHERNET:
1000 return "ETHERNET";
1001 case TYPE_MOBILE_FOTA:
1002 return "MOBILE_FOTA";
1003 case TYPE_MOBILE_IMS:
1004 return "MOBILE_IMS";
1005 case TYPE_MOBILE_CBS:
1006 return "MOBILE_CBS";
1007 case TYPE_WIFI_P2P:
1008 return "WIFI_P2P";
1009 case TYPE_MOBILE_IA:
1010 return "MOBILE_IA";
1011 case TYPE_MOBILE_EMERGENCY:
1012 return "MOBILE_EMERGENCY";
1013 case TYPE_PROXY:
1014 return "PROXY";
1015 case TYPE_VPN:
1016 return "VPN";
1017 default:
1018 return Integer.toString(type);
1019 }
1020 }
1021
1022 /**
1023 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001024 */
lucaslin10774b72021-03-17 14:16:01 +08001025 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001026 public void systemReady() {
1027 try {
1028 mService.systemReady();
1029 } catch (RemoteException e) {
1030 throw e.rethrowFromSystemServer();
1031 }
1032 }
1033
1034 /**
1035 * Checks if a given type uses the cellular data connection.
1036 * This should be replaced in the future by a network property.
1037 * @param networkType the type to check
1038 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1039 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1040 * {@hide}
1041 */
1042 @Deprecated
1043 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1044 public static boolean isNetworkTypeMobile(int networkType) {
1045 switch (networkType) {
1046 case TYPE_MOBILE:
1047 case TYPE_MOBILE_MMS:
1048 case TYPE_MOBILE_SUPL:
1049 case TYPE_MOBILE_DUN:
1050 case TYPE_MOBILE_HIPRI:
1051 case TYPE_MOBILE_FOTA:
1052 case TYPE_MOBILE_IMS:
1053 case TYPE_MOBILE_CBS:
1054 case TYPE_MOBILE_IA:
1055 case TYPE_MOBILE_EMERGENCY:
1056 return true;
1057 default:
1058 return false;
1059 }
1060 }
1061
1062 /**
1063 * Checks if the given network type is backed by a Wi-Fi radio.
1064 *
1065 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1066 * @hide
1067 */
1068 @Deprecated
1069 public static boolean isNetworkTypeWifi(int networkType) {
1070 switch (networkType) {
1071 case TYPE_WIFI:
1072 case TYPE_WIFI_P2P:
1073 return true;
1074 default:
1075 return false;
1076 }
1077 }
1078
1079 /**
Chalard Jeanad565e22021-02-25 17:23:40 +09001080 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1081 * Specify that the traffic for this user should by follow the default rules.
1082 * @hide
1083 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001084 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001085 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1086
1087 /**
1088 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1089 * Specify that the traffic for this user should by default go on a network with
1090 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1091 * if no such network is available.
1092 * @hide
1093 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001094 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001095 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1096
1097 /** @hide */
1098 @Retention(RetentionPolicy.SOURCE)
1099 @IntDef(value = {
1100 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1101 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1102 })
1103 public @interface ProfileNetworkPreference {
1104 }
1105
1106 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001107 * Specifies the preferred network type. When the device has more
1108 * than one type available the preferred network type will be used.
1109 *
1110 * @param preference the network type to prefer over all others. It is
1111 * unspecified what happens to the old preferred network in the
1112 * overall ordering.
1113 * @deprecated Functionality has been removed as it no longer makes sense,
1114 * with many more than two networks - we'd need an array to express
1115 * preference. Instead we use dynamic network properties of
1116 * the networks to describe their precedence.
1117 */
1118 @Deprecated
1119 public void setNetworkPreference(int preference) {
1120 }
1121
1122 /**
1123 * Retrieves the current preferred network type.
1124 *
1125 * @return an integer representing the preferred network type
1126 *
1127 * @deprecated Functionality has been removed as it no longer makes sense,
1128 * with many more than two networks - we'd need an array to express
1129 * preference. Instead we use dynamic network properties of
1130 * the networks to describe their precedence.
1131 */
1132 @Deprecated
1133 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1134 public int getNetworkPreference() {
1135 return TYPE_NONE;
1136 }
1137
1138 /**
1139 * Returns details about the currently active default data network. When
1140 * connected, this network is the default route for outgoing connections.
1141 * You should always check {@link NetworkInfo#isConnected()} before initiating
1142 * network traffic. This may return {@code null} when there is no default
1143 * network.
1144 * Note that if the default network is a VPN, this method will return the
1145 * NetworkInfo for one of its underlying networks instead, or null if the
1146 * VPN agent did not specify any. Apps interested in learning about VPNs
1147 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1148 *
1149 * @return a {@link NetworkInfo} object for the current default network
1150 * or {@code null} if no default network is currently active
1151 * @deprecated See {@link NetworkInfo}.
1152 */
1153 @Deprecated
1154 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1155 @Nullable
1156 public NetworkInfo getActiveNetworkInfo() {
1157 try {
1158 return mService.getActiveNetworkInfo();
1159 } catch (RemoteException e) {
1160 throw e.rethrowFromSystemServer();
1161 }
1162 }
1163
1164 /**
1165 * Returns a {@link Network} object corresponding to the currently active
1166 * default data network. In the event that the current active default data
1167 * network disconnects, the returned {@code Network} object will no longer
1168 * be usable. This will return {@code null} when there is no default
1169 * network.
1170 *
1171 * @return a {@link Network} object for the current default network or
1172 * {@code null} if no default network is currently active
1173 */
1174 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1175 @Nullable
1176 public Network getActiveNetwork() {
1177 try {
1178 return mService.getActiveNetwork();
1179 } catch (RemoteException e) {
1180 throw e.rethrowFromSystemServer();
1181 }
1182 }
1183
1184 /**
1185 * Returns a {@link Network} object corresponding to the currently active
1186 * default data network for a specific UID. In the event that the default data
1187 * network disconnects, the returned {@code Network} object will no longer
1188 * be usable. This will return {@code null} when there is no default
1189 * network for the UID.
1190 *
1191 * @return a {@link Network} object for the current default network for the
1192 * given UID or {@code null} if no default network is currently active
1193 *
1194 * @hide
1195 */
1196 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1197 @Nullable
1198 public Network getActiveNetworkForUid(int uid) {
1199 return getActiveNetworkForUid(uid, false);
1200 }
1201
1202 /** {@hide} */
1203 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1204 try {
1205 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1206 } catch (RemoteException e) {
1207 throw e.rethrowFromSystemServer();
1208 }
1209 }
1210
1211 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001212 * Adds or removes a requirement for given UID ranges to use the VPN.
1213 *
1214 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1215 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1216 * otherwise have permission to bypass the VPN (e.g., because they have the
1217 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1218 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1219 * set to {@code false}, a previously-added restriction is removed.
1220 * <p>
1221 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1222 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1223 * remove a previously-added range, the exact range must be removed as is.
1224 * <p>
1225 * The changes are applied asynchronously and may not have been applied by the time the method
1226 * returns. Apps will be notified about any changes that apply to them via
1227 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1228 * effect.
1229 * <p>
1230 * This method should be called only by the VPN code.
1231 *
1232 * @param ranges the UID ranges to restrict
1233 * @param requireVpn whether the specified UID ranges must use a VPN
1234 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001235 * @hide
1236 */
1237 @RequiresPermission(anyOf = {
1238 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin29278ee2021-03-22 11:51:27 +08001239 android.Manifest.permission.NETWORK_STACK,
1240 android.Manifest.permission.NETWORK_SETTINGS})
1241 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001242 public void setRequireVpnForUids(boolean requireVpn,
1243 @NonNull Collection<Range<Integer>> ranges) {
1244 Objects.requireNonNull(ranges);
1245 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1246 // This method is not necessarily expected to be used outside the system server, so
1247 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1248 // stack process, or by tests.
1249 UidRange[] rangesArray = new UidRange[ranges.size()];
1250 int index = 0;
1251 for (Range<Integer> range : ranges) {
1252 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1253 }
1254 try {
1255 mService.setRequireVpnForUids(requireVpn, rangesArray);
1256 } catch (RemoteException e) {
1257 throw e.rethrowFromSystemServer();
1258 }
1259 }
1260
1261 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001262 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1263 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1264 * but is still supported for backwards compatibility.
1265 * <p>
1266 * This type of VPN is assumed always to use the system default network, and must always declare
1267 * exactly one underlying network, which is the network that was the default when the VPN
1268 * connected.
1269 * <p>
1270 * Calling this method with {@code true} enables legacy behaviour, specifically:
1271 * <ul>
1272 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1273 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1274 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1275 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1276 * underlying the VPN.</li>
1277 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1278 * similarly replaced by the VPN network state.</li>
1279 * <li>Information on current network interfaces passed to NetworkStatsService will not
1280 * include any VPN interfaces.</li>
1281 * </ul>
1282 *
1283 * @param enabled whether legacy lockdown VPN is enabled or disabled
1284 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001285 * @hide
1286 */
1287 @RequiresPermission(anyOf = {
1288 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin29278ee2021-03-22 11:51:27 +08001289 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001290 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin29278ee2021-03-22 11:51:27 +08001291 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001292 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1293 try {
1294 mService.setLegacyLockdownVpnEnabled(enabled);
1295 } catch (RemoteException e) {
1296 throw e.rethrowFromSystemServer();
1297 }
1298 }
1299
1300 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001301 * Returns details about the currently active default data network
1302 * for a given uid. This is for internal use only to avoid spying
1303 * other apps.
1304 *
1305 * @return a {@link NetworkInfo} object for the current default network
1306 * for the given uid or {@code null} if no default network is
1307 * available for the specified uid.
1308 *
1309 * {@hide}
1310 */
1311 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1312 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1313 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1314 return getActiveNetworkInfoForUid(uid, false);
1315 }
1316
1317 /** {@hide} */
1318 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1319 try {
1320 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1321 } catch (RemoteException e) {
1322 throw e.rethrowFromSystemServer();
1323 }
1324 }
1325
1326 /**
1327 * Returns connection status information about a particular
1328 * network type.
1329 *
1330 * @param networkType integer specifying which networkType in
1331 * which you're interested.
1332 * @return a {@link NetworkInfo} object for the requested
1333 * network type or {@code null} if the type is not
1334 * supported by the device. If {@code networkType} is
1335 * TYPE_VPN and a VPN is active for the calling app,
1336 * then this method will try to return one of the
1337 * underlying networks for the VPN or null if the
1338 * VPN agent didn't specify any.
1339 *
1340 * @deprecated This method does not support multiple connected networks
1341 * of the same type. Use {@link #getAllNetworks} and
1342 * {@link #getNetworkInfo(android.net.Network)} instead.
1343 */
1344 @Deprecated
1345 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1346 @Nullable
1347 public NetworkInfo getNetworkInfo(int networkType) {
1348 try {
1349 return mService.getNetworkInfo(networkType);
1350 } catch (RemoteException e) {
1351 throw e.rethrowFromSystemServer();
1352 }
1353 }
1354
1355 /**
1356 * Returns connection status information about a particular
1357 * Network.
1358 *
1359 * @param network {@link Network} specifying which network
1360 * in which you're interested.
1361 * @return a {@link NetworkInfo} object for the requested
1362 * network or {@code null} if the {@code Network}
1363 * is not valid.
1364 * @deprecated See {@link NetworkInfo}.
1365 */
1366 @Deprecated
1367 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1368 @Nullable
1369 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1370 return getNetworkInfoForUid(network, Process.myUid(), false);
1371 }
1372
1373 /** {@hide} */
1374 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1375 try {
1376 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1377 } catch (RemoteException e) {
1378 throw e.rethrowFromSystemServer();
1379 }
1380 }
1381
1382 /**
1383 * Returns connection status information about all network
1384 * types supported by the device.
1385 *
1386 * @return an array of {@link NetworkInfo} objects. Check each
1387 * {@link NetworkInfo#getType} for which type each applies.
1388 *
1389 * @deprecated This method does not support multiple connected networks
1390 * of the same type. Use {@link #getAllNetworks} and
1391 * {@link #getNetworkInfo(android.net.Network)} instead.
1392 */
1393 @Deprecated
1394 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1395 @NonNull
1396 public NetworkInfo[] getAllNetworkInfo() {
1397 try {
1398 return mService.getAllNetworkInfo();
1399 } catch (RemoteException e) {
1400 throw e.rethrowFromSystemServer();
1401 }
1402 }
1403
1404 /**
junyulaib1211372021-03-03 12:09:05 +08001405 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1406 * connected.
1407 * @hide
1408 */
1409 @SystemApi(client = MODULE_LIBRARIES)
1410 @RequiresPermission(anyOf = {
1411 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1412 android.Manifest.permission.NETWORK_STACK,
1413 android.Manifest.permission.NETWORK_SETTINGS})
1414 @NonNull
1415 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1416 try {
1417 return mService.getAllNetworkStateSnapshot();
1418 } catch (RemoteException e) {
1419 throw e.rethrowFromSystemServer();
1420 }
1421 }
1422
1423 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001424 * Returns the {@link Network} object currently serving a given type, or
1425 * null if the given type is not connected.
1426 *
1427 * @hide
1428 * @deprecated This method does not support multiple connected networks
1429 * of the same type. Use {@link #getAllNetworks} and
1430 * {@link #getNetworkInfo(android.net.Network)} instead.
1431 */
1432 @Deprecated
1433 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1434 @UnsupportedAppUsage
1435 public Network getNetworkForType(int networkType) {
1436 try {
1437 return mService.getNetworkForType(networkType);
1438 } catch (RemoteException e) {
1439 throw e.rethrowFromSystemServer();
1440 }
1441 }
1442
1443 /**
1444 * Returns an array of all {@link Network} currently tracked by the
1445 * framework.
1446 *
1447 * @return an array of {@link Network} objects.
1448 */
1449 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1450 @NonNull
1451 public Network[] getAllNetworks() {
1452 try {
1453 return mService.getAllNetworks();
1454 } catch (RemoteException e) {
1455 throw e.rethrowFromSystemServer();
1456 }
1457 }
1458
1459 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001460 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001461 * the Networks that applications run by the given user will use by default.
1462 * @hide
1463 */
1464 @UnsupportedAppUsage
1465 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1466 try {
1467 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001468 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001469 } catch (RemoteException e) {
1470 throw e.rethrowFromSystemServer();
1471 }
1472 }
1473
1474 /**
1475 * Returns the IP information for the current default network.
1476 *
1477 * @return a {@link LinkProperties} object describing the IP info
1478 * for the current default network, or {@code null} if there
1479 * is no current default network.
1480 *
1481 * {@hide}
1482 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1483 * value of {@link #getActiveNetwork()} instead. In particular,
1484 * this method will return non-null LinkProperties even if the
1485 * app is blocked by policy from using this network.
1486 */
1487 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1488 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1489 public LinkProperties getActiveLinkProperties() {
1490 try {
1491 return mService.getActiveLinkProperties();
1492 } catch (RemoteException e) {
1493 throw e.rethrowFromSystemServer();
1494 }
1495 }
1496
1497 /**
1498 * Returns the IP information for a given network type.
1499 *
1500 * @param networkType the network type of interest.
1501 * @return a {@link LinkProperties} object describing the IP info
1502 * for the given networkType, or {@code null} if there is
1503 * no current default network.
1504 *
1505 * {@hide}
1506 * @deprecated This method does not support multiple connected networks
1507 * of the same type. Use {@link #getAllNetworks},
1508 * {@link #getNetworkInfo(android.net.Network)}, and
1509 * {@link #getLinkProperties(android.net.Network)} instead.
1510 */
1511 @Deprecated
1512 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1513 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1514 public LinkProperties getLinkProperties(int networkType) {
1515 try {
1516 return mService.getLinkPropertiesForType(networkType);
1517 } catch (RemoteException e) {
1518 throw e.rethrowFromSystemServer();
1519 }
1520 }
1521
1522 /**
1523 * Get the {@link LinkProperties} for the given {@link Network}. This
1524 * will return {@code null} if the network is unknown.
1525 *
1526 * @param network The {@link Network} object identifying the network in question.
1527 * @return The {@link LinkProperties} for the network, or {@code null}.
1528 */
1529 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1530 @Nullable
1531 public LinkProperties getLinkProperties(@Nullable Network network) {
1532 try {
1533 return mService.getLinkProperties(network);
1534 } catch (RemoteException e) {
1535 throw e.rethrowFromSystemServer();
1536 }
1537 }
1538
1539 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001540 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001541 * will return {@code null} if the network is unknown.
1542 *
Roshan Piuse08bc182020-12-22 15:10:42 -08001543 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1544 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1545 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1546 * this location sensitive information (subject to app's location permissions) will be
1547 * noted by system. To include any location sensitive data in {@link TransportInfo},
1548 * use a {@link NetworkCallback} with
1549 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1550 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001551 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001552 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001553 */
1554 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1555 @Nullable
1556 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1557 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001558 return mService.getNetworkCapabilities(
1559 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001560 } catch (RemoteException e) {
1561 throw e.rethrowFromSystemServer();
1562 }
1563 }
1564
1565 /**
1566 * Gets a URL that can be used for resolving whether a captive portal is present.
1567 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1568 * portal is present.
1569 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1570 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1571 *
1572 * The system network validation may be using different strategies to detect captive portals,
1573 * so this method does not necessarily return a URL used by the system. It only returns a URL
1574 * that may be relevant for other components trying to detect captive portals.
1575 *
1576 * @hide
1577 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1578 * system.
1579 */
1580 @Deprecated
1581 @SystemApi
1582 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1583 public String getCaptivePortalServerUrl() {
1584 try {
1585 return mService.getCaptivePortalServerUrl();
1586 } catch (RemoteException e) {
1587 throw e.rethrowFromSystemServer();
1588 }
1589 }
1590
1591 /**
1592 * Tells the underlying networking system that the caller wants to
1593 * begin using the named feature. The interpretation of {@code feature}
1594 * is completely up to each networking implementation.
1595 *
1596 * <p>This method requires the caller to hold either the
1597 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1598 * or the ability to modify system settings as determined by
1599 * {@link android.provider.Settings.System#canWrite}.</p>
1600 *
1601 * @param networkType specifies which network the request pertains to
1602 * @param feature the name of the feature to be used
1603 * @return an integer value representing the outcome of the request.
1604 * The interpretation of this value is specific to each networking
1605 * implementation+feature combination, except that the value {@code -1}
1606 * always indicates failure.
1607 *
1608 * @deprecated Deprecated in favor of the cleaner
1609 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1610 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1611 * throw {@code UnsupportedOperationException} if called.
1612 * @removed
1613 */
1614 @Deprecated
1615 public int startUsingNetworkFeature(int networkType, String feature) {
1616 checkLegacyRoutingApiAccess();
1617 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1618 if (netCap == null) {
1619 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1620 feature);
1621 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1622 }
1623
1624 NetworkRequest request = null;
1625 synchronized (sLegacyRequests) {
1626 LegacyRequest l = sLegacyRequests.get(netCap);
1627 if (l != null) {
1628 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1629 renewRequestLocked(l);
1630 if (l.currentNetwork != null) {
1631 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1632 } else {
1633 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1634 }
1635 }
1636
1637 request = requestNetworkForFeatureLocked(netCap);
1638 }
1639 if (request != null) {
1640 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1641 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1642 } else {
1643 Log.d(TAG, " request Failed");
1644 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1645 }
1646 }
1647
1648 /**
1649 * Tells the underlying networking system that the caller is finished
1650 * using the named feature. The interpretation of {@code feature}
1651 * is completely up to each networking implementation.
1652 *
1653 * <p>This method requires the caller to hold either the
1654 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1655 * or the ability to modify system settings as determined by
1656 * {@link android.provider.Settings.System#canWrite}.</p>
1657 *
1658 * @param networkType specifies which network the request pertains to
1659 * @param feature the name of the feature that is no longer needed
1660 * @return an integer value representing the outcome of the request.
1661 * The interpretation of this value is specific to each networking
1662 * implementation+feature combination, except that the value {@code -1}
1663 * always indicates failure.
1664 *
1665 * @deprecated Deprecated in favor of the cleaner
1666 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1667 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1668 * throw {@code UnsupportedOperationException} if called.
1669 * @removed
1670 */
1671 @Deprecated
1672 public int stopUsingNetworkFeature(int networkType, String feature) {
1673 checkLegacyRoutingApiAccess();
1674 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1675 if (netCap == null) {
1676 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1677 feature);
1678 return -1;
1679 }
1680
1681 if (removeRequestForFeature(netCap)) {
1682 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1683 }
1684 return 1;
1685 }
1686
1687 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1688 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1689 if (networkType == TYPE_MOBILE) {
1690 switch (feature) {
1691 case "enableCBS":
1692 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1693 case "enableDUN":
1694 case "enableDUNAlways":
1695 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1696 case "enableFOTA":
1697 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1698 case "enableHIPRI":
1699 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1700 case "enableIMS":
1701 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1702 case "enableMMS":
1703 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1704 case "enableSUPL":
1705 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1706 default:
1707 return null;
1708 }
1709 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1710 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1711 }
1712 return null;
1713 }
1714
1715 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1716 if (netCap == null) return TYPE_NONE;
1717 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1718 return TYPE_MOBILE_CBS;
1719 }
1720 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1721 return TYPE_MOBILE_IMS;
1722 }
1723 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1724 return TYPE_MOBILE_FOTA;
1725 }
1726 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1727 return TYPE_MOBILE_DUN;
1728 }
1729 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1730 return TYPE_MOBILE_SUPL;
1731 }
1732 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1733 return TYPE_MOBILE_MMS;
1734 }
1735 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1736 return TYPE_MOBILE_HIPRI;
1737 }
1738 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1739 return TYPE_WIFI_P2P;
1740 }
1741 return TYPE_NONE;
1742 }
1743
1744 private static class LegacyRequest {
1745 NetworkCapabilities networkCapabilities;
1746 NetworkRequest networkRequest;
1747 int expireSequenceNumber;
1748 Network currentNetwork;
1749 int delay = -1;
1750
1751 private void clearDnsBinding() {
1752 if (currentNetwork != null) {
1753 currentNetwork = null;
1754 setProcessDefaultNetworkForHostResolution(null);
1755 }
1756 }
1757
1758 NetworkCallback networkCallback = new NetworkCallback() {
1759 @Override
1760 public void onAvailable(Network network) {
1761 currentNetwork = network;
1762 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1763 setProcessDefaultNetworkForHostResolution(network);
1764 }
1765 @Override
1766 public void onLost(Network network) {
1767 if (network.equals(currentNetwork)) clearDnsBinding();
1768 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1769 }
1770 };
1771 }
1772
1773 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1774 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1775 new HashMap<>();
1776
1777 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1778 synchronized (sLegacyRequests) {
1779 LegacyRequest l = sLegacyRequests.get(netCap);
1780 if (l != null) return l.networkRequest;
1781 }
1782 return null;
1783 }
1784
1785 private void renewRequestLocked(LegacyRequest l) {
1786 l.expireSequenceNumber++;
1787 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1788 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1789 }
1790
1791 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1792 int ourSeqNum = -1;
1793 synchronized (sLegacyRequests) {
1794 LegacyRequest l = sLegacyRequests.get(netCap);
1795 if (l == null) return;
1796 ourSeqNum = l.expireSequenceNumber;
1797 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
1798 }
1799 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1800 }
1801
1802 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1803 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1804 int delay = -1;
1805 int type = legacyTypeForNetworkCapabilities(netCap);
1806 try {
1807 delay = mService.getRestoreDefaultNetworkDelay(type);
1808 } catch (RemoteException e) {
1809 throw e.rethrowFromSystemServer();
1810 }
1811 LegacyRequest l = new LegacyRequest();
1812 l.networkCapabilities = netCap;
1813 l.delay = delay;
1814 l.expireSequenceNumber = 0;
1815 l.networkRequest = sendRequestForNetwork(
1816 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
1817 if (l.networkRequest == null) return null;
1818 sLegacyRequests.put(netCap, l);
1819 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1820 return l.networkRequest;
1821 }
1822
1823 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1824 if (delay >= 0) {
1825 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
1826 CallbackHandler handler = getDefaultHandler();
1827 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1828 handler.sendMessageDelayed(msg, delay);
1829 }
1830 }
1831
1832 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1833 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1834 final LegacyRequest l;
1835 synchronized (sLegacyRequests) {
1836 l = sLegacyRequests.remove(netCap);
1837 }
1838 if (l == null) return false;
1839 unregisterNetworkCallback(l.networkCallback);
1840 l.clearDnsBinding();
1841 return true;
1842 }
1843
1844 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1845 static {
1846 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1847 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1848 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1849 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1850 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1851 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1852 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1853 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1854 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1855 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1856 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1857 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1858 }
1859
1860 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1861 static {
1862 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1863 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1864 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1865 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1866 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1867 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1868 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1869 }
1870
1871 /**
1872 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1873 * instance suitable for registering a request or callback. Throws an
1874 * IllegalArgumentException if no mapping from the legacy type to
1875 * NetworkCapabilities is known.
1876 *
1877 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1878 * to find the network instead.
1879 * @hide
1880 */
1881 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1882 final NetworkCapabilities nc = new NetworkCapabilities();
1883
1884 // Map from type to transports.
1885 final int NOT_FOUND = -1;
1886 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00001887 if (transport == NOT_FOUND) {
1888 throw new IllegalArgumentException("unknown legacy type: " + type);
1889 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001890 nc.addTransportType(transport);
1891
1892 // Map from type to capabilities.
1893 nc.addCapability(sLegacyTypeToCapability.get(
1894 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1895 nc.maybeMarkCapabilitiesRestricted();
1896 return nc;
1897 }
1898
1899 /** @hide */
1900 public static class PacketKeepaliveCallback {
1901 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1902 public PacketKeepaliveCallback() {
1903 }
1904 /** The requested keepalive was successfully started. */
1905 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1906 public void onStarted() {}
1907 /** The keepalive was successfully stopped. */
1908 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1909 public void onStopped() {}
1910 /** An error occurred. */
1911 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1912 public void onError(int error) {}
1913 }
1914
1915 /**
1916 * Allows applications to request that the system periodically send specific packets on their
1917 * behalf, using hardware offload to save battery power.
1918 *
1919 * To request that the system send keepalives, call one of the methods that return a
1920 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1921 * passing in a non-null callback. If the callback is successfully started, the callback's
1922 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1923 * specifying one of the {@code ERROR_*} constants in this class.
1924 *
1925 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1926 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1927 * {@link PacketKeepaliveCallback#onError} if an error occurred.
1928 *
1929 * @deprecated Use {@link SocketKeepalive} instead.
1930 *
1931 * @hide
1932 */
1933 public class PacketKeepalive {
1934
1935 private static final String TAG = "PacketKeepalive";
1936
1937 /** @hide */
1938 public static final int SUCCESS = 0;
1939
1940 /** @hide */
1941 public static final int NO_KEEPALIVE = -1;
1942
1943 /** @hide */
1944 public static final int BINDER_DIED = -10;
1945
1946 /** The specified {@code Network} is not connected. */
1947 public static final int ERROR_INVALID_NETWORK = -20;
1948 /** The specified IP addresses are invalid. For example, the specified source IP address is
1949 * not configured on the specified {@code Network}. */
1950 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1951 /** The requested port is invalid. */
1952 public static final int ERROR_INVALID_PORT = -22;
1953 /** The packet length is invalid (e.g., too long). */
1954 public static final int ERROR_INVALID_LENGTH = -23;
1955 /** The packet transmission interval is invalid (e.g., too short). */
1956 public static final int ERROR_INVALID_INTERVAL = -24;
1957
1958 /** The hardware does not support this request. */
1959 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
1960 /** The hardware returned an error. */
1961 public static final int ERROR_HARDWARE_ERROR = -31;
1962
1963 /** The NAT-T destination port for IPsec */
1964 public static final int NATT_PORT = 4500;
1965
1966 /** The minimum interval in seconds between keepalive packet transmissions */
1967 public static final int MIN_INTERVAL = 10;
1968
1969 private final Network mNetwork;
1970 private final ISocketKeepaliveCallback mCallback;
1971 private final ExecutorService mExecutor;
1972
1973 private volatile Integer mSlot;
1974
1975 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1976 public void stop() {
1977 try {
1978 mExecutor.execute(() -> {
1979 try {
1980 if (mSlot != null) {
1981 mService.stopKeepalive(mNetwork, mSlot);
1982 }
1983 } catch (RemoteException e) {
1984 Log.e(TAG, "Error stopping packet keepalive: ", e);
1985 throw e.rethrowFromSystemServer();
1986 }
1987 });
1988 } catch (RejectedExecutionException e) {
1989 // The internal executor has already stopped due to previous event.
1990 }
1991 }
1992
1993 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00001994 Objects.requireNonNull(network, "network cannot be null");
1995 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001996 mNetwork = network;
1997 mExecutor = Executors.newSingleThreadExecutor();
1998 mCallback = new ISocketKeepaliveCallback.Stub() {
1999 @Override
2000 public void onStarted(int slot) {
2001 final long token = Binder.clearCallingIdentity();
2002 try {
2003 mExecutor.execute(() -> {
2004 mSlot = slot;
2005 callback.onStarted();
2006 });
2007 } finally {
2008 Binder.restoreCallingIdentity(token);
2009 }
2010 }
2011
2012 @Override
2013 public void onStopped() {
2014 final long token = Binder.clearCallingIdentity();
2015 try {
2016 mExecutor.execute(() -> {
2017 mSlot = null;
2018 callback.onStopped();
2019 });
2020 } finally {
2021 Binder.restoreCallingIdentity(token);
2022 }
2023 mExecutor.shutdown();
2024 }
2025
2026 @Override
2027 public void onError(int error) {
2028 final long token = Binder.clearCallingIdentity();
2029 try {
2030 mExecutor.execute(() -> {
2031 mSlot = null;
2032 callback.onError(error);
2033 });
2034 } finally {
2035 Binder.restoreCallingIdentity(token);
2036 }
2037 mExecutor.shutdown();
2038 }
2039
2040 @Override
2041 public void onDataReceived() {
2042 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2043 // this callback when data is received.
2044 }
2045 };
2046 }
2047 }
2048
2049 /**
2050 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2051 *
2052 * @deprecated Use {@link #createSocketKeepalive} instead.
2053 *
2054 * @hide
2055 */
2056 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2057 public PacketKeepalive startNattKeepalive(
2058 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2059 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2060 final PacketKeepalive k = new PacketKeepalive(network, callback);
2061 try {
2062 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2063 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2064 } catch (RemoteException e) {
2065 Log.e(TAG, "Error starting packet keepalive: ", e);
2066 throw e.rethrowFromSystemServer();
2067 }
2068 return k;
2069 }
2070
2071 // Construct an invalid fd.
2072 private ParcelFileDescriptor createInvalidFd() {
2073 final int invalidFd = -1;
2074 return ParcelFileDescriptor.adoptFd(invalidFd);
2075 }
2076
2077 /**
2078 * Request that keepalives be started on a IPsec NAT-T socket.
2079 *
2080 * @param network The {@link Network} the socket is on.
2081 * @param socket The socket that needs to be kept alive.
2082 * @param source The source address of the {@link UdpEncapsulationSocket}.
2083 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2084 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2085 * must run callback sequentially, otherwise the order of callbacks cannot be
2086 * guaranteed.
2087 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2088 * changes. Must be extended by applications that use this API.
2089 *
2090 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2091 * given socket.
2092 **/
2093 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2094 @NonNull UdpEncapsulationSocket socket,
2095 @NonNull InetAddress source,
2096 @NonNull InetAddress destination,
2097 @NonNull @CallbackExecutor Executor executor,
2098 @NonNull Callback callback) {
2099 ParcelFileDescriptor dup;
2100 try {
2101 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2102 // which cannot be obtained by the app process.
2103 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2104 } catch (IOException ignored) {
2105 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2106 // ERROR_INVALID_SOCKET.
2107 dup = createInvalidFd();
2108 }
2109 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2110 destination, executor, callback);
2111 }
2112
2113 /**
2114 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2115 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2116 *
2117 * @param network The {@link Network} the socket is on.
2118 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2119 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2120 * from that port.
2121 * @param source The source address of the {@link UdpEncapsulationSocket}.
2122 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2123 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2124 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2125 * must run callback sequentially, otherwise the order of callbacks cannot be
2126 * guaranteed.
2127 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2128 * changes. Must be extended by applications that use this API.
2129 *
2130 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2131 * given socket.
2132 * @hide
2133 */
2134 @SystemApi
2135 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2136 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2137 @NonNull ParcelFileDescriptor pfd,
2138 @NonNull InetAddress source,
2139 @NonNull InetAddress destination,
2140 @NonNull @CallbackExecutor Executor executor,
2141 @NonNull Callback callback) {
2142 ParcelFileDescriptor dup;
2143 try {
2144 // TODO: Consider remove unnecessary dup.
2145 dup = pfd.dup();
2146 } catch (IOException ignored) {
2147 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2148 // ERROR_INVALID_SOCKET.
2149 dup = createInvalidFd();
2150 }
2151 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002152 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002153 }
2154
2155 /**
2156 * Request that keepalives be started on a TCP socket.
2157 * The socket must be established.
2158 *
2159 * @param network The {@link Network} the socket is on.
2160 * @param socket The socket that needs to be kept alive.
2161 * @param executor The executor on which callback will be invoked. This implementation assumes
2162 * the provided {@link Executor} runs the callbacks in sequence with no
2163 * concurrency. Failing this, no guarantee of correctness can be made. It is
2164 * the responsibility of the caller to ensure the executor provides this
2165 * guarantee. A simple way of creating such an executor is with the standard
2166 * tool {@code Executors.newSingleThreadExecutor}.
2167 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2168 * changes. Must be extended by applications that use this API.
2169 *
2170 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2171 * given socket.
2172 * @hide
2173 */
2174 @SystemApi
2175 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2176 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2177 @NonNull Socket socket,
2178 @NonNull Executor executor,
2179 @NonNull Callback callback) {
2180 ParcelFileDescriptor dup;
2181 try {
2182 dup = ParcelFileDescriptor.fromSocket(socket);
2183 } catch (UncheckedIOException ignored) {
2184 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2185 // ERROR_INVALID_SOCKET.
2186 dup = createInvalidFd();
2187 }
2188 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2189 }
2190
2191 /**
2192 * Ensure that a network route exists to deliver traffic to the specified
2193 * host via the specified network interface. An attempt to add a route that
2194 * already exists is ignored, but treated as successful.
2195 *
2196 * <p>This method requires the caller to hold either the
2197 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2198 * or the ability to modify system settings as determined by
2199 * {@link android.provider.Settings.System#canWrite}.</p>
2200 *
2201 * @param networkType the type of the network over which traffic to the specified
2202 * host is to be routed
2203 * @param hostAddress the IP address of the host to which the route is desired
2204 * @return {@code true} on success, {@code false} on failure
2205 *
2206 * @deprecated Deprecated in favor of the
2207 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2208 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2209 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2210 * throw {@code UnsupportedOperationException} if called.
2211 * @removed
2212 */
2213 @Deprecated
2214 public boolean requestRouteToHost(int networkType, int hostAddress) {
2215 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2216 }
2217
2218 /**
2219 * Ensure that a network route exists to deliver traffic to the specified
2220 * host via the specified network interface. An attempt to add a route that
2221 * already exists is ignored, but treated as successful.
2222 *
2223 * <p>This method requires the caller to hold either the
2224 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2225 * or the ability to modify system settings as determined by
2226 * {@link android.provider.Settings.System#canWrite}.</p>
2227 *
2228 * @param networkType the type of the network over which traffic to the specified
2229 * host is to be routed
2230 * @param hostAddress the IP address of the host to which the route is desired
2231 * @return {@code true} on success, {@code false} on failure
2232 * @hide
2233 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2234 * {@link #bindProcessToNetwork} API.
2235 */
2236 @Deprecated
2237 @UnsupportedAppUsage
lucaslin29278ee2021-03-22 11:51:27 +08002238 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002239 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2240 checkLegacyRoutingApiAccess();
2241 try {
2242 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2243 mContext.getOpPackageName(), getAttributionTag());
2244 } catch (RemoteException e) {
2245 throw e.rethrowFromSystemServer();
2246 }
2247 }
2248
2249 /**
2250 * @return the context's attribution tag
2251 */
2252 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2253 private @Nullable String getAttributionTag() {
Roshan Piusa8a477b2020-12-17 14:53:09 -08002254 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002255 }
2256
2257 /**
2258 * Returns the value of the setting for background data usage. If false,
2259 * applications should not use the network if the application is not in the
2260 * foreground. Developers should respect this setting, and check the value
2261 * of this before performing any background data operations.
2262 * <p>
2263 * All applications that have background services that use the network
2264 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2265 * <p>
2266 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2267 * background data depends on several combined factors, and this method will
2268 * always return {@code true}. Instead, when background data is unavailable,
2269 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2270 *
2271 * @return Whether background data usage is allowed.
2272 */
2273 @Deprecated
2274 public boolean getBackgroundDataSetting() {
2275 // assume that background data is allowed; final authority is
2276 // NetworkInfo which may be blocked.
2277 return true;
2278 }
2279
2280 /**
2281 * Sets the value of the setting for background data usage.
2282 *
2283 * @param allowBackgroundData Whether an application should use data while
2284 * it is in the background.
2285 *
2286 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2287 * @see #getBackgroundDataSetting()
2288 * @hide
2289 */
2290 @Deprecated
2291 @UnsupportedAppUsage
2292 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2293 // ignored
2294 }
2295
2296 /**
2297 * @hide
2298 * @deprecated Talk to TelephonyManager directly
2299 */
2300 @Deprecated
2301 @UnsupportedAppUsage
2302 public boolean getMobileDataEnabled() {
2303 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2304 if (tm != null) {
2305 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2306 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2307 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2308 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2309 + " retVal=" + retVal);
2310 return retVal;
2311 }
2312 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2313 return false;
2314 }
2315
2316 /**
2317 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2318 * to find out when the system default network has gone in to a high power state.
2319 */
2320 public interface OnNetworkActiveListener {
2321 /**
2322 * Called on the main thread of the process to report that the current data network
2323 * has become active, and it is now a good time to perform any pending network
2324 * operations. Note that this listener only tells you when the network becomes
2325 * active; if at any other time you want to know whether it is active (and thus okay
2326 * to initiate network traffic), you can retrieve its instantaneous state with
2327 * {@link ConnectivityManager#isDefaultNetworkActive}.
2328 */
2329 void onNetworkActive();
2330 }
2331
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002332 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2333 mNetworkActivityListeners = new ArrayMap<>();
2334
2335 /**
2336 * Start listening to reports when the system's default data network is active, meaning it is
2337 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2338 * to determine the current state of the system's default network after registering the
2339 * listener.
2340 * <p>
2341 * If the process default network has been set with
2342 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2343 * reflect the process's default, but the system default.
2344 *
2345 * @param l The listener to be told when the network is active.
2346 */
2347 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
2348 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2349 @Override
2350 public void onNetworkActive() throws RemoteException {
2351 l.onNetworkActive();
2352 }
2353 };
2354
2355 try {
lucaslin709eb842021-01-21 02:04:15 +08002356 mService.registerNetworkActivityListener(rl);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002357 mNetworkActivityListeners.put(l, rl);
2358 } catch (RemoteException e) {
2359 throw e.rethrowFromSystemServer();
2360 }
2361 }
2362
2363 /**
2364 * Remove network active listener previously registered with
2365 * {@link #addDefaultNetworkActiveListener}.
2366 *
2367 * @param l Previously registered listener.
2368 */
2369 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
2370 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002371 if (rl == null) {
2372 throw new IllegalArgumentException("Listener was not registered.");
2373 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002374 try {
lucaslin709eb842021-01-21 02:04:15 +08002375 mService.registerNetworkActivityListener(rl);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002376 } catch (RemoteException e) {
2377 throw e.rethrowFromSystemServer();
2378 }
2379 }
2380
2381 /**
2382 * Return whether the data network is currently active. An active network means that
2383 * it is currently in a high power state for performing data transmission. On some
2384 * types of networks, it may be expensive to move and stay in such a state, so it is
2385 * more power efficient to batch network traffic together when the radio is already in
2386 * this state. This method tells you whether right now is currently a good time to
2387 * initiate network traffic, as the network is already active.
2388 */
2389 public boolean isDefaultNetworkActive() {
2390 try {
lucaslin709eb842021-01-21 02:04:15 +08002391 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002392 } catch (RemoteException e) {
2393 throw e.rethrowFromSystemServer();
2394 }
2395 }
2396
2397 /**
2398 * {@hide}
2399 */
2400 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002401 mContext = Objects.requireNonNull(context, "missing context");
2402 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002403 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
2404 sInstance = this;
2405 }
2406
2407 /** {@hide} */
2408 @UnsupportedAppUsage
2409 public static ConnectivityManager from(Context context) {
2410 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2411 }
2412
2413 /** @hide */
2414 public NetworkRequest getDefaultRequest() {
2415 try {
2416 // This is not racy as the default request is final in ConnectivityService.
2417 return mService.getDefaultRequest();
2418 } catch (RemoteException e) {
2419 throw e.rethrowFromSystemServer();
2420 }
2421 }
2422
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002423 /**
2424 * Check if the package is a allowed to write settings. This also accounts that such an access
2425 * happened.
2426 *
2427 * @return {@code true} iff the package is allowed to write settings.
2428 */
2429 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2430 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2431 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2432 boolean throwException) {
2433 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2434 throwException);
2435 }
2436
2437 /**
2438 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2439 * situations where a Context pointer is unavailable.
2440 * @hide
2441 */
2442 @Deprecated
2443 static ConnectivityManager getInstanceOrNull() {
2444 return sInstance;
2445 }
2446
2447 /**
2448 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2449 * situations where a Context pointer is unavailable.
2450 * @hide
2451 */
2452 @Deprecated
2453 @UnsupportedAppUsage
2454 private static ConnectivityManager getInstance() {
2455 if (getInstanceOrNull() == null) {
2456 throw new IllegalStateException("No ConnectivityManager yet constructed");
2457 }
2458 return getInstanceOrNull();
2459 }
2460
2461 /**
2462 * Get the set of tetherable, available interfaces. This list is limited by
2463 * device configuration and current interface existence.
2464 *
2465 * @return an array of 0 or more Strings of tetherable interface names.
2466 *
2467 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2468 * {@hide}
2469 */
2470 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2471 @UnsupportedAppUsage
2472 @Deprecated
2473 public String[] getTetherableIfaces() {
2474 return mTetheringManager.getTetherableIfaces();
2475 }
2476
2477 /**
2478 * Get the set of tethered interfaces.
2479 *
2480 * @return an array of 0 or more String of currently tethered interface names.
2481 *
2482 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2483 * {@hide}
2484 */
2485 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2486 @UnsupportedAppUsage
2487 @Deprecated
2488 public String[] getTetheredIfaces() {
2489 return mTetheringManager.getTetheredIfaces();
2490 }
2491
2492 /**
2493 * Get the set of interface names which attempted to tether but
2494 * failed. Re-attempting to tether may cause them to reset to the Tethered
2495 * state. Alternatively, causing the interface to be destroyed and recreated
2496 * may cause them to reset to the available state.
2497 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2498 * information on the cause of the errors.
2499 *
2500 * @return an array of 0 or more String indicating the interface names
2501 * which failed to tether.
2502 *
2503 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2504 * {@hide}
2505 */
2506 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2507 @UnsupportedAppUsage
2508 @Deprecated
2509 public String[] getTetheringErroredIfaces() {
2510 return mTetheringManager.getTetheringErroredIfaces();
2511 }
2512
2513 /**
2514 * Get the set of tethered dhcp ranges.
2515 *
2516 * @deprecated This method is not supported.
2517 * TODO: remove this function when all of clients are removed.
2518 * {@hide}
2519 */
2520 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2521 @Deprecated
2522 public String[] getTetheredDhcpRanges() {
2523 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2524 }
2525
2526 /**
2527 * Attempt to tether the named interface. This will setup a dhcp server
2528 * on the interface, forward and NAT IP packets and forward DNS requests
2529 * to the best active upstream network interface. Note that if no upstream
2530 * IP network interface is available, dhcp will still run and traffic will be
2531 * allowed between the tethered devices and this device, though upstream net
2532 * access will of course fail until an upstream network interface becomes
2533 * active.
2534 *
2535 * <p>This method requires the caller to hold either the
2536 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2537 * or the ability to modify system settings as determined by
2538 * {@link android.provider.Settings.System#canWrite}.</p>
2539 *
2540 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2541 * and WifiStateMachine which need direct access. All other clients should use
2542 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2543 * logic.</p>
2544 *
2545 * @param iface the interface name to tether.
2546 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2547 * @deprecated Use {@link TetheringManager#startTethering} instead
2548 *
2549 * {@hide}
2550 */
2551 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2552 @Deprecated
2553 public int tether(String iface) {
2554 return mTetheringManager.tether(iface);
2555 }
2556
2557 /**
2558 * Stop tethering the named interface.
2559 *
2560 * <p>This method requires the caller to hold either the
2561 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2562 * or the ability to modify system settings as determined by
2563 * {@link android.provider.Settings.System#canWrite}.</p>
2564 *
2565 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2566 * and WifiStateMachine which need direct access. All other clients should use
2567 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2568 * logic.</p>
2569 *
2570 * @param iface the interface name to untether.
2571 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2572 *
2573 * {@hide}
2574 */
2575 @UnsupportedAppUsage
2576 @Deprecated
2577 public int untether(String iface) {
2578 return mTetheringManager.untether(iface);
2579 }
2580
2581 /**
2582 * Check if the device allows for tethering. It may be disabled via
2583 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2584 * due to device configuration.
2585 *
2586 * <p>If this app does not have permission to use this API, it will always
2587 * return false rather than throw an exception.</p>
2588 *
2589 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2590 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2591 *
2592 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2593 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2594 *
2595 * @return a boolean - {@code true} indicating Tethering is supported.
2596 *
2597 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2598 * {@hide}
2599 */
2600 @SystemApi
2601 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2602 android.Manifest.permission.WRITE_SETTINGS})
2603 public boolean isTetheringSupported() {
2604 return mTetheringManager.isTetheringSupported();
2605 }
2606
2607 /**
2608 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2609 *
2610 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2611 * @hide
2612 */
2613 @SystemApi
2614 @Deprecated
2615 public static abstract class OnStartTetheringCallback {
2616 /**
2617 * Called when tethering has been successfully started.
2618 */
2619 public void onTetheringStarted() {}
2620
2621 /**
2622 * Called when starting tethering failed.
2623 */
2624 public void onTetheringFailed() {}
2625 }
2626
2627 /**
2628 * Convenient overload for
2629 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2630 * handler to run on the current thread's {@link Looper}.
2631 *
2632 * @deprecated Use {@link TetheringManager#startTethering} instead.
2633 * @hide
2634 */
2635 @SystemApi
2636 @Deprecated
2637 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2638 public void startTethering(int type, boolean showProvisioningUi,
2639 final OnStartTetheringCallback callback) {
2640 startTethering(type, showProvisioningUi, callback, null);
2641 }
2642
2643 /**
2644 * Runs tether provisioning for the given type if needed and then starts tethering if
2645 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2646 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2647 * schedules tether provisioning re-checks if appropriate.
2648 *
2649 * @param type The type of tethering to start. Must be one of
2650 * {@link ConnectivityManager.TETHERING_WIFI},
2651 * {@link ConnectivityManager.TETHERING_USB}, or
2652 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2653 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2654 * is one. This should be true the first time this function is called and also any time
2655 * the user can see this UI. It gives users information from their carrier about the
2656 * check failing and how they can sign up for tethering if possible.
2657 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2658 * of the result of trying to tether.
2659 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2660 *
2661 * @deprecated Use {@link TetheringManager#startTethering} instead.
2662 * @hide
2663 */
2664 @SystemApi
2665 @Deprecated
2666 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2667 public void startTethering(int type, boolean showProvisioningUi,
2668 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002669 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002670
2671 final Executor executor = new Executor() {
2672 @Override
2673 public void execute(Runnable command) {
2674 if (handler == null) {
2675 command.run();
2676 } else {
2677 handler.post(command);
2678 }
2679 }
2680 };
2681
2682 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2683 @Override
2684 public void onTetheringStarted() {
2685 callback.onTetheringStarted();
2686 }
2687
2688 @Override
2689 public void onTetheringFailed(final int error) {
2690 callback.onTetheringFailed();
2691 }
2692 };
2693
2694 final TetheringRequest request = new TetheringRequest.Builder(type)
2695 .setShouldShowEntitlementUi(showProvisioningUi).build();
2696
2697 mTetheringManager.startTethering(request, executor, tetheringCallback);
2698 }
2699
2700 /**
2701 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2702 * applicable.
2703 *
2704 * @param type The type of tethering to stop. Must be one of
2705 * {@link ConnectivityManager.TETHERING_WIFI},
2706 * {@link ConnectivityManager.TETHERING_USB}, or
2707 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2708 *
2709 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2710 * @hide
2711 */
2712 @SystemApi
2713 @Deprecated
2714 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2715 public void stopTethering(int type) {
2716 mTetheringManager.stopTethering(type);
2717 }
2718
2719 /**
2720 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2721 * upstream status.
2722 *
2723 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2724 * @hide
2725 */
2726 @SystemApi
2727 @Deprecated
2728 public abstract static class OnTetheringEventCallback {
2729
2730 /**
2731 * Called when tethering upstream changed. This can be called multiple times and can be
2732 * called any time.
2733 *
2734 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2735 * have any upstream.
2736 */
2737 public void onUpstreamChanged(@Nullable Network network) {}
2738 }
2739
2740 @GuardedBy("mTetheringEventCallbacks")
2741 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2742 mTetheringEventCallbacks = new ArrayMap<>();
2743
2744 /**
2745 * Start listening to tethering change events. Any new added callback will receive the last
2746 * tethering status right away. If callback is registered when tethering has no upstream or
2747 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2748 * with a null argument. The same callback object cannot be registered twice.
2749 *
2750 * @param executor the executor on which callback will be invoked.
2751 * @param callback the callback to be called when tethering has change events.
2752 *
2753 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2754 * @hide
2755 */
2756 @SystemApi
2757 @Deprecated
2758 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2759 public void registerTetheringEventCallback(
2760 @NonNull @CallbackExecutor Executor executor,
2761 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002762 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002763
2764 final TetheringEventCallback tetherCallback =
2765 new TetheringEventCallback() {
2766 @Override
2767 public void onUpstreamChanged(@Nullable Network network) {
2768 callback.onUpstreamChanged(network);
2769 }
2770 };
2771
2772 synchronized (mTetheringEventCallbacks) {
2773 mTetheringEventCallbacks.put(callback, tetherCallback);
2774 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
2775 }
2776 }
2777
2778 /**
2779 * Remove tethering event callback previously registered with
2780 * {@link #registerTetheringEventCallback}.
2781 *
2782 * @param callback previously registered callback.
2783 *
2784 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
2785 * @hide
2786 */
2787 @SystemApi
2788 @Deprecated
2789 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2790 public void unregisterTetheringEventCallback(
2791 @NonNull final OnTetheringEventCallback callback) {
2792 Objects.requireNonNull(callback, "The callback must be non-null");
2793 synchronized (mTetheringEventCallbacks) {
2794 final TetheringEventCallback tetherCallback =
2795 mTetheringEventCallbacks.remove(callback);
2796 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
2797 }
2798 }
2799
2800
2801 /**
2802 * Get the list of regular expressions that define any tetherable
2803 * USB network interfaces. If USB tethering is not supported by the
2804 * device, this list should be empty.
2805 *
2806 * @return an array of 0 or more regular expression Strings defining
2807 * what interfaces are considered tetherable usb interfaces.
2808 *
2809 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2810 * {@hide}
2811 */
2812 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2813 @UnsupportedAppUsage
2814 @Deprecated
2815 public String[] getTetherableUsbRegexs() {
2816 return mTetheringManager.getTetherableUsbRegexs();
2817 }
2818
2819 /**
2820 * Get the list of regular expressions that define any tetherable
2821 * Wifi network interfaces. If Wifi tethering is not supported by the
2822 * device, this list should be empty.
2823 *
2824 * @return an array of 0 or more regular expression Strings defining
2825 * what interfaces are considered tetherable wifi interfaces.
2826 *
2827 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2828 * {@hide}
2829 */
2830 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2831 @UnsupportedAppUsage
2832 @Deprecated
2833 public String[] getTetherableWifiRegexs() {
2834 return mTetheringManager.getTetherableWifiRegexs();
2835 }
2836
2837 /**
2838 * Get the list of regular expressions that define any tetherable
2839 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2840 * device, this list should be empty.
2841 *
2842 * @return an array of 0 or more regular expression Strings defining
2843 * what interfaces are considered tetherable bluetooth interfaces.
2844 *
2845 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2846 *TetheringManager.TetheringInterfaceRegexps)} instead.
2847 * {@hide}
2848 */
2849 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2850 @UnsupportedAppUsage
2851 @Deprecated
2852 public String[] getTetherableBluetoothRegexs() {
2853 return mTetheringManager.getTetherableBluetoothRegexs();
2854 }
2855
2856 /**
2857 * Attempt to both alter the mode of USB and Tethering of USB. A
2858 * utility method to deal with some of the complexity of USB - will
2859 * attempt to switch to Rndis and subsequently tether the resulting
2860 * interface on {@code true} or turn off tethering and switch off
2861 * Rndis on {@code false}.
2862 *
2863 * <p>This method requires the caller to hold either the
2864 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2865 * or the ability to modify system settings as determined by
2866 * {@link android.provider.Settings.System#canWrite}.</p>
2867 *
2868 * @param enable a boolean - {@code true} to enable tethering
2869 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2870 * @deprecated Use {@link TetheringManager#startTethering} instead
2871 *
2872 * {@hide}
2873 */
2874 @UnsupportedAppUsage
2875 @Deprecated
2876 public int setUsbTethering(boolean enable) {
2877 return mTetheringManager.setUsbTethering(enable);
2878 }
2879
2880 /**
2881 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2882 * {@hide}
2883 */
2884 @SystemApi
2885 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002886 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002887 /**
2888 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2889 * {@hide}
2890 */
2891 @Deprecated
2892 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2893 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2894 /**
2895 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2896 * {@hide}
2897 */
2898 @Deprecated
2899 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2900 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2901 /**
2902 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2903 * {@hide}
2904 */
2905 @Deprecated
2906 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2907 /**
2908 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2909 * {@hide}
2910 */
2911 @Deprecated
2912 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2913 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2914 /**
2915 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
2916 * {@hide}
2917 */
2918 @Deprecated
2919 public static final int TETHER_ERROR_MASTER_ERROR =
2920 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
2921 /**
2922 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2923 * {@hide}
2924 */
2925 @Deprecated
2926 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2927 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2928 /**
2929 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2930 * {@hide}
2931 */
2932 @Deprecated
2933 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2934 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2935 /**
2936 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
2937 * {@hide}
2938 */
2939 @Deprecated
2940 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
2941 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
2942 /**
2943 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
2944 * {@hide}
2945 */
2946 @Deprecated
2947 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
2948 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
2949 /**
2950 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2951 * {@hide}
2952 */
2953 @Deprecated
2954 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2955 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2956 /**
2957 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
2958 * {@hide}
2959 */
2960 @SystemApi
2961 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002962 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002963 /**
2964 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2965 * {@hide}
2966 */
2967 @Deprecated
2968 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2969 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2970 /**
2971 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2972 * {@hide}
2973 */
2974 @SystemApi
2975 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002976 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002977
2978 /**
2979 * Get a more detailed error code after a Tethering or Untethering
2980 * request asynchronously failed.
2981 *
2982 * @param iface The name of the interface of interest
2983 * @return error The error code of the last error tethering or untethering the named
2984 * interface
2985 *
2986 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2987 * {@hide}
2988 */
2989 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2990 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2991 @Deprecated
2992 public int getLastTetherError(String iface) {
2993 int error = mTetheringManager.getLastTetherError(iface);
2994 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2995 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2996 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2997 // instead.
2998 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2999 }
3000 return error;
3001 }
3002
3003 /** @hide */
3004 @Retention(RetentionPolicy.SOURCE)
3005 @IntDef(value = {
3006 TETHER_ERROR_NO_ERROR,
3007 TETHER_ERROR_PROVISION_FAILED,
3008 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3009 })
3010 public @interface EntitlementResultCode {
3011 }
3012
3013 /**
3014 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3015 * entitlement succeeded.
3016 *
3017 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3018 * @hide
3019 */
3020 @SystemApi
3021 @Deprecated
3022 public interface OnTetheringEntitlementResultListener {
3023 /**
3024 * Called to notify entitlement result.
3025 *
3026 * @param resultCode an int value of entitlement result. It may be one of
3027 * {@link #TETHER_ERROR_NO_ERROR},
3028 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3029 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3030 */
3031 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3032 }
3033
3034 /**
3035 * Get the last value of the entitlement check on this downstream. If the cached value is
3036 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3037 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3038 * guaranteed that the UI-based entitlement check will complete in any specific time period
3039 * and may in fact never complete. Any successful entitlement check the platform performs for
3040 * any reason will update the cached value.
3041 *
3042 * @param type the downstream type of tethering. Must be one of
3043 * {@link #TETHERING_WIFI},
3044 * {@link #TETHERING_USB}, or
3045 * {@link #TETHERING_BLUETOOTH}.
3046 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3047 * @param executor the executor on which callback will be invoked.
3048 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3049 * notify the caller of the result of entitlement check. The listener may be called zero
3050 * or one time.
3051 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3052 * {@hide}
3053 */
3054 @SystemApi
3055 @Deprecated
3056 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3057 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3058 @NonNull @CallbackExecutor Executor executor,
3059 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003060 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003061 ResultReceiver wrappedListener = new ResultReceiver(null) {
3062 @Override
3063 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003064 final long token = Binder.clearCallingIdentity();
3065 try {
3066 executor.execute(() -> {
3067 listener.onTetheringEntitlementResult(resultCode);
3068 });
3069 } finally {
3070 Binder.restoreCallingIdentity(token);
3071 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003072 }
3073 };
3074
3075 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
3076 showEntitlementUi);
3077 }
3078
3079 /**
3080 * Report network connectivity status. This is currently used only
3081 * to alter status bar UI.
3082 * <p>This method requires the caller to hold the permission
3083 * {@link android.Manifest.permission#STATUS_BAR}.
3084 *
3085 * @param networkType The type of network you want to report on
3086 * @param percentage The quality of the connection 0 is bad, 100 is good
3087 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3088 * {@hide}
3089 */
3090 public void reportInetCondition(int networkType, int percentage) {
3091 printStackTrace();
3092 try {
3093 mService.reportInetCondition(networkType, percentage);
3094 } catch (RemoteException e) {
3095 throw e.rethrowFromSystemServer();
3096 }
3097 }
3098
3099 /**
3100 * Report a problem network to the framework. This provides a hint to the system
3101 * that there might be connectivity problems on this network and may cause
3102 * the framework to re-evaluate network connectivity and/or switch to another
3103 * network.
3104 *
3105 * @param network The {@link Network} the application was attempting to use
3106 * or {@code null} to indicate the current default network.
3107 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3108 * working and non-working connectivity.
3109 */
3110 @Deprecated
3111 public void reportBadNetwork(@Nullable Network network) {
3112 printStackTrace();
3113 try {
3114 // One of these will be ignored because it matches system's current state.
3115 // The other will trigger the necessary reevaluation.
3116 mService.reportNetworkConnectivity(network, true);
3117 mService.reportNetworkConnectivity(network, false);
3118 } catch (RemoteException e) {
3119 throw e.rethrowFromSystemServer();
3120 }
3121 }
3122
3123 /**
3124 * Report to the framework whether a network has working connectivity.
3125 * This provides a hint to the system that a particular network is providing
3126 * working connectivity or not. In response the framework may re-evaluate
3127 * the network's connectivity and might take further action thereafter.
3128 *
3129 * @param network The {@link Network} the application was attempting to use
3130 * or {@code null} to indicate the current default network.
3131 * @param hasConnectivity {@code true} if the application was able to successfully access the
3132 * Internet using {@code network} or {@code false} if not.
3133 */
3134 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3135 printStackTrace();
3136 try {
3137 mService.reportNetworkConnectivity(network, hasConnectivity);
3138 } catch (RemoteException e) {
3139 throw e.rethrowFromSystemServer();
3140 }
3141 }
3142
3143 /**
3144 * Set a network-independent global http proxy. This is not normally what you want
3145 * for typical HTTP proxies - they are general network dependent. However if you're
3146 * doing something unusual like general internal filtering this may be useful. On
3147 * a private network where the proxy is not accessible, you may break HTTP using this.
3148 *
3149 * @param p A {@link ProxyInfo} object defining the new global
3150 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
3151 * @hide
3152 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003153 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003154 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chiachang Wangf9294e72021-03-18 09:44:34 +08003155 public void setGlobalProxy(@Nullable ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003156 try {
3157 mService.setGlobalProxy(p);
3158 } catch (RemoteException e) {
3159 throw e.rethrowFromSystemServer();
3160 }
3161 }
3162
3163 /**
3164 * Retrieve any network-independent global HTTP proxy.
3165 *
3166 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3167 * if no global HTTP proxy is set.
3168 * @hide
3169 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003170 @SystemApi(client = MODULE_LIBRARIES)
3171 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003172 public ProxyInfo getGlobalProxy() {
3173 try {
3174 return mService.getGlobalProxy();
3175 } catch (RemoteException e) {
3176 throw e.rethrowFromSystemServer();
3177 }
3178 }
3179
3180 /**
3181 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3182 * network-specific HTTP proxy. If {@code network} is null, the
3183 * network-specific proxy returned is the proxy of the default active
3184 * network.
3185 *
3186 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3187 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3188 * or when {@code network} is {@code null},
3189 * the {@code ProxyInfo} for the default active network. Returns
3190 * {@code null} when no proxy applies or the caller doesn't have
3191 * permission to use {@code network}.
3192 * @hide
3193 */
3194 public ProxyInfo getProxyForNetwork(Network network) {
3195 try {
3196 return mService.getProxyForNetwork(network);
3197 } catch (RemoteException e) {
3198 throw e.rethrowFromSystemServer();
3199 }
3200 }
3201
3202 /**
3203 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3204 * otherwise if this process is bound to a {@link Network} using
3205 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3206 * the default network's proxy is returned.
3207 *
3208 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3209 * HTTP proxy is active.
3210 */
3211 @Nullable
3212 public ProxyInfo getDefaultProxy() {
3213 return getProxyForNetwork(getBoundNetworkForProcess());
3214 }
3215
3216 /**
3217 * Returns true if the hardware supports the given network type
3218 * else it returns false. This doesn't indicate we have coverage
3219 * or are authorized onto a network, just whether or not the
3220 * hardware supports it. For example a GSM phone without a SIM
3221 * should still return {@code true} for mobile data, but a wifi only
3222 * tablet would return {@code false}.
3223 *
3224 * @param networkType The network type we'd like to check
3225 * @return {@code true} if supported, else {@code false}
3226 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3227 * @hide
3228 */
3229 @Deprecated
3230 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3231 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3232 public boolean isNetworkSupported(int networkType) {
3233 try {
3234 return mService.isNetworkSupported(networkType);
3235 } catch (RemoteException e) {
3236 throw e.rethrowFromSystemServer();
3237 }
3238 }
3239
3240 /**
3241 * Returns if the currently active data network is metered. A network is
3242 * classified as metered when the user is sensitive to heavy data usage on
3243 * that connection due to monetary costs, data limitations or
3244 * battery/performance issues. You should check this before doing large
3245 * data transfers, and warn the user or delay the operation until another
3246 * network is available.
3247 *
3248 * @return {@code true} if large transfers should be avoided, otherwise
3249 * {@code false}.
3250 */
3251 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3252 public boolean isActiveNetworkMetered() {
3253 try {
3254 return mService.isActiveNetworkMetered();
3255 } catch (RemoteException e) {
3256 throw e.rethrowFromSystemServer();
3257 }
3258 }
3259
3260 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003261 * Set sign in error notification to visible or invisible
3262 *
3263 * @hide
3264 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3265 */
3266 @Deprecated
3267 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3268 String action) {
3269 try {
3270 mService.setProvisioningNotificationVisible(visible, networkType, action);
3271 } catch (RemoteException e) {
3272 throw e.rethrowFromSystemServer();
3273 }
3274 }
3275
3276 /**
3277 * Set the value for enabling/disabling airplane mode
3278 *
3279 * @param enable whether to enable airplane mode or not
3280 *
3281 * @hide
3282 */
3283 @RequiresPermission(anyOf = {
3284 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3285 android.Manifest.permission.NETWORK_SETTINGS,
3286 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3287 android.Manifest.permission.NETWORK_STACK})
3288 @SystemApi
3289 public void setAirplaneMode(boolean enable) {
3290 try {
3291 mService.setAirplaneMode(enable);
3292 } catch (RemoteException e) {
3293 throw e.rethrowFromSystemServer();
3294 }
3295 }
3296
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003297 /**
3298 * Registers the specified {@link NetworkProvider}.
3299 * Each listener must only be registered once. The listener can be unregistered with
3300 * {@link #unregisterNetworkProvider}.
3301 *
3302 * @param provider the provider to register
3303 * @return the ID of the provider. This ID must be used by the provider when registering
3304 * {@link android.net.NetworkAgent}s.
3305 * @hide
3306 */
3307 @SystemApi
3308 @RequiresPermission(anyOf = {
3309 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3310 android.Manifest.permission.NETWORK_FACTORY})
3311 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3312 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3313 throw new IllegalStateException("NetworkProviders can only be registered once");
3314 }
3315
3316 try {
3317 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3318 provider.getName());
3319 provider.setProviderId(providerId);
3320 } catch (RemoteException e) {
3321 throw e.rethrowFromSystemServer();
3322 }
3323 return provider.getProviderId();
3324 }
3325
3326 /**
3327 * Unregisters the specified NetworkProvider.
3328 *
3329 * @param provider the provider to unregister
3330 * @hide
3331 */
3332 @SystemApi
3333 @RequiresPermission(anyOf = {
3334 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3335 android.Manifest.permission.NETWORK_FACTORY})
3336 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3337 try {
3338 mService.unregisterNetworkProvider(provider.getMessenger());
3339 } catch (RemoteException e) {
3340 throw e.rethrowFromSystemServer();
3341 }
3342 provider.setProviderId(NetworkProvider.ID_NONE);
3343 }
3344
3345
3346 /** @hide exposed via the NetworkProvider class. */
3347 @RequiresPermission(anyOf = {
3348 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3349 android.Manifest.permission.NETWORK_FACTORY})
3350 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3351 try {
3352 mService.declareNetworkRequestUnfulfillable(request);
3353 } catch (RemoteException e) {
3354 throw e.rethrowFromSystemServer();
3355 }
3356 }
3357
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003358 /**
3359 * @hide
3360 * Register a NetworkAgent with ConnectivityService.
3361 * @return Network corresponding to NetworkAgent.
3362 */
3363 @RequiresPermission(anyOf = {
3364 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3365 android.Manifest.permission.NETWORK_FACTORY})
3366 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003367 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3368 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003369 try {
3370 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3371 } catch (RemoteException e) {
3372 throw e.rethrowFromSystemServer();
3373 }
3374 }
3375
3376 /**
3377 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3378 * changes. Should be extended by applications wanting notifications.
3379 *
3380 * A {@code NetworkCallback} is registered by calling
3381 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3382 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3383 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3384 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3385 * A {@code NetworkCallback} should be registered at most once at any time.
3386 * A {@code NetworkCallback} that has been unregistered can be registered again.
3387 */
3388 public static class NetworkCallback {
3389 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003390 * No flags associated with this callback.
3391 * @hide
3392 */
3393 public static final int FLAG_NONE = 0;
3394 /**
3395 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3396 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3397 * <p>
3398 * These include:
3399 * <li> Some transport info instances (retrieved via
3400 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3401 * contain location sensitive information.
3402 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3403 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3404 * </p>
3405 * <p>
3406 * Note:
3407 * <li> Retrieving this location sensitive information (subject to app's location
3408 * permissions) will be noted by system. </li>
3409 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3410 * not include location sensitive info.
3411 * </p>
3412 */
3413 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3414
3415 /** @hide */
3416 @Retention(RetentionPolicy.SOURCE)
3417 @IntDef(flag = true, prefix = "FLAG_", value = {
3418 FLAG_NONE,
3419 FLAG_INCLUDE_LOCATION_INFO
3420 })
3421 public @interface Flag { }
3422
3423 /**
3424 * All the valid flags for error checking.
3425 */
3426 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3427
3428 public NetworkCallback() {
3429 this(FLAG_NONE);
3430 }
3431
3432 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003433 if ((flags & VALID_FLAGS) != flags) {
3434 throw new IllegalArgumentException("Invalid flags");
3435 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003436 mFlags = flags;
3437 }
3438
3439 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003440 * Called when the framework connects to a new network to evaluate whether it satisfies this
3441 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3442 * callback. There is no guarantee that this new network will satisfy any requests, or that
3443 * the network will stay connected for longer than the time necessary to evaluate it.
3444 * <p>
3445 * Most applications <b>should not</b> act on this callback, and should instead use
3446 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3447 * the framework in properly evaluating the network &mdash; for example, an application that
3448 * can automatically log in to a captive portal without user intervention.
3449 *
3450 * @param network The {@link Network} of the network that is being evaluated.
3451 *
3452 * @hide
3453 */
3454 public void onPreCheck(@NonNull Network network) {}
3455
3456 /**
3457 * Called when the framework connects and has declared a new network ready for use.
3458 * This callback may be called more than once if the {@link Network} that is
3459 * satisfying the request changes.
3460 *
3461 * @param network The {@link Network} of the satisfying network.
3462 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3463 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3464 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3465 * @hide
3466 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003467 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003468 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003469 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003470 // Internally only this method is called when a new network is available, and
3471 // it calls the callback in the same way and order that older versions used
3472 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003473 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3474 onBlockedStatusChanged(network, blocked);
3475 }
3476
3477 /**
3478 * Legacy variant of onAvailable that takes a boolean blocked reason.
3479 *
3480 * This method has never been public API, but it's not final, so there may be apps that
3481 * implemented it and rely on it being called. Do our best not to break them.
3482 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3483 * this method is called. There does not seem to be a way to avoid this.
3484 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3485 *
3486 * @hide
3487 */
3488 public void onAvailable(@NonNull Network network,
3489 @NonNull NetworkCapabilities networkCapabilities,
3490 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003491 onAvailable(network);
3492 if (!networkCapabilities.hasCapability(
3493 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3494 onNetworkSuspended(network);
3495 }
3496 onCapabilitiesChanged(network, networkCapabilities);
3497 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003498 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003499 }
3500
3501 /**
3502 * Called when the framework connects and has declared a new network ready for use.
3503 *
3504 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3505 * be available at the same time, and onAvailable will be called for each of these as they
3506 * appear.
3507 *
3508 * <p>For callbacks registered with {@link #requestNetwork} and
3509 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3510 * is the new best network for this request and is now tracked by this callback ; this
3511 * callback will no longer receive method calls about other networks that may have been
3512 * passed to this method previously. The previously-best network may have disconnected, or
3513 * it may still be around and the newly-best network may simply be better.
3514 *
3515 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3516 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3517 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3518 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3519 *
3520 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3521 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3522 * this callback as this is prone to race conditions (there is no guarantee the objects
3523 * returned by these methods will be current). Instead, wait for a call to
3524 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3525 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3526 * to be well-ordered with respect to other callbacks.
3527 *
3528 * @param network The {@link Network} of the satisfying network.
3529 */
3530 public void onAvailable(@NonNull Network network) {}
3531
3532 /**
3533 * Called when the network is about to be lost, typically because there are no outstanding
3534 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3535 * with the new replacement network for graceful handover. This method is not guaranteed
3536 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3537 * network is suddenly disconnected.
3538 *
3539 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3540 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3541 * this callback as this is prone to race conditions ; calling these methods while in a
3542 * callback may return an outdated or even a null object.
3543 *
3544 * @param network The {@link Network} that is about to be lost.
3545 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3546 * connected for graceful handover; note that the network may still
3547 * suffer a hard loss at any time.
3548 */
3549 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3550
3551 /**
3552 * Called when a network disconnects or otherwise no longer satisfies this request or
3553 * callback.
3554 *
3555 * <p>If the callback was registered with requestNetwork() or
3556 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3557 * returned by onAvailable() when that network is lost and no other network satisfies
3558 * the criteria of the request.
3559 *
3560 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3561 * each network which no longer satisfies the criteria of the callback.
3562 *
3563 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3564 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3565 * this callback as this is prone to race conditions ; calling these methods while in a
3566 * callback may return an outdated or even a null object.
3567 *
3568 * @param network The {@link Network} lost.
3569 */
3570 public void onLost(@NonNull Network network) {}
3571
3572 /**
3573 * Called if no network is found within the timeout time specified in
3574 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3575 * requested network request cannot be fulfilled (whether or not a timeout was
3576 * specified). When this callback is invoked the associated
3577 * {@link NetworkRequest} will have already been removed and released, as if
3578 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3579 */
3580 public void onUnavailable() {}
3581
3582 /**
3583 * Called when the network corresponding to this request changes capabilities but still
3584 * satisfies the requested criteria.
3585 *
3586 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3587 * to be called immediately after {@link #onAvailable}.
3588 *
3589 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3590 * ConnectivityManager methods in this callback as this is prone to race conditions :
3591 * calling these methods while in a callback may return an outdated or even a null object.
3592 *
3593 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003594 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003595 * network.
3596 */
3597 public void onCapabilitiesChanged(@NonNull Network network,
3598 @NonNull NetworkCapabilities networkCapabilities) {}
3599
3600 /**
3601 * Called when the network corresponding to this request changes {@link LinkProperties}.
3602 *
3603 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3604 * to be called immediately after {@link #onAvailable}.
3605 *
3606 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3607 * ConnectivityManager methods in this callback as this is prone to race conditions :
3608 * calling these methods while in a callback may return an outdated or even a null object.
3609 *
3610 * @param network The {@link Network} whose link properties have changed.
3611 * @param linkProperties The new {@link LinkProperties} for this network.
3612 */
3613 public void onLinkPropertiesChanged(@NonNull Network network,
3614 @NonNull LinkProperties linkProperties) {}
3615
3616 /**
3617 * Called when the network the framework connected to for this request suspends data
3618 * transmission temporarily.
3619 *
3620 * <p>This generally means that while the TCP connections are still live temporarily
3621 * network data fails to transfer. To give a specific example, this is used on cellular
3622 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3623 * means read operations on sockets on this network will block once the buffers are
3624 * drained, and write operations will block once the buffers are full.
3625 *
3626 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3627 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3628 * this callback as this is prone to race conditions (there is no guarantee the objects
3629 * returned by these methods will be current).
3630 *
3631 * @hide
3632 */
3633 public void onNetworkSuspended(@NonNull Network network) {}
3634
3635 /**
3636 * Called when the network the framework connected to for this request
3637 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3638 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3639
3640 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3641 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3642 * this callback as this is prone to race conditions : calling these methods while in a
3643 * callback may return an outdated or even a null object.
3644 *
3645 * @hide
3646 */
3647 public void onNetworkResumed(@NonNull Network network) {}
3648
3649 /**
3650 * Called when access to the specified network is blocked or unblocked.
3651 *
3652 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3653 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3654 * this callback as this is prone to race conditions : calling these methods while in a
3655 * callback may return an outdated or even a null object.
3656 *
3657 * @param network The {@link Network} whose blocked status has changed.
3658 * @param blocked The blocked status of this {@link Network}.
3659 */
3660 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3661
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003662 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09003663 * Called when access to the specified network is blocked or unblocked, or the reason for
3664 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003665 *
3666 * If a NetworkCallback object implements this method,
3667 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3668 *
3669 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3670 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3671 * this callback as this is prone to race conditions : calling these methods while in a
3672 * callback may return an outdated or even a null object.
3673 *
3674 * @param network The {@link Network} whose blocked status has changed.
3675 * @param blocked The blocked status of this {@link Network}.
3676 * @hide
3677 */
3678 @SystemApi(client = MODULE_LIBRARIES)
3679 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3680 onBlockedStatusChanged(network, blocked != 0);
3681 }
3682
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003683 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08003684 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003685 }
3686
3687 /**
3688 * Constant error codes used by ConnectivityService to communicate about failures and errors
3689 * across a Binder boundary.
3690 * @hide
3691 */
3692 public interface Errors {
3693 int TOO_MANY_REQUESTS = 1;
3694 }
3695
3696 /** @hide */
3697 public static class TooManyRequestsException extends RuntimeException {}
3698
3699 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3700 switch (e.errorCode) {
3701 case Errors.TOO_MANY_REQUESTS:
3702 return new TooManyRequestsException();
3703 default:
3704 Log.w(TAG, "Unknown service error code " + e.errorCode);
3705 return new RuntimeException(e);
3706 }
3707 }
3708
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003709 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003710 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003711 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003712 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003713 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003714 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003715 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003716 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003717 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003718 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003719 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003720 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003721 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003722 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003723 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003724 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003725 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003726 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003727 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003728 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003729 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003730 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003731
3732 /** @hide */
3733 public static String getCallbackName(int whichCallback) {
3734 switch (whichCallback) {
3735 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3736 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3737 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3738 case CALLBACK_LOST: return "CALLBACK_LOST";
3739 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3740 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3741 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
3742 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3743 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3744 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
3745 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
3746 default:
3747 return Integer.toString(whichCallback);
3748 }
3749 }
3750
3751 private class CallbackHandler extends Handler {
3752 private static final String TAG = "ConnectivityManager.CallbackHandler";
3753 private static final boolean DBG = false;
3754
3755 CallbackHandler(Looper looper) {
3756 super(looper);
3757 }
3758
3759 CallbackHandler(Handler handler) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003760 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003761 }
3762
3763 @Override
3764 public void handleMessage(Message message) {
3765 if (message.what == EXPIRE_LEGACY_REQUEST) {
3766 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3767 return;
3768 }
3769
3770 final NetworkRequest request = getObject(message, NetworkRequest.class);
3771 final Network network = getObject(message, Network.class);
3772 final NetworkCallback callback;
3773 synchronized (sCallbacks) {
3774 callback = sCallbacks.get(request);
3775 if (callback == null) {
3776 Log.w(TAG,
3777 "callback not found for " + getCallbackName(message.what) + " message");
3778 return;
3779 }
3780 if (message.what == CALLBACK_UNAVAIL) {
3781 sCallbacks.remove(request);
3782 callback.networkRequest = ALREADY_UNREGISTERED;
3783 }
3784 }
3785 if (DBG) {
3786 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
3787 }
3788
3789 switch (message.what) {
3790 case CALLBACK_PRECHECK: {
3791 callback.onPreCheck(network);
3792 break;
3793 }
3794 case CALLBACK_AVAILABLE: {
3795 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3796 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003797 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003798 break;
3799 }
3800 case CALLBACK_LOSING: {
3801 callback.onLosing(network, message.arg1);
3802 break;
3803 }
3804 case CALLBACK_LOST: {
3805 callback.onLost(network);
3806 break;
3807 }
3808 case CALLBACK_UNAVAIL: {
3809 callback.onUnavailable();
3810 break;
3811 }
3812 case CALLBACK_CAP_CHANGED: {
3813 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3814 callback.onCapabilitiesChanged(network, cap);
3815 break;
3816 }
3817 case CALLBACK_IP_CHANGED: {
3818 LinkProperties lp = getObject(message, LinkProperties.class);
3819 callback.onLinkPropertiesChanged(network, lp);
3820 break;
3821 }
3822 case CALLBACK_SUSPENDED: {
3823 callback.onNetworkSuspended(network);
3824 break;
3825 }
3826 case CALLBACK_RESUMED: {
3827 callback.onNetworkResumed(network);
3828 break;
3829 }
3830 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003831 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003832 }
3833 }
3834 }
3835
3836 private <T> T getObject(Message msg, Class<T> c) {
3837 return (T) msg.getData().getParcelable(c.getSimpleName());
3838 }
3839 }
3840
3841 private CallbackHandler getDefaultHandler() {
3842 synchronized (sCallbacks) {
3843 if (sCallbackHandler == null) {
3844 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
3845 }
3846 return sCallbackHandler;
3847 }
3848 }
3849
3850 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3851 private static CallbackHandler sCallbackHandler;
3852
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003853 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3854 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3855 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003856 printStackTrace();
3857 checkCallbackNotNull(callback);
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003858 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3859 throw new IllegalArgumentException("null NetworkCapabilities");
3860 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003861 final NetworkRequest request;
3862 final String callingPackageName = mContext.getOpPackageName();
3863 try {
3864 synchronized(sCallbacks) {
3865 if (callback.networkRequest != null
3866 && callback.networkRequest != ALREADY_UNREGISTERED) {
3867 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3868 // and requests (http://b/20701525).
3869 Log.e(TAG, "NetworkCallback was already registered");
3870 }
3871 Messenger messenger = new Messenger(handler);
3872 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08003873 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003874 if (reqType == LISTEN) {
3875 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08003876 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08003877 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003878 } else {
3879 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003880 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3881 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003882 }
3883 if (request != null) {
3884 sCallbacks.put(request, callback);
3885 }
3886 callback.networkRequest = request;
3887 }
3888 } catch (RemoteException e) {
3889 throw e.rethrowFromSystemServer();
3890 } catch (ServiceSpecificException e) {
3891 throw convertServiceException(e);
3892 }
3893 return request;
3894 }
3895
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003896 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3897 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3898 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3899 legacyType, handler);
3900 }
3901
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003902 /**
3903 * Helper function to request a network with a particular legacy type.
3904 *
3905 * This API is only for use in internal system code that requests networks with legacy type and
3906 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
3907 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
3908 *
3909 * @param request {@link NetworkRequest} describing this request.
3910 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3911 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3912 * be a positive value (i.e. >0).
3913 * @param legacyType to specify the network type(#TYPE_*).
3914 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3915 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3916 * the callback must not be shared - it uniquely specifies this request.
3917 *
3918 * @hide
3919 */
3920 @SystemApi
3921 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
3922 public void requestNetwork(@NonNull NetworkRequest request,
3923 int timeoutMs, int legacyType, @NonNull Handler handler,
3924 @NonNull NetworkCallback networkCallback) {
3925 if (legacyType == TYPE_NONE) {
3926 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3927 }
3928 CallbackHandler cbHandler = new CallbackHandler(handler);
3929 NetworkCapabilities nc = request.networkCapabilities;
3930 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
3931 }
3932
3933 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003934 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003935 *
3936 * <p>This method will attempt to find the best network that matches the passed
3937 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3938 * criteria. The platform will evaluate which network is the best at its own discretion.
3939 * Throughput, latency, cost per byte, policy, user preference and other considerations
3940 * may be factored in the decision of what is considered the best network.
3941 *
3942 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3943 * matching this request, while always attempting to match the request to a better network if
3944 * possible. If a better match is found, the platform will switch this request to the now-best
3945 * network and inform the app of the newly best network by invoking
3946 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3947 * will not try to maintain any other network than the best one currently matching the request:
3948 * a network not matching any network request may be disconnected at any time.
3949 *
3950 * <p>For example, an application could use this method to obtain a connected cellular network
3951 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3952 * radio to consume additional power. Or, an application could inform the system that it wants
3953 * a network supporting sending MMSes and have the system let it know about the currently best
3954 * MMS-supporting network through the provided {@link NetworkCallback}.
3955 *
3956 * <p>The status of the request can be followed by listening to the various callbacks described
3957 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3958 * used to direct traffic to the network (although accessing some networks may be subject to
3959 * holding specific permissions). Callers will learn about the specific characteristics of the
3960 * network through
3961 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3962 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3963 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3964 * matching the request at any given time; therefore when a better network matching the request
3965 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3966 * with the new network after which no further updates are given about the previously-best
3967 * network, unless it becomes the best again at some later time. All callbacks are invoked
3968 * in order on the same thread, which by default is a thread created by the framework running
3969 * in the app.
3970 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3971 * callbacks are invoked.
3972 *
3973 * <p>This{@link NetworkRequest} will live until released via
3974 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3975 * which point the system may let go of the network at any time.
3976 *
3977 * <p>A version of this method which takes a timeout is
3978 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3979 * wait for a limited amount of time for the network to become unavailable.
3980 *
3981 * <p>It is presently unsupported to request a network with mutable
3982 * {@link NetworkCapabilities} such as
3983 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3984 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3985 * as these {@code NetworkCapabilities} represent states that a particular
3986 * network may never attain, and whether a network will attain these states
3987 * is unknown prior to bringing up the network so the framework does not
3988 * know how to go about satisfying a request with these capabilities.
3989 *
3990 * <p>This method requires the caller to hold either the
3991 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3992 * or the ability to modify system settings as determined by
3993 * {@link android.provider.Settings.System#canWrite}.</p>
3994 *
3995 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3996 * number of outstanding requests to 100 per app (identified by their UID), shared with
3997 * all variants of this method, of {@link #registerNetworkCallback} as well as
3998 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3999 * Requesting a network with this method will count toward this limit. If this limit is
4000 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4001 * make sure to unregister the callbacks with
4002 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4003 *
4004 * @param request {@link NetworkRequest} describing this request.
4005 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4006 * the callback must not be shared - it uniquely specifies this request.
4007 * The callback is invoked on the default internal Handler.
4008 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4009 * @throws SecurityException if missing the appropriate permissions.
4010 * @throws RuntimeException if the app already has too many callbacks registered.
4011 */
4012 public void requestNetwork(@NonNull NetworkRequest request,
4013 @NonNull NetworkCallback networkCallback) {
4014 requestNetwork(request, networkCallback, getDefaultHandler());
4015 }
4016
4017 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004018 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004019 *
4020 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4021 * but runs all the callbacks on the passed Handler.
4022 *
4023 * <p>This method has the same permission requirements as
4024 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4025 * and throws the same exceptions in the same conditions.
4026 *
4027 * @param request {@link NetworkRequest} describing this request.
4028 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4029 * the callback must not be shared - it uniquely specifies this request.
4030 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4031 */
4032 public void requestNetwork(@NonNull NetworkRequest request,
4033 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4034 CallbackHandler cbHandler = new CallbackHandler(handler);
4035 NetworkCapabilities nc = request.networkCapabilities;
4036 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4037 }
4038
4039 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004040 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004041 * by a timeout.
4042 *
4043 * This function behaves identically to the non-timed-out version
4044 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4045 * is not found within the given time (in milliseconds) the
4046 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4047 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4048 * not have to be released if timed-out (it is automatically released). Unregistering a
4049 * request that timed out is not an error.
4050 *
4051 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4052 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4053 * for that purpose. Calling this method will attempt to bring up the requested network.
4054 *
4055 * <p>This method has the same permission requirements as
4056 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4057 * and throws the same exceptions in the same conditions.
4058 *
4059 * @param request {@link NetworkRequest} describing this request.
4060 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4061 * the callback must not be shared - it uniquely specifies this request.
4062 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4063 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4064 * be a positive value (i.e. >0).
4065 */
4066 public void requestNetwork(@NonNull NetworkRequest request,
4067 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4068 checkTimeout(timeoutMs);
4069 NetworkCapabilities nc = request.networkCapabilities;
4070 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4071 getDefaultHandler());
4072 }
4073
4074 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004075 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004076 * by a timeout.
4077 *
4078 * This method behaves identically to
4079 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4080 * on the passed Handler.
4081 *
4082 * <p>This method has the same permission requirements as
4083 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4084 * and throws the same exceptions in the same conditions.
4085 *
4086 * @param request {@link NetworkRequest} describing this request.
4087 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4088 * the callback must not be shared - it uniquely specifies this request.
4089 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4090 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4091 * before {@link NetworkCallback#onUnavailable} is called.
4092 */
4093 public void requestNetwork(@NonNull NetworkRequest request,
4094 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4095 checkTimeout(timeoutMs);
4096 CallbackHandler cbHandler = new CallbackHandler(handler);
4097 NetworkCapabilities nc = request.networkCapabilities;
4098 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4099 }
4100
4101 /**
4102 * The lookup key for a {@link Network} object included with the intent after
4103 * successfully finding a network for the applications request. Retrieve it with
4104 * {@link android.content.Intent#getParcelableExtra(String)}.
4105 * <p>
4106 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4107 * then you must get a ConnectivityManager instance before doing so.
4108 */
4109 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4110
4111 /**
4112 * The lookup key for a {@link NetworkRequest} object included with the intent after
4113 * successfully finding a network for the applications request. Retrieve it with
4114 * {@link android.content.Intent#getParcelableExtra(String)}.
4115 */
4116 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4117
4118
4119 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004120 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004121 *
4122 * This function behaves identically to the version that takes a NetworkCallback, but instead
4123 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4124 * the request may outlive the calling application and get called back when a suitable
4125 * network is found.
4126 * <p>
4127 * The operation is an Intent broadcast that goes to a broadcast receiver that
4128 * you registered with {@link Context#registerReceiver} or through the
4129 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4130 * <p>
4131 * The operation Intent is delivered with two extras, a {@link Network} typed
4132 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4133 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4134 * the original requests parameters. It is important to create a new,
4135 * {@link NetworkCallback} based request before completing the processing of the
4136 * Intent to reserve the network or it will be released shortly after the Intent
4137 * is processed.
4138 * <p>
4139 * If there is already a request for this Intent registered (with the equality of
4140 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4141 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4142 * <p>
4143 * The request may be released normally by calling
4144 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4145 * <p>It is presently unsupported to request a network with either
4146 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4147 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4148 * as these {@code NetworkCapabilities} represent states that a particular
4149 * network may never attain, and whether a network will attain these states
4150 * is unknown prior to bringing up the network so the framework does not
4151 * know how to go about satisfying a request with these capabilities.
4152 *
4153 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4154 * number of outstanding requests to 100 per app (identified by their UID), shared with
4155 * all variants of this method, of {@link #registerNetworkCallback} as well as
4156 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4157 * Requesting a network with this method will count toward this limit. If this limit is
4158 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4159 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4160 * or {@link #releaseNetworkRequest(PendingIntent)}.
4161 *
4162 * <p>This method requires the caller to hold either the
4163 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4164 * or the ability to modify system settings as determined by
4165 * {@link android.provider.Settings.System#canWrite}.</p>
4166 *
4167 * @param request {@link NetworkRequest} describing this request.
4168 * @param operation Action to perform when the network is available (corresponds
4169 * to the {@link NetworkCallback#onAvailable} call. Typically
4170 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4171 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4172 * @throws SecurityException if missing the appropriate permissions.
4173 * @throws RuntimeException if the app already has too many callbacks registered.
4174 */
4175 public void requestNetwork(@NonNull NetworkRequest request,
4176 @NonNull PendingIntent operation) {
4177 printStackTrace();
4178 checkPendingIntentNotNull(operation);
4179 try {
4180 mService.pendingRequestForNetwork(
4181 request.networkCapabilities, operation, mContext.getOpPackageName(),
4182 getAttributionTag());
4183 } catch (RemoteException e) {
4184 throw e.rethrowFromSystemServer();
4185 } catch (ServiceSpecificException e) {
4186 throw convertServiceException(e);
4187 }
4188 }
4189
4190 /**
4191 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4192 * <p>
4193 * This method has the same behavior as
4194 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4195 * releasing network resources and disconnecting.
4196 *
4197 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4198 * PendingIntent passed to
4199 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4200 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4201 */
4202 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4203 printStackTrace();
4204 checkPendingIntentNotNull(operation);
4205 try {
4206 mService.releasePendingNetworkRequest(operation);
4207 } catch (RemoteException e) {
4208 throw e.rethrowFromSystemServer();
4209 }
4210 }
4211
4212 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004213 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004214 }
4215
4216 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004217 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004218 }
4219
4220 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004221 if (timeoutMs <= 0) {
4222 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4223 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004224 }
4225
4226 /**
4227 * Registers to receive notifications about all networks which satisfy the given
4228 * {@link NetworkRequest}. The callbacks will continue to be called until
4229 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4230 * called.
4231 *
4232 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4233 * number of outstanding requests to 100 per app (identified by their UID), shared with
4234 * all variants of this method, of {@link #requestNetwork} as well as
4235 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4236 * Requesting a network with this method will count toward this limit. If this limit is
4237 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4238 * make sure to unregister the callbacks with
4239 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4240 *
4241 * @param request {@link NetworkRequest} describing this request.
4242 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4243 * networks change state.
4244 * The callback is invoked on the default internal Handler.
4245 * @throws RuntimeException if the app already has too many callbacks registered.
4246 */
4247 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4248 public void registerNetworkCallback(@NonNull NetworkRequest request,
4249 @NonNull NetworkCallback networkCallback) {
4250 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4251 }
4252
4253 /**
4254 * Registers to receive notifications about all networks which satisfy the given
4255 * {@link NetworkRequest}. The callbacks will continue to be called until
4256 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4257 * called.
4258 *
4259 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4260 * number of outstanding requests to 100 per app (identified by their UID), shared with
4261 * all variants of this method, of {@link #requestNetwork} as well as
4262 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4263 * Requesting a network with this method will count toward this limit. If this limit is
4264 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4265 * make sure to unregister the callbacks with
4266 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4267 *
4268 *
4269 * @param request {@link NetworkRequest} describing this request.
4270 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4271 * networks change state.
4272 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4273 * @throws RuntimeException if the app already has too many callbacks registered.
4274 */
4275 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4276 public void registerNetworkCallback(@NonNull NetworkRequest request,
4277 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4278 CallbackHandler cbHandler = new CallbackHandler(handler);
4279 NetworkCapabilities nc = request.networkCapabilities;
4280 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4281 }
4282
4283 /**
4284 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4285 * {@link NetworkRequest}.
4286 *
4287 * This function behaves identically to the version that takes a NetworkCallback, but instead
4288 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4289 * the request may outlive the calling application and get called back when a suitable
4290 * network is found.
4291 * <p>
4292 * The operation is an Intent broadcast that goes to a broadcast receiver that
4293 * you registered with {@link Context#registerReceiver} or through the
4294 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4295 * <p>
4296 * The operation Intent is delivered with two extras, a {@link Network} typed
4297 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4298 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4299 * the original requests parameters.
4300 * <p>
4301 * If there is already a request for this Intent registered (with the equality of
4302 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4303 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4304 * <p>
4305 * The request may be released normally by calling
4306 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4307 *
4308 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4309 * number of outstanding requests to 100 per app (identified by their UID), shared with
4310 * all variants of this method, of {@link #requestNetwork} as well as
4311 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4312 * Requesting a network with this method will count toward this limit. If this limit is
4313 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4314 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4315 * or {@link #releaseNetworkRequest(PendingIntent)}.
4316 *
4317 * @param request {@link NetworkRequest} describing this request.
4318 * @param operation Action to perform when the network is available (corresponds
4319 * to the {@link NetworkCallback#onAvailable} call. Typically
4320 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4321 * @throws RuntimeException if the app already has too many callbacks registered.
4322 */
4323 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4324 public void registerNetworkCallback(@NonNull NetworkRequest request,
4325 @NonNull PendingIntent operation) {
4326 printStackTrace();
4327 checkPendingIntentNotNull(operation);
4328 try {
4329 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004330 request.networkCapabilities, operation, mContext.getOpPackageName(),
4331 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004332 } catch (RemoteException e) {
4333 throw e.rethrowFromSystemServer();
4334 } catch (ServiceSpecificException e) {
4335 throw convertServiceException(e);
4336 }
4337 }
4338
4339 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004340 * Registers to receive notifications about changes in the application's default network. This
4341 * may be a physical network or a virtual network, such as a VPN that applies to the
4342 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004343 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4344 *
4345 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4346 * number of outstanding requests to 100 per app (identified by their UID), shared with
4347 * all variants of this method, of {@link #requestNetwork} as well as
4348 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4349 * Requesting a network with this method will count toward this limit. If this limit is
4350 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4351 * make sure to unregister the callbacks with
4352 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4353 *
4354 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004355 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004356 * The callback is invoked on the default internal Handler.
4357 * @throws RuntimeException if the app already has too many callbacks registered.
4358 */
4359 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4360 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4361 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4362 }
4363
4364 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004365 * Registers to receive notifications about changes in the application's default network. This
4366 * may be a physical network or a virtual network, such as a VPN that applies to the
4367 * application. The callbacks will continue to be called until either the application exits or
4368 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4369 *
4370 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4371 * number of outstanding requests to 100 per app (identified by their UID), shared with
4372 * all variants of this method, of {@link #requestNetwork} as well as
4373 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4374 * Requesting a network with this method will count toward this limit. If this limit is
4375 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4376 * make sure to unregister the callbacks with
4377 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4378 *
4379 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4380 * application's default network changes.
4381 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4382 * @throws RuntimeException if the app already has too many callbacks registered.
4383 */
4384 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4385 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4386 @NonNull Handler handler) {
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004387 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4388 }
4389
4390 /**
4391 * Registers to receive notifications about changes in the default network for the specified
4392 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4393 * UID. The callbacks will continue to be called until either the application exits or
4394 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4395 *
4396 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4397 * number of outstanding requests to 100 per app (identified by their UID), shared with
4398 * all variants of this method, of {@link #requestNetwork} as well as
4399 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4400 * Requesting a network with this method will count toward this limit. If this limit is
4401 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4402 * make sure to unregister the callbacks with
4403 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4404 *
4405 * @param uid the UID for which to track default network changes.
4406 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4407 * UID's default network changes.
4408 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4409 * @throws RuntimeException if the app already has too many callbacks registered.
4410 * @hide
4411 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004412 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004413 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4414 @RequiresPermission(anyOf = {
4415 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4416 android.Manifest.permission.NETWORK_SETTINGS})
4417 public void registerDefaultNetworkCallbackAsUid(int uid,
4418 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004419 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004420 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004421 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4422 }
4423
4424 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004425 * Registers to receive notifications about changes in the system default network. The callbacks
4426 * will continue to be called until either the application exits or
4427 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4428 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004429 * This method should not be used to determine networking state seen by applications, because in
4430 * many cases, most or even all application traffic may not use the default network directly,
4431 * and traffic from different applications may go on different networks by default. As an
4432 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4433 * and not onto the system default network. Applications or system components desiring to do
4434 * determine network state as seen by applications should use other methods such as
4435 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4436 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004437 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4438 * number of outstanding requests to 100 per app (identified by their UID), shared with
4439 * all variants of this method, of {@link #requestNetwork} as well as
4440 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4441 * Requesting a network with this method will count toward this limit. If this limit is
4442 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4443 * make sure to unregister the callbacks with
4444 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4445 *
4446 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4447 * system default network changes.
4448 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4449 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004450 *
4451 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004452 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004453 @SystemApi(client = MODULE_LIBRARIES)
4454 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4455 @RequiresPermission(anyOf = {
4456 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4457 android.Manifest.permission.NETWORK_SETTINGS})
4458 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004459 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004460 CallbackHandler cbHandler = new CallbackHandler(handler);
4461 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004462 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004463 }
4464
4465 /**
junyulaibd123062021-03-15 11:48:48 +08004466 * Registers to receive notifications about the best matching network which satisfy the given
4467 * {@link NetworkRequest}. The callbacks will continue to be called until
4468 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4469 * called.
4470 *
4471 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4472 * number of outstanding requests to 100 per app (identified by their UID), shared with
4473 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4474 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4475 * Requesting a network with this method will count toward this limit. If this limit is
4476 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4477 * make sure to unregister the callbacks with
4478 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4479 *
4480 *
4481 * @param request {@link NetworkRequest} describing this request.
4482 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4483 * networks change state.
4484 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4485 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004486 */
junyulai5a5c99b2021-03-05 15:51:17 +08004487 @SuppressLint("ExecutorRegistration")
4488 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4489 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4490 final NetworkCapabilities nc = request.networkCapabilities;
4491 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004492 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004493 }
4494
4495 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004496 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4497 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4498 * network connection for updated bandwidth information. The caller will be notified via
4499 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4500 * method assumes that the caller has previously called
4501 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4502 * changes.
4503 *
4504 * @param network {@link Network} specifying which network you're interested.
4505 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4506 */
4507 public boolean requestBandwidthUpdate(@NonNull Network network) {
4508 try {
4509 return mService.requestBandwidthUpdate(network);
4510 } catch (RemoteException e) {
4511 throw e.rethrowFromSystemServer();
4512 }
4513 }
4514
4515 /**
4516 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4517 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4518 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4519 * If the given {@code NetworkCallback} had previously been used with
4520 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4521 * will be disconnected.
4522 *
4523 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4524 * triggering it as soon as this call returns.
4525 *
4526 * @param networkCallback The {@link NetworkCallback} used when making the request.
4527 */
4528 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4529 printStackTrace();
4530 checkCallbackNotNull(networkCallback);
4531 final List<NetworkRequest> reqs = new ArrayList<>();
4532 // Find all requests associated to this callback and stop callback triggers immediately.
4533 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4534 synchronized (sCallbacks) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004535 if (networkCallback.networkRequest == null) {
4536 throw new IllegalArgumentException("NetworkCallback was not registered");
4537 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004538 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4539 Log.d(TAG, "NetworkCallback was already unregistered");
4540 return;
4541 }
4542 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4543 if (e.getValue() == networkCallback) {
4544 reqs.add(e.getKey());
4545 }
4546 }
4547 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4548 for (NetworkRequest r : reqs) {
4549 try {
4550 mService.releaseNetworkRequest(r);
4551 } catch (RemoteException e) {
4552 throw e.rethrowFromSystemServer();
4553 }
4554 // Only remove mapping if rpc was successful.
4555 sCallbacks.remove(r);
4556 }
4557 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4558 }
4559 }
4560
4561 /**
4562 * Unregisters a callback previously registered via
4563 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4564 *
4565 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4566 * PendingIntent passed to
4567 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4568 * Cannot be null.
4569 */
4570 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4571 releaseNetworkRequest(operation);
4572 }
4573
4574 /**
4575 * Informs the system whether it should switch to {@code network} regardless of whether it is
4576 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4577 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4578 * the system default network regardless of any other network that's currently connected. If
4579 * {@code always} is true, then the choice is remembered, so that the next time the user
4580 * connects to this network, the system will switch to it.
4581 *
4582 * @param network The network to accept.
4583 * @param accept Whether to accept the network even if unvalidated.
4584 * @param always Whether to remember this choice in the future.
4585 *
4586 * @hide
4587 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004588 @SystemApi(client = MODULE_LIBRARIES)
4589 @RequiresPermission(anyOf = {
4590 android.Manifest.permission.NETWORK_SETTINGS,
4591 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4592 android.Manifest.permission.NETWORK_STACK,
4593 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4594 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004595 try {
4596 mService.setAcceptUnvalidated(network, accept, always);
4597 } catch (RemoteException e) {
4598 throw e.rethrowFromSystemServer();
4599 }
4600 }
4601
4602 /**
4603 * Informs the system whether it should consider the network as validated even if it only has
4604 * partial connectivity. If {@code accept} is true, then the network will be considered as
4605 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4606 * is remembered, so that the next time the user connects to this network, the system will
4607 * switch to it.
4608 *
4609 * @param network The network to accept.
4610 * @param accept Whether to consider the network as validated even if it has partial
4611 * connectivity.
4612 * @param always Whether to remember this choice in the future.
4613 *
4614 * @hide
4615 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004616 @SystemApi(client = MODULE_LIBRARIES)
4617 @RequiresPermission(anyOf = {
4618 android.Manifest.permission.NETWORK_SETTINGS,
4619 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4620 android.Manifest.permission.NETWORK_STACK,
4621 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4622 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4623 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004624 try {
4625 mService.setAcceptPartialConnectivity(network, accept, always);
4626 } catch (RemoteException e) {
4627 throw e.rethrowFromSystemServer();
4628 }
4629 }
4630
4631 /**
4632 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4633 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4634 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4635 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4636 *
4637 * @param network The network to accept.
4638 *
4639 * @hide
4640 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004641 @SystemApi(client = MODULE_LIBRARIES)
4642 @RequiresPermission(anyOf = {
4643 android.Manifest.permission.NETWORK_SETTINGS,
4644 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4645 android.Manifest.permission.NETWORK_STACK,
4646 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4647 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004648 try {
4649 mService.setAvoidUnvalidated(network);
4650 } catch (RemoteException e) {
4651 throw e.rethrowFromSystemServer();
4652 }
4653 }
4654
4655 /**
4656 * Requests that the system open the captive portal app on the specified network.
4657 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004658 * <p>This is to be used on networks where a captive portal was detected, as per
4659 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4660 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004661 * @param network The network to log into.
4662 *
4663 * @hide
4664 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004665 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4666 @RequiresPermission(anyOf = {
4667 android.Manifest.permission.NETWORK_SETTINGS,
4668 android.Manifest.permission.NETWORK_STACK,
4669 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4670 })
4671 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004672 try {
4673 mService.startCaptivePortalApp(network);
4674 } catch (RemoteException e) {
4675 throw e.rethrowFromSystemServer();
4676 }
4677 }
4678
4679 /**
4680 * Requests that the system open the captive portal app with the specified extras.
4681 *
4682 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4683 * corresponding permission.
4684 * @param network Network on which the captive portal was detected.
4685 * @param appExtras Extras to include in the app start intent.
4686 * @hide
4687 */
4688 @SystemApi
4689 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4690 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4691 try {
4692 mService.startCaptivePortalAppInternal(network, appExtras);
4693 } catch (RemoteException e) {
4694 throw e.rethrowFromSystemServer();
4695 }
4696 }
4697
4698 /**
4699 * Determine whether the device is configured to avoid bad wifi.
4700 * @hide
4701 */
4702 @SystemApi
4703 @RequiresPermission(anyOf = {
4704 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4705 android.Manifest.permission.NETWORK_STACK})
4706 public boolean shouldAvoidBadWifi() {
4707 try {
4708 return mService.shouldAvoidBadWifi();
4709 } catch (RemoteException e) {
4710 throw e.rethrowFromSystemServer();
4711 }
4712 }
4713
4714 /**
4715 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4716 * time-sensitive user-facing operations when the system default network is temporarily
4717 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4718 * this method), and the operation should be infrequent to ensure that data usage is limited.
4719 *
4720 * An example of such an operation might be a time-sensitive foreground activity, such as a
4721 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4722 */
4723 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4724
4725 /**
4726 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4727 * a backup channel for traffic that is primarily going over another network.
4728 *
4729 * An example might be maintaining backup connections to peers or servers for the purpose of
4730 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4731 * on backup paths should be negligible compared to the traffic on the main path.
4732 */
4733 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4734
4735 /**
4736 * It is acceptable to use metered data to improve network latency and performance.
4737 */
4738 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4739
4740 /**
4741 * Return value to use for unmetered networks. On such networks we currently set all the flags
4742 * to true.
4743 * @hide
4744 */
4745 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4746 MULTIPATH_PREFERENCE_HANDOVER |
4747 MULTIPATH_PREFERENCE_RELIABILITY |
4748 MULTIPATH_PREFERENCE_PERFORMANCE;
4749
4750 /** @hide */
4751 @Retention(RetentionPolicy.SOURCE)
4752 @IntDef(flag = true, value = {
4753 MULTIPATH_PREFERENCE_HANDOVER,
4754 MULTIPATH_PREFERENCE_RELIABILITY,
4755 MULTIPATH_PREFERENCE_PERFORMANCE,
4756 })
4757 public @interface MultipathPreference {
4758 }
4759
4760 /**
4761 * Provides a hint to the calling application on whether it is desirable to use the
4762 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4763 * for multipath data transfer on this network when it is not the system default network.
4764 * Applications desiring to use multipath network protocols should call this method before
4765 * each such operation.
4766 *
4767 * @param network The network on which the application desires to use multipath data.
4768 * If {@code null}, this method will return the a preference that will generally
4769 * apply to metered networks.
4770 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4771 */
4772 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4773 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
4774 try {
4775 return mService.getMultipathPreference(network);
4776 } catch (RemoteException e) {
4777 throw e.rethrowFromSystemServer();
4778 }
4779 }
4780
4781 /**
4782 * Resets all connectivity manager settings back to factory defaults.
4783 * @hide
4784 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004785 @SystemApi(client = MODULE_LIBRARIES)
4786 @RequiresPermission(anyOf = {
4787 android.Manifest.permission.NETWORK_SETTINGS,
4788 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004789 public void factoryReset() {
4790 try {
4791 mService.factoryReset();
4792 mTetheringManager.stopAllTethering();
4793 } catch (RemoteException e) {
4794 throw e.rethrowFromSystemServer();
4795 }
4796 }
4797
4798 /**
4799 * Binds the current process to {@code network}. All Sockets created in the future
4800 * (and not explicitly bound via a bound SocketFactory from
4801 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4802 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4803 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4804 * work and all host name resolutions will fail. This is by design so an application doesn't
4805 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4806 * To clear binding pass {@code null} for {@code network}. Using individually bound
4807 * Sockets created by Network.getSocketFactory().createSocket() and
4808 * performing network-specific host name resolutions via
4809 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4810 * {@code bindProcessToNetwork}.
4811 *
4812 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4813 * the current binding.
4814 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4815 */
4816 public boolean bindProcessToNetwork(@Nullable Network network) {
4817 // Forcing callers to call through non-static function ensures ConnectivityManager
4818 // instantiated.
4819 return setProcessDefaultNetwork(network);
4820 }
4821
4822 /**
4823 * Binds the current process to {@code network}. All Sockets created in the future
4824 * (and not explicitly bound via a bound SocketFactory from
4825 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4826 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4827 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4828 * work and all host name resolutions will fail. This is by design so an application doesn't
4829 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4830 * To clear binding pass {@code null} for {@code network}. Using individually bound
4831 * Sockets created by Network.getSocketFactory().createSocket() and
4832 * performing network-specific host name resolutions via
4833 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4834 * {@code setProcessDefaultNetwork}.
4835 *
4836 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4837 * the current binding.
4838 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4839 * @deprecated This function can throw {@link IllegalStateException}. Use
4840 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4841 * is a direct replacement.
4842 */
4843 @Deprecated
4844 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
4845 int netId = (network == null) ? NETID_UNSET : network.netId;
4846 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4847
4848 if (netId != NETID_UNSET) {
4849 netId = network.getNetIdForResolv();
4850 }
4851
4852 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4853 return false;
4854 }
4855
4856 if (!isSameNetId) {
4857 // Set HTTP proxy system properties to match network.
4858 // TODO: Deprecate this static method and replace it with a non-static version.
4859 try {
Remi NGUYEN VAN345c2df2021-02-03 10:18:20 +09004860 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004861 } catch (SecurityException e) {
4862 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4863 Log.e(TAG, "Can't set proxy properties", e);
4864 }
4865 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN342dddd2021-03-18 23:27:19 +09004866 InetAddressCompat.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004867 // Must flush socket pool as idle sockets will be bound to previous network and may
4868 // cause subsequent fetches to be performed on old network.
4869 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
4870 }
4871
4872 return true;
4873 }
4874
4875 /**
4876 * Returns the {@link Network} currently bound to this process via
4877 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4878 *
4879 * @return {@code Network} to which this process is bound, or {@code null}.
4880 */
4881 @Nullable
4882 public Network getBoundNetworkForProcess() {
4883 // Forcing callers to call thru non-static function ensures ConnectivityManager
4884 // instantiated.
4885 return getProcessDefaultNetwork();
4886 }
4887
4888 /**
4889 * Returns the {@link Network} currently bound to this process via
4890 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4891 *
4892 * @return {@code Network} to which this process is bound, or {@code null}.
4893 * @deprecated Using this function can lead to other functions throwing
4894 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4895 * {@code getBoundNetworkForProcess} is a direct replacement.
4896 */
4897 @Deprecated
4898 @Nullable
4899 public static Network getProcessDefaultNetwork() {
4900 int netId = NetworkUtils.getBoundNetworkForProcess();
4901 if (netId == NETID_UNSET) return null;
4902 return new Network(netId);
4903 }
4904
4905 private void unsupportedStartingFrom(int version) {
4906 if (Process.myUid() == Process.SYSTEM_UID) {
4907 // The getApplicationInfo() call we make below is not supported in system context. Let
4908 // the call through here, and rely on the fact that ConnectivityService will refuse to
4909 // allow the system to use these APIs anyway.
4910 return;
4911 }
4912
4913 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4914 throw new UnsupportedOperationException(
4915 "This method is not supported in target SDK version " + version + " and above");
4916 }
4917 }
4918
4919 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4920 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
4921 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
4922 // remove these exemptions. Note that this check is not secure, and apps can still access these
4923 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4924 // so is unsupported and may break in the future. http://b/22728205
4925 private void checkLegacyRoutingApiAccess() {
4926 unsupportedStartingFrom(VERSION_CODES.M);
4927 }
4928
4929 /**
4930 * Binds host resolutions performed by this process to {@code network}.
4931 * {@link #bindProcessToNetwork} takes precedence over this setting.
4932 *
4933 * @param network The {@link Network} to bind host resolutions from the current process to, or
4934 * {@code null} to clear the current binding.
4935 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4936 * @hide
4937 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4938 */
4939 @Deprecated
4940 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4941 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
4942 return NetworkUtils.bindProcessToNetworkForHostResolution(
4943 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
4944 }
4945
4946 /**
4947 * Device is not restricting metered network activity while application is running on
4948 * background.
4949 */
4950 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4951
4952 /**
4953 * Device is restricting metered network activity while application is running on background,
4954 * but application is allowed to bypass it.
4955 * <p>
4956 * In this state, application should take action to mitigate metered network access.
4957 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4958 */
4959 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4960
4961 /**
4962 * Device is restricting metered network activity while application is running on background.
4963 * <p>
4964 * In this state, application should not try to use the network while running on background,
4965 * because it would be denied.
4966 */
4967 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4968
4969 /**
4970 * A change in the background metered network activity restriction has occurred.
4971 * <p>
4972 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4973 * applies to them.
4974 * <p>
4975 * This is only sent to registered receivers, not manifest receivers.
4976 */
4977 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4978 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4979 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4980
4981 /** @hide */
4982 @Retention(RetentionPolicy.SOURCE)
4983 @IntDef(flag = false, value = {
4984 RESTRICT_BACKGROUND_STATUS_DISABLED,
4985 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4986 RESTRICT_BACKGROUND_STATUS_ENABLED,
4987 })
4988 public @interface RestrictBackgroundStatus {
4989 }
4990
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004991 /**
4992 * Determines if the calling application is subject to metered network restrictions while
4993 * running on background.
4994 *
4995 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4996 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4997 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
4998 */
4999 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5000 try {
Remi NGUYEN VANe62e7ff2021-03-18 14:23:12 +09005001 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005002 } catch (RemoteException e) {
5003 throw e.rethrowFromSystemServer();
5004 }
5005 }
5006
5007 /**
5008 * The network watchlist is a list of domains and IP addresses that are associated with
5009 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5010 * currently used by the system for validation purposes.
5011 *
5012 * @return Hash of network watchlist config file. Null if config does not exist.
5013 */
5014 @Nullable
5015 public byte[] getNetworkWatchlistConfigHash() {
5016 try {
5017 return mService.getNetworkWatchlistConfigHash();
5018 } catch (RemoteException e) {
5019 Log.e(TAG, "Unable to get watchlist config hash");
5020 throw e.rethrowFromSystemServer();
5021 }
5022 }
5023
5024 /**
5025 * Returns the {@code uid} of the owner of a network connection.
5026 *
5027 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5028 * IPPROTO_UDP} currently supported.
5029 * @param local The local {@link InetSocketAddress} of a connection.
5030 * @param remote The remote {@link InetSocketAddress} of a connection.
5031 * @return {@code uid} if the connection is found and the app has permission to observe it
5032 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5033 * android.os.Process#INVALID_UID} if the connection is not found.
5034 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5035 * user.
5036 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5037 */
5038 public int getConnectionOwnerUid(
5039 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5040 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5041 try {
5042 return mService.getConnectionOwnerUid(connectionInfo);
5043 } catch (RemoteException e) {
5044 throw e.rethrowFromSystemServer();
5045 }
5046 }
5047
5048 private void printStackTrace() {
5049 if (DEBUG) {
5050 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5051 final StringBuffer sb = new StringBuffer();
5052 for (int i = 3; i < callStack.length; i++) {
5053 final String stackTrace = callStack[i].toString();
5054 if (stackTrace == null || stackTrace.contains("android.os")) {
5055 break;
5056 }
5057 sb.append(" [").append(stackTrace).append("]");
5058 }
5059 Log.d(TAG, "StackLog:" + sb.toString());
5060 }
5061 }
5062
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005063 /** @hide */
5064 public TestNetworkManager startOrGetTestNetworkManager() {
5065 final IBinder tnBinder;
5066 try {
5067 tnBinder = mService.startOrGetTestNetworkService();
5068 } catch (RemoteException e) {
5069 throw e.rethrowFromSystemServer();
5070 }
5071
5072 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5073 }
5074
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005075 /** @hide */
5076 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5077 return new ConnectivityDiagnosticsManager(mContext, mService);
5078 }
5079
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005080 /**
5081 * Simulates a Data Stall for the specified Network.
5082 *
5083 * <p>This method should only be used for tests.
5084 *
5085 * <p>The caller must be the owner of the specified Network.
5086 *
5087 * @param detectionMethod The detection method used to identify the Data Stall.
5088 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
5089 * @param network The Network for which a Data Stall is being simluated.
5090 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5091 * @throws SecurityException if the caller is not the owner of the given network.
5092 * @hide
5093 */
5094 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5095 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5096 android.Manifest.permission.NETWORK_STACK})
5097 public void simulateDataStall(int detectionMethod, long timestampMillis,
5098 @NonNull Network network, @NonNull PersistableBundle extras) {
5099 try {
5100 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5101 } catch (RemoteException e) {
5102 e.rethrowFromSystemServer();
5103 }
5104 }
5105
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005106 @NonNull
5107 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5108
5109 /**
5110 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5111 * receive available QoS events related to the {@link Network} and local ip + port
5112 * specified within socketInfo.
5113 * <p/>
5114 * The same {@link QosCallback} must be unregistered before being registered a second time,
5115 * otherwise {@link QosCallbackRegistrationException} is thrown.
5116 * <p/>
5117 * This API does not, in itself, require any permission if called with a network that is not
5118 * restricted. However, the underlying implementation currently only supports the IMS network,
5119 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5120 * useful, because they'd never be called back on networks that they would have access to.
5121 *
5122 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5123 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5124 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5125 * @throws RuntimeException if the app already has too many callbacks registered.
5126 *
5127 * Exceptions after the time of registration is passed through
5128 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5129 *
5130 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005131 * @param executor The executor on which the callback will be invoked. The provided
5132 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005133 * callbacks cannot be guaranteed.onQosCallbackRegistered
5134 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005135 *
5136 * @hide
5137 */
5138 @SystemApi
5139 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005140 @CallbackExecutor @NonNull final Executor executor,
5141 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005142 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005143 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005144 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005145
5146 try {
5147 synchronized (mQosCallbackConnections) {
5148 if (getQosCallbackConnection(callback) == null) {
5149 final QosCallbackConnection connection =
5150 new QosCallbackConnection(this, callback, executor);
5151 mQosCallbackConnections.add(connection);
5152 mService.registerQosSocketCallback(socketInfo, connection);
5153 } else {
5154 Log.e(TAG, "registerQosCallback: Callback already registered");
5155 throw new QosCallbackRegistrationException();
5156 }
5157 }
5158 } catch (final RemoteException e) {
5159 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5160
5161 // The same unregister method method is called for consistency even though nothing
5162 // will be sent to the ConnectivityService since the callback was never successfully
5163 // registered.
5164 unregisterQosCallback(callback);
5165 e.rethrowFromSystemServer();
5166 } catch (final ServiceSpecificException e) {
5167 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5168 unregisterQosCallback(callback);
5169 throw convertServiceException(e);
5170 }
5171 }
5172
5173 /**
5174 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5175 * events once unregistered and can be registered a second time.
5176 * <p/>
5177 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5178 *
5179 * @param callback the callback being unregistered
5180 *
5181 * @hide
5182 */
5183 @SystemApi
5184 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5185 Objects.requireNonNull(callback, "The callback must be non-null");
5186 try {
5187 synchronized (mQosCallbackConnections) {
5188 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5189 if (connection != null) {
5190 connection.stopReceivingMessages();
5191 mService.unregisterQosCallback(connection);
5192 mQosCallbackConnections.remove(connection);
5193 } else {
5194 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5195 }
5196 }
5197 } catch (final RemoteException e) {
5198 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5199 e.rethrowFromSystemServer();
5200 }
5201 }
5202
5203 /**
5204 * Gets the connection related to the callback.
5205 *
5206 * @param callback the callback to look up
5207 * @return the related connection
5208 */
5209 @Nullable
5210 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5211 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5212 // Checking by reference here is intentional
5213 if (connection.getCallback() == callback) {
5214 return connection;
5215 }
5216 }
5217 return null;
5218 }
5219
5220 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005221 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005222 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5223 * be used to request that the system provide a network without causing the network to be
5224 * in the foreground.
5225 *
5226 * <p>This method will attempt to find the best network that matches the passed
5227 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5228 * criteria. The platform will evaluate which network is the best at its own discretion.
5229 * Throughput, latency, cost per byte, policy, user preference and other considerations
5230 * may be factored in the decision of what is considered the best network.
5231 *
5232 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5233 * matching this request, while always attempting to match the request to a better network if
5234 * possible. If a better match is found, the platform will switch this request to the now-best
5235 * network and inform the app of the newly best network by invoking
5236 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5237 * will not try to maintain any other network than the best one currently matching the request:
5238 * a network not matching any network request may be disconnected at any time.
5239 *
5240 * <p>For example, an application could use this method to obtain a connected cellular network
5241 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5242 * radio to consume additional power. Or, an application could inform the system that it wants
5243 * a network supporting sending MMSes and have the system let it know about the currently best
5244 * MMS-supporting network through the provided {@link NetworkCallback}.
5245 *
5246 * <p>The status of the request can be followed by listening to the various callbacks described
5247 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5248 * used to direct traffic to the network (although accessing some networks may be subject to
5249 * holding specific permissions). Callers will learn about the specific characteristics of the
5250 * network through
5251 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5252 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5253 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5254 * matching the request at any given time; therefore when a better network matching the request
5255 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5256 * with the new network after which no further updates are given about the previously-best
5257 * network, unless it becomes the best again at some later time. All callbacks are invoked
5258 * in order on the same thread, which by default is a thread created by the framework running
5259 * in the app.
5260 *
5261 * <p>This{@link NetworkRequest} will live until released via
5262 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5263 * which point the system may let go of the network at any time.
5264 *
5265 * <p>It is presently unsupported to request a network with mutable
5266 * {@link NetworkCapabilities} such as
5267 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5268 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5269 * as these {@code NetworkCapabilities} represent states that a particular
5270 * network may never attain, and whether a network will attain these states
5271 * is unknown prior to bringing up the network so the framework does not
5272 * know how to go about satisfying a request with these capabilities.
5273 *
5274 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5275 * number of outstanding requests to 100 per app (identified by their UID), shared with
5276 * all variants of this method, of {@link #registerNetworkCallback} as well as
5277 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5278 * Requesting a network with this method will count toward this limit. If this limit is
5279 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5280 * make sure to unregister the callbacks with
5281 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5282 *
5283 * @param request {@link NetworkRequest} describing this request.
5284 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5285 * If null, the callback is invoked on the default internal Handler.
5286 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5287 * the callback must not be shared - it uniquely specifies this request.
5288 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5289 * @throws SecurityException if missing the appropriate permissions.
5290 * @throws RuntimeException if the app already has too many callbacks registered.
5291 *
5292 * @hide
5293 */
5294 @SystemApi(client = MODULE_LIBRARIES)
5295 @SuppressLint("ExecutorRegistration")
5296 @RequiresPermission(anyOf = {
5297 android.Manifest.permission.NETWORK_SETTINGS,
5298 android.Manifest.permission.NETWORK_STACK,
5299 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5300 })
5301 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaidbb70462021-03-09 20:49:48 +08005302 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005303 final NetworkCapabilities nc = request.networkCapabilities;
5304 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005305 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005306 }
James Mattis12aeab82021-01-10 14:24:24 -08005307
5308 /**
James Mattis12aeab82021-01-10 14:24:24 -08005309 * Used by automotive devices to set the network preferences used to direct traffic at an
5310 * application level as per the given OemNetworkPreferences. An example use-case would be an
5311 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5312 * vehicle via a particular network.
5313 *
5314 * Calling this will overwrite the existing preference.
5315 *
5316 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5317 * @param executor the executor on which listener will be invoked.
5318 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5319 * communicate completion of setOemNetworkPreference(). This will only be
5320 * called once upon successful completion of setOemNetworkPreference().
5321 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5322 * @throws SecurityException if missing the appropriate permissions.
5323 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005324 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005325 */
James Mattis6e2d7022021-01-26 16:23:52 -08005326 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005327 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005328 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005329 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005330 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005331 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5332 if (null != listener) {
5333 Objects.requireNonNull(executor, "Executor must be non-null");
5334 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005335 final IOnCompleteListener listenerInternal = listener == null ? null :
5336 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005337 @Override
5338 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005339 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005340 }
5341 };
5342
5343 try {
5344 mService.setOemNetworkPreference(preference, listenerInternal);
5345 } catch (RemoteException e) {
5346 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5347 throw e.rethrowFromSystemServer();
5348 }
5349 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005350
Chalard Jeanad565e22021-02-25 17:23:40 +09005351 /**
5352 * Request that a user profile is put by default on a network matching a given preference.
5353 *
5354 * See the documentation for the individual preferences for a description of the supported
5355 * behaviors.
5356 *
5357 * @param profile the profile concerned.
5358 * @param preference the preference for this profile.
5359 * @param executor an executor to execute the listener on. Optional if listener is null.
5360 * @param listener an optional listener to listen for completion of the operation.
5361 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5362 * @throws SecurityException if missing the appropriate permissions.
5363 * @hide
5364 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005365 // This function is for establishing per-profile default networking and can only be called by
5366 // the device policy manager, running as the system server. It would make no sense to call it
5367 // on a context for a user because it does not establish a setting on behalf of a user, rather
5368 // it establishes a setting for a user on behalf of the DPM.
5369 @SuppressLint({"UserHandle"})
5370 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005371 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5372 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5373 @ProfileNetworkPreference final int preference,
5374 @Nullable @CallbackExecutor final Executor executor,
5375 @Nullable final Runnable listener) {
5376 if (null != listener) {
5377 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5378 }
5379 final IOnCompleteListener proxy;
5380 if (null == listener) {
5381 proxy = null;
5382 } else {
5383 proxy = new IOnCompleteListener.Stub() {
5384 @Override
5385 public void onComplete() {
5386 executor.execute(listener::run);
5387 }
5388 };
5389 }
5390 try {
5391 mService.setProfileNetworkPreference(profile, preference, proxy);
5392 } catch (RemoteException e) {
5393 throw e.rethrowFromSystemServer();
5394 }
5395 }
5396
lucaslin5cdbcfb2021-03-12 00:46:33 +08005397 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005398 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005399 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005400 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005401
5402 /**
5403 * Get the network ID range reserved for IPSec tunnel interfaces.
5404 *
5405 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5406 * @hide
5407 */
5408 @SystemApi(client = MODULE_LIBRARIES)
5409 @NonNull
5410 public static Range<Integer> getIpSecNetIdRange() {
5411 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5412 }
lucaslin889dcda2021-03-12 17:56:09 +08005413
5414 /**
5415 * Get private DNS mode from settings.
5416 *
lucaslindebfe602021-03-17 14:53:35 +08005417 * @param context The Context to query the private DNS mode from settings.
lucaslin889dcda2021-03-12 17:56:09 +08005418 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5419 *
5420 * @hide
5421 */
5422 @SystemApi(client = MODULE_LIBRARIES)
5423 @NonNull
5424 @PrivateDnsMode
lucasline2cd02d2021-03-16 17:11:14 +08005425 public static String getPrivateDnsMode(@NonNull Context context) {
5426 final ContentResolver cr = context.getContentResolver();
lucaslin889dcda2021-03-12 17:56:09 +08005427 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5428 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5429 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5430 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5431 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5432 return mode;
5433 }
paulhu6865eb62021-03-25 12:36:56 +08005434
5435 /**
5436 * Set private DNS mode to settings.
5437 *
5438 * @param context The {@link Context} to set the private DNS mode.
5439 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5440 *
5441 * @hide
5442 */
5443 @SystemApi(client = MODULE_LIBRARIES)
5444 public static void setPrivateDnsMode(@NonNull Context context,
5445 @NonNull @PrivateDnsMode String mode) {
5446 if (!(mode == PRIVATE_DNS_MODE_OFF
5447 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5448 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5449 throw new IllegalArgumentException("Invalid private dns mode");
5450 }
5451 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5452 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005453}