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