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