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