blob: 5769b92642e67bf29574b1485eda9480a2b34c65 [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;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080019import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
21import static android.net.NetworkRequest.Type.LISTEN;
junyulai7664f622021-03-12 20:05:08 +080022import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090023import static android.net.NetworkRequest.Type.REQUEST;
24import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colittia77d05e2021-01-29 20:14:04 +090025import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090026import static android.net.QosCallback.QosCallbackRegistrationException;
27
28import android.annotation.CallbackExecutor;
29import android.annotation.IntDef;
30import android.annotation.NonNull;
31import android.annotation.Nullable;
32import android.annotation.RequiresPermission;
33import android.annotation.SdkConstant;
34import android.annotation.SdkConstant.SdkConstantType;
35import android.annotation.SuppressLint;
36import android.annotation.SystemApi;
37import android.annotation.SystemService;
38import android.app.PendingIntent;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090039import android.app.admin.DevicePolicyManager;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090040import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090041import android.content.ComponentName;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090042import android.content.Context;
43import android.content.Intent;
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +090044import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090045import android.net.IpSecManager.UdpEncapsulationSocket;
46import android.net.SocketKeepalive.Callback;
47import android.net.TetheringManager.StartTetheringCallback;
48import android.net.TetheringManager.TetheringEventCallback;
49import android.net.TetheringManager.TetheringRequest;
50import 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 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100880 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
881 * result in its network access being blocked.
882 *
883 * @hide
884 */
885 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
886 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
887
888 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000889 * Flag to indicate that an app is subject to Data saver 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_DATA_SAVER = 1 << 16;
896
897 /**
898 * Flag to indicate that an app is subject to user 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_USER_RESTRICTED = 1 << 17;
905
906 /**
907 * Flag to indicate that an app is subject to Device admin restrictions that would
908 * result in its metered network access being blocked.
909 *
910 * @hide
911 */
912 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
913 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
914
915 /**
916 * @hide
917 */
918 @Retention(RetentionPolicy.SOURCE)
919 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
920 BLOCKED_REASON_NONE,
921 BLOCKED_REASON_BATTERY_SAVER,
922 BLOCKED_REASON_DOZE,
923 BLOCKED_REASON_APP_STANDBY,
924 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900925 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100926 BLOCKED_REASON_LOW_POWER_STANDBY,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000927 BLOCKED_METERED_REASON_DATA_SAVER,
928 BLOCKED_METERED_REASON_USER_RESTRICTED,
929 BLOCKED_METERED_REASON_ADMIN_DISABLED,
930 })
931 public @interface BlockedReason {}
932
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900933 /**
934 * Set of blocked reasons that are only applicable on metered networks.
935 *
936 * @hide
937 */
938 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
939 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
940
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900941 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
942 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900943
Robert Horvathd945bf02022-01-27 19:55:16 +0100944 // LINT.IfChange(firewall_chain)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900945 /**
markchiene1561fa2021-12-09 22:00:56 +0800946 * Firewall chain for device idle (doze mode).
947 * Allowlist of apps that have network access in device idle.
948 * @hide
949 */
950 @SystemApi(client = MODULE_LIBRARIES)
951 public static final int FIREWALL_CHAIN_DOZABLE = 1;
952
953 /**
954 * Firewall chain used for app standby.
955 * Denylist of apps that do not have network access.
956 * @hide
957 */
958 @SystemApi(client = MODULE_LIBRARIES)
959 public static final int FIREWALL_CHAIN_STANDBY = 2;
960
961 /**
962 * Firewall chain used for battery saver.
963 * Allowlist of apps that have network access when battery saver is on.
964 * @hide
965 */
966 @SystemApi(client = MODULE_LIBRARIES)
967 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
968
969 /**
970 * Firewall chain used for restricted networking mode.
971 * Allowlist of apps that have access in restricted networking mode.
972 * @hide
973 */
974 @SystemApi(client = MODULE_LIBRARIES)
975 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
976
Robert Horvath34cba142022-01-27 19:52:43 +0100977 /**
978 * Firewall chain used for low power standby.
979 * Allowlist of apps that have access in low power standby.
980 * @hide
981 */
982 @SystemApi(client = MODULE_LIBRARIES)
983 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
984
Motomu Utsumib08654c2022-05-11 05:56:26 +0000985 /**
986 * Firewall chain used for lockdown VPN.
987 * Denylist of apps that cannot receive incoming packets except on loopback because they are
988 * subject to an always-on VPN which is not currently connected.
989 *
990 * @see #BLOCKED_REASON_LOCKDOWN_VPN
991 * @hide
992 */
993 public static final int FIREWALL_CHAIN_LOCKDOWN_VPN = 6;
994
Motomu Utsumid9801492022-06-01 13:57:27 +0000995 /**
996 * Firewall chain used for OEM-specific application restrictions.
997 * Denylist of apps that will not have network access due to OEM-specific restrictions.
998 * @hide
999 */
1000 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1001
1002 /**
1003 * Firewall chain used for OEM-specific application restrictions.
1004 * Denylist of apps that will not have network access due to OEM-specific restrictions.
1005 * @hide
1006 */
1007 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1008
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001009 /**
1010 * Firewall chain used for OEM-specific application restrictions.
1011 * Denylist of apps that will not have network access due to OEM-specific restrictions.
1012 * @hide
1013 */
1014 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1015
markchiene1561fa2021-12-09 22:00:56 +08001016 /** @hide */
1017 @Retention(RetentionPolicy.SOURCE)
1018 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1019 FIREWALL_CHAIN_DOZABLE,
1020 FIREWALL_CHAIN_STANDBY,
1021 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001022 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001023 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Motomu Utsumid9801492022-06-01 13:57:27 +00001024 FIREWALL_CHAIN_LOCKDOWN_VPN,
1025 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001026 FIREWALL_CHAIN_OEM_DENY_2,
1027 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001028 })
1029 public @interface FirewallChain {}
Robert Horvathd945bf02022-01-27 19:55:16 +01001030 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
markchiene1561fa2021-12-09 22:00:56 +08001031
1032 /**
markchien011a7f52022-03-29 01:07:22 +08001033 * A firewall rule which allows or drops packets depending on existing policy.
1034 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1035 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001036 * @hide
1037 */
1038 @SystemApi(client = MODULE_LIBRARIES)
1039 public static final int FIREWALL_RULE_DEFAULT = 0;
1040
1041 /**
markchien011a7f52022-03-29 01:07:22 +08001042 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1043 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001044 * @hide
1045 */
1046 @SystemApi(client = MODULE_LIBRARIES)
1047 public static final int FIREWALL_RULE_ALLOW = 1;
1048
1049 /**
markchien011a7f52022-03-29 01:07:22 +08001050 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1051 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001052 * @hide
1053 */
1054 @SystemApi(client = MODULE_LIBRARIES)
1055 public static final int FIREWALL_RULE_DENY = 2;
1056
1057 /** @hide */
1058 @Retention(RetentionPolicy.SOURCE)
1059 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1060 FIREWALL_RULE_DEFAULT,
1061 FIREWALL_RULE_ALLOW,
1062 FIREWALL_RULE_DENY
1063 })
1064 public @interface FirewallRule {}
1065
1066 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001067 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1068 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1069 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1070 * methods that take a Context argument.
1071 */
1072 private static ConnectivityManager sInstance;
1073
1074 private final Context mContext;
1075
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001076 @GuardedBy("mTetheringEventCallbacks")
1077 private TetheringManager mTetheringManager;
1078
1079 private TetheringManager getTetheringManager() {
1080 synchronized (mTetheringEventCallbacks) {
1081 if (mTetheringManager == null) {
1082 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1083 }
1084 return mTetheringManager;
1085 }
1086 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001087
1088 /**
1089 * Tests if a given integer represents a valid network type.
1090 * @param networkType the type to be tested
1091 * @return a boolean. {@code true} if the type is valid, else {@code false}
1092 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1093 * validate a network type.
1094 */
1095 @Deprecated
1096 public static boolean isNetworkTypeValid(int networkType) {
1097 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1098 }
1099
1100 /**
1101 * Returns a non-localized string representing a given network type.
1102 * ONLY used for debugging output.
1103 * @param type the type needing naming
1104 * @return a String for the given type, or a string version of the type ("87")
1105 * if no name is known.
1106 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1107 * {@hide}
1108 */
1109 @Deprecated
1110 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1111 public static String getNetworkTypeName(int type) {
1112 switch (type) {
1113 case TYPE_NONE:
1114 return "NONE";
1115 case TYPE_MOBILE:
1116 return "MOBILE";
1117 case TYPE_WIFI:
1118 return "WIFI";
1119 case TYPE_MOBILE_MMS:
1120 return "MOBILE_MMS";
1121 case TYPE_MOBILE_SUPL:
1122 return "MOBILE_SUPL";
1123 case TYPE_MOBILE_DUN:
1124 return "MOBILE_DUN";
1125 case TYPE_MOBILE_HIPRI:
1126 return "MOBILE_HIPRI";
1127 case TYPE_WIMAX:
1128 return "WIMAX";
1129 case TYPE_BLUETOOTH:
1130 return "BLUETOOTH";
1131 case TYPE_DUMMY:
1132 return "DUMMY";
1133 case TYPE_ETHERNET:
1134 return "ETHERNET";
1135 case TYPE_MOBILE_FOTA:
1136 return "MOBILE_FOTA";
1137 case TYPE_MOBILE_IMS:
1138 return "MOBILE_IMS";
1139 case TYPE_MOBILE_CBS:
1140 return "MOBILE_CBS";
1141 case TYPE_WIFI_P2P:
1142 return "WIFI_P2P";
1143 case TYPE_MOBILE_IA:
1144 return "MOBILE_IA";
1145 case TYPE_MOBILE_EMERGENCY:
1146 return "MOBILE_EMERGENCY";
1147 case TYPE_PROXY:
1148 return "PROXY";
1149 case TYPE_VPN:
1150 return "VPN";
1151 default:
1152 return Integer.toString(type);
1153 }
1154 }
1155
1156 /**
1157 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001158 */
lucaslin10774b72021-03-17 14:16:01 +08001159 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001160 public void systemReady() {
1161 try {
1162 mService.systemReady();
1163 } catch (RemoteException e) {
1164 throw e.rethrowFromSystemServer();
1165 }
1166 }
1167
1168 /**
1169 * Checks if a given type uses the cellular data connection.
1170 * This should be replaced in the future by a network property.
1171 * @param networkType the type to check
1172 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1173 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1174 * {@hide}
1175 */
1176 @Deprecated
1177 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1178 public static boolean isNetworkTypeMobile(int networkType) {
1179 switch (networkType) {
1180 case TYPE_MOBILE:
1181 case TYPE_MOBILE_MMS:
1182 case TYPE_MOBILE_SUPL:
1183 case TYPE_MOBILE_DUN:
1184 case TYPE_MOBILE_HIPRI:
1185 case TYPE_MOBILE_FOTA:
1186 case TYPE_MOBILE_IMS:
1187 case TYPE_MOBILE_CBS:
1188 case TYPE_MOBILE_IA:
1189 case TYPE_MOBILE_EMERGENCY:
1190 return true;
1191 default:
1192 return false;
1193 }
1194 }
1195
1196 /**
1197 * Checks if the given network type is backed by a Wi-Fi radio.
1198 *
1199 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1200 * @hide
1201 */
1202 @Deprecated
1203 public static boolean isNetworkTypeWifi(int networkType) {
1204 switch (networkType) {
1205 case TYPE_WIFI:
1206 case TYPE_WIFI_P2P:
1207 return true;
1208 default:
1209 return false;
1210 }
1211 }
1212
1213 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001214 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1215 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001216 * Specify that the traffic for this user should by follow the default rules.
1217 * @hide
1218 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001219 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001220 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1221
1222 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001223 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1224 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001225 * Specify that the traffic for this user should by default go on a network with
1226 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1227 * if no such network is available.
1228 * @hide
1229 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001230 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001231 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1232
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001233 /**
1234 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1235 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1236 * Specify that the traffic for this user should by default go on a network with
1237 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
1238 * should not go on the system default network
1239 * @hide
1240 */
1241 @SystemApi(client = MODULE_LIBRARIES)
1242 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1243
Chalard Jeanad565e22021-02-25 17:23:40 +09001244 /** @hide */
1245 @Retention(RetentionPolicy.SOURCE)
1246 @IntDef(value = {
1247 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001248 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1249 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001250 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001251 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001252 }
1253
1254 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001255 * Specifies the preferred network type. When the device has more
1256 * than one type available the preferred network type will be used.
1257 *
1258 * @param preference the network type to prefer over all others. It is
1259 * unspecified what happens to the old preferred network in the
1260 * overall ordering.
1261 * @deprecated Functionality has been removed as it no longer makes sense,
1262 * with many more than two networks - we'd need an array to express
1263 * preference. Instead we use dynamic network properties of
1264 * the networks to describe their precedence.
1265 */
1266 @Deprecated
1267 public void setNetworkPreference(int preference) {
1268 }
1269
1270 /**
1271 * Retrieves the current preferred network type.
1272 *
1273 * @return an integer representing the preferred network type
1274 *
1275 * @deprecated Functionality has been removed as it no longer makes sense,
1276 * with many more than two networks - we'd need an array to express
1277 * preference. Instead we use dynamic network properties of
1278 * the networks to describe their precedence.
1279 */
1280 @Deprecated
1281 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1282 public int getNetworkPreference() {
1283 return TYPE_NONE;
1284 }
1285
1286 /**
1287 * Returns details about the currently active default data network. When
1288 * connected, this network is the default route for outgoing connections.
1289 * You should always check {@link NetworkInfo#isConnected()} before initiating
1290 * network traffic. This may return {@code null} when there is no default
1291 * network.
1292 * Note that if the default network is a VPN, this method will return the
1293 * NetworkInfo for one of its underlying networks instead, or null if the
1294 * VPN agent did not specify any. Apps interested in learning about VPNs
1295 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1296 *
1297 * @return a {@link NetworkInfo} object for the current default network
1298 * or {@code null} if no default network is currently active
1299 * @deprecated See {@link NetworkInfo}.
1300 */
1301 @Deprecated
1302 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1303 @Nullable
1304 public NetworkInfo getActiveNetworkInfo() {
1305 try {
1306 return mService.getActiveNetworkInfo();
1307 } catch (RemoteException e) {
1308 throw e.rethrowFromSystemServer();
1309 }
1310 }
1311
1312 /**
1313 * Returns a {@link Network} object corresponding to the currently active
1314 * default data network. In the event that the current active default data
1315 * network disconnects, the returned {@code Network} object will no longer
1316 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001317 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001318 *
1319 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001320 * {@code null} if no default network is currently active or if
1321 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001322 */
1323 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1324 @Nullable
1325 public Network getActiveNetwork() {
1326 try {
1327 return mService.getActiveNetwork();
1328 } catch (RemoteException e) {
1329 throw e.rethrowFromSystemServer();
1330 }
1331 }
1332
1333 /**
1334 * Returns a {@link Network} object corresponding to the currently active
1335 * default data network for a specific UID. In the event that the default data
1336 * network disconnects, the returned {@code Network} object will no longer
1337 * be usable. This will return {@code null} when there is no default
1338 * network for the UID.
1339 *
1340 * @return a {@link Network} object for the current default network for the
1341 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001342 *
1343 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001344 */
1345 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1346 @Nullable
1347 public Network getActiveNetworkForUid(int uid) {
1348 return getActiveNetworkForUid(uid, false);
1349 }
1350
1351 /** {@hide} */
1352 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1353 try {
1354 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1355 } catch (RemoteException e) {
1356 throw e.rethrowFromSystemServer();
1357 }
1358 }
1359
1360 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001361 * Adds or removes a requirement for given UID ranges to use the VPN.
1362 *
1363 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1364 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1365 * otherwise have permission to bypass the VPN (e.g., because they have the
1366 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1367 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1368 * set to {@code false}, a previously-added restriction is removed.
1369 * <p>
1370 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1371 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1372 * remove a previously-added range, the exact range must be removed as is.
1373 * <p>
1374 * The changes are applied asynchronously and may not have been applied by the time the method
1375 * returns. Apps will be notified about any changes that apply to them via
1376 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1377 * effect.
1378 * <p>
1379 * This method should be called only by the VPN code.
1380 *
1381 * @param ranges the UID ranges to restrict
1382 * @param requireVpn whether the specified UID ranges must use a VPN
1383 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001384 * @hide
1385 */
1386 @RequiresPermission(anyOf = {
1387 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001388 android.Manifest.permission.NETWORK_STACK,
1389 android.Manifest.permission.NETWORK_SETTINGS})
1390 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001391 public void setRequireVpnForUids(boolean requireVpn,
1392 @NonNull Collection<Range<Integer>> ranges) {
1393 Objects.requireNonNull(ranges);
1394 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1395 // This method is not necessarily expected to be used outside the system server, so
1396 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1397 // stack process, or by tests.
1398 UidRange[] rangesArray = new UidRange[ranges.size()];
1399 int index = 0;
1400 for (Range<Integer> range : ranges) {
1401 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1402 }
1403 try {
1404 mService.setRequireVpnForUids(requireVpn, rangesArray);
1405 } catch (RemoteException e) {
1406 throw e.rethrowFromSystemServer();
1407 }
1408 }
1409
1410 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001411 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1412 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1413 * but is still supported for backwards compatibility.
1414 * <p>
1415 * This type of VPN is assumed always to use the system default network, and must always declare
1416 * exactly one underlying network, which is the network that was the default when the VPN
1417 * connected.
1418 * <p>
1419 * Calling this method with {@code true} enables legacy behaviour, specifically:
1420 * <ul>
1421 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1422 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1423 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1424 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1425 * underlying the VPN.</li>
1426 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1427 * similarly replaced by the VPN network state.</li>
1428 * <li>Information on current network interfaces passed to NetworkStatsService will not
1429 * include any VPN interfaces.</li>
1430 * </ul>
1431 *
1432 * @param enabled whether legacy lockdown VPN is enabled or disabled
1433 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001434 * @hide
1435 */
1436 @RequiresPermission(anyOf = {
1437 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001438 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001439 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001440 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001441 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1442 try {
1443 mService.setLegacyLockdownVpnEnabled(enabled);
1444 } catch (RemoteException e) {
1445 throw e.rethrowFromSystemServer();
1446 }
1447 }
1448
1449 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001450 * Returns details about the currently active default data network
1451 * for a given uid. This is for internal use only to avoid spying
1452 * other apps.
1453 *
1454 * @return a {@link NetworkInfo} object for the current default network
1455 * for the given uid or {@code null} if no default network is
1456 * available for the specified uid.
1457 *
1458 * {@hide}
1459 */
1460 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1461 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1462 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1463 return getActiveNetworkInfoForUid(uid, false);
1464 }
1465
1466 /** {@hide} */
1467 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1468 try {
1469 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1470 } catch (RemoteException e) {
1471 throw e.rethrowFromSystemServer();
1472 }
1473 }
1474
1475 /**
1476 * Returns connection status information about a particular
1477 * network type.
1478 *
1479 * @param networkType integer specifying which networkType in
1480 * which you're interested.
1481 * @return a {@link NetworkInfo} object for the requested
1482 * network type or {@code null} if the type is not
1483 * supported by the device. If {@code networkType} is
1484 * TYPE_VPN and a VPN is active for the calling app,
1485 * then this method will try to return one of the
1486 * underlying networks for the VPN or null if the
1487 * VPN agent didn't specify any.
1488 *
1489 * @deprecated This method does not support multiple connected networks
1490 * of the same type. Use {@link #getAllNetworks} and
1491 * {@link #getNetworkInfo(android.net.Network)} instead.
1492 */
1493 @Deprecated
1494 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1495 @Nullable
1496 public NetworkInfo getNetworkInfo(int networkType) {
1497 try {
1498 return mService.getNetworkInfo(networkType);
1499 } catch (RemoteException e) {
1500 throw e.rethrowFromSystemServer();
1501 }
1502 }
1503
1504 /**
1505 * Returns connection status information about a particular
1506 * Network.
1507 *
1508 * @param network {@link Network} specifying which network
1509 * in which you're interested.
1510 * @return a {@link NetworkInfo} object for the requested
1511 * network or {@code null} if the {@code Network}
1512 * is not valid.
1513 * @deprecated See {@link NetworkInfo}.
1514 */
1515 @Deprecated
1516 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1517 @Nullable
1518 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1519 return getNetworkInfoForUid(network, Process.myUid(), false);
1520 }
1521
1522 /** {@hide} */
1523 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1524 try {
1525 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1526 } catch (RemoteException e) {
1527 throw e.rethrowFromSystemServer();
1528 }
1529 }
1530
1531 /**
1532 * Returns connection status information about all network
1533 * types supported by the device.
1534 *
1535 * @return an array of {@link NetworkInfo} objects. Check each
1536 * {@link NetworkInfo#getType} for which type each applies.
1537 *
1538 * @deprecated This method does not support multiple connected networks
1539 * of the same type. Use {@link #getAllNetworks} and
1540 * {@link #getNetworkInfo(android.net.Network)} instead.
1541 */
1542 @Deprecated
1543 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1544 @NonNull
1545 public NetworkInfo[] getAllNetworkInfo() {
1546 try {
1547 return mService.getAllNetworkInfo();
1548 } catch (RemoteException e) {
1549 throw e.rethrowFromSystemServer();
1550 }
1551 }
1552
1553 /**
junyulaib1211372021-03-03 12:09:05 +08001554 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1555 * connected.
1556 * @hide
1557 */
1558 @SystemApi(client = MODULE_LIBRARIES)
1559 @RequiresPermission(anyOf = {
1560 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1561 android.Manifest.permission.NETWORK_STACK,
1562 android.Manifest.permission.NETWORK_SETTINGS})
1563 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001564 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001565 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001566 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001567 } catch (RemoteException e) {
1568 throw e.rethrowFromSystemServer();
1569 }
1570 }
1571
1572 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001573 * Returns the {@link Network} object currently serving a given type, or
1574 * null if the given type is not connected.
1575 *
1576 * @hide
1577 * @deprecated This method does not support multiple connected networks
1578 * of the same type. Use {@link #getAllNetworks} and
1579 * {@link #getNetworkInfo(android.net.Network)} instead.
1580 */
1581 @Deprecated
1582 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1583 @UnsupportedAppUsage
1584 public Network getNetworkForType(int networkType) {
1585 try {
1586 return mService.getNetworkForType(networkType);
1587 } catch (RemoteException e) {
1588 throw e.rethrowFromSystemServer();
1589 }
1590 }
1591
1592 /**
1593 * Returns an array of all {@link Network} currently tracked by the
1594 * framework.
1595 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001596 * @deprecated This method does not provide any notification of network state changes, forcing
1597 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1598 * Apps should use methods such as
1599 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1600 * Apps that desire to obtain information about networks that do not apply to them
1601 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1602 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001603 * @return an array of {@link Network} objects.
1604 */
1605 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1606 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001607 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001608 public Network[] getAllNetworks() {
1609 try {
1610 return mService.getAllNetworks();
1611 } catch (RemoteException e) {
1612 throw e.rethrowFromSystemServer();
1613 }
1614 }
1615
1616 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001617 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001618 * the Networks that applications run by the given user will use by default.
1619 * @hide
1620 */
1621 @UnsupportedAppUsage
1622 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1623 try {
1624 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001625 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001626 } catch (RemoteException e) {
1627 throw e.rethrowFromSystemServer();
1628 }
1629 }
1630
1631 /**
1632 * Returns the IP information for the current default network.
1633 *
1634 * @return a {@link LinkProperties} object describing the IP info
1635 * for the current default network, or {@code null} if there
1636 * is no current default network.
1637 *
1638 * {@hide}
1639 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1640 * value of {@link #getActiveNetwork()} instead. In particular,
1641 * this method will return non-null LinkProperties even if the
1642 * app is blocked by policy from using this network.
1643 */
1644 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1645 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1646 public LinkProperties getActiveLinkProperties() {
1647 try {
1648 return mService.getActiveLinkProperties();
1649 } catch (RemoteException e) {
1650 throw e.rethrowFromSystemServer();
1651 }
1652 }
1653
1654 /**
1655 * Returns the IP information for a given network type.
1656 *
1657 * @param networkType the network type of interest.
1658 * @return a {@link LinkProperties} object describing the IP info
1659 * for the given networkType, or {@code null} if there is
1660 * no current default network.
1661 *
1662 * {@hide}
1663 * @deprecated This method does not support multiple connected networks
1664 * of the same type. Use {@link #getAllNetworks},
1665 * {@link #getNetworkInfo(android.net.Network)}, and
1666 * {@link #getLinkProperties(android.net.Network)} instead.
1667 */
1668 @Deprecated
1669 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1670 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1671 public LinkProperties getLinkProperties(int networkType) {
1672 try {
1673 return mService.getLinkPropertiesForType(networkType);
1674 } catch (RemoteException e) {
1675 throw e.rethrowFromSystemServer();
1676 }
1677 }
1678
1679 /**
1680 * Get the {@link LinkProperties} for the given {@link Network}. This
1681 * will return {@code null} if the network is unknown.
1682 *
1683 * @param network The {@link Network} object identifying the network in question.
1684 * @return The {@link LinkProperties} for the network, or {@code null}.
1685 */
1686 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1687 @Nullable
1688 public LinkProperties getLinkProperties(@Nullable Network network) {
1689 try {
1690 return mService.getLinkProperties(network);
1691 } catch (RemoteException e) {
1692 throw e.rethrowFromSystemServer();
1693 }
1694 }
1695
1696 /**
lucaslinc582d502022-01-27 09:07:00 +08001697 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001698 *
lucaslinc582d502022-01-27 09:07:00 +08001699 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1700 * given package, considering its permissions.
1701 *
1702 * @param lp A {@link LinkProperties} which will be redacted.
1703 * @param uid The target uid.
1704 * @param packageName The name of the package, for appops logging.
1705 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1706 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1707 * @hide
1708 */
1709 @RequiresPermission(anyOf = {
1710 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1711 android.Manifest.permission.NETWORK_STACK,
1712 android.Manifest.permission.NETWORK_SETTINGS})
1713 @SystemApi(client = MODULE_LIBRARIES)
1714 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001715 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001716 @NonNull String packageName) {
1717 try {
lucaslind2b06132022-03-02 10:56:57 +08001718 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001719 lp, uid, packageName, getAttributionTag());
1720 } catch (RemoteException e) {
1721 throw e.rethrowFromSystemServer();
1722 }
1723 }
1724
1725 /**
1726 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1727 *
1728 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1729 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1730 * sensitive information. To retrieve this location sensitive information (subject to
1731 * the caller's location permissions), use a {@link NetworkCallback} with the
1732 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1733 *
1734 * This method returns {@code null} if the network is unknown or if the |network| argument
1735 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001736 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001737 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001738 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001739 */
1740 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1741 @Nullable
1742 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1743 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001744 return mService.getNetworkCapabilities(
1745 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001746 } catch (RemoteException e) {
1747 throw e.rethrowFromSystemServer();
1748 }
1749 }
1750
1751 /**
lucaslinc582d502022-01-27 09:07:00 +08001752 * Redact {@link NetworkCapabilities} for a given package.
1753 *
1754 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001755 * to the given package, considering its permissions. If the passed capabilities contain
1756 * location-sensitive information, they will be redacted to the correct degree for the location
1757 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1758 * that level of location. If the UID holds no location permission, the returned object will
1759 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001760 *
1761 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1762 * @param uid The target uid.
1763 * @param packageName The name of the package, for appops logging.
1764 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1765 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1766 * @hide
1767 */
1768 @RequiresPermission(anyOf = {
1769 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1770 android.Manifest.permission.NETWORK_STACK,
1771 android.Manifest.permission.NETWORK_SETTINGS})
1772 @SystemApi(client = MODULE_LIBRARIES)
1773 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001774 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001775 @NonNull NetworkCapabilities nc,
1776 int uid, @NonNull String packageName) {
1777 try {
lucaslind2b06132022-03-02 10:56:57 +08001778 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001779 getAttributionTag());
1780 } catch (RemoteException e) {
1781 throw e.rethrowFromSystemServer();
1782 }
1783 }
1784
1785 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001786 * Gets a URL that can be used for resolving whether a captive portal is present.
1787 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1788 * portal is present.
1789 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1790 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1791 *
1792 * The system network validation may be using different strategies to detect captive portals,
1793 * so this method does not necessarily return a URL used by the system. It only returns a URL
1794 * that may be relevant for other components trying to detect captive portals.
1795 *
1796 * @hide
1797 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1798 * system.
1799 */
1800 @Deprecated
1801 @SystemApi
1802 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1803 public String getCaptivePortalServerUrl() {
1804 try {
1805 return mService.getCaptivePortalServerUrl();
1806 } catch (RemoteException e) {
1807 throw e.rethrowFromSystemServer();
1808 }
1809 }
1810
1811 /**
1812 * Tells the underlying networking system that the caller wants to
1813 * begin using the named feature. The interpretation of {@code feature}
1814 * is completely up to each networking implementation.
1815 *
1816 * <p>This method requires the caller to hold either the
1817 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1818 * or the ability to modify system settings as determined by
1819 * {@link android.provider.Settings.System#canWrite}.</p>
1820 *
1821 * @param networkType specifies which network the request pertains to
1822 * @param feature the name of the feature to be used
1823 * @return an integer value representing the outcome of the request.
1824 * The interpretation of this value is specific to each networking
1825 * implementation+feature combination, except that the value {@code -1}
1826 * always indicates failure.
1827 *
1828 * @deprecated Deprecated in favor of the cleaner
1829 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1830 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1831 * throw {@code UnsupportedOperationException} if called.
1832 * @removed
1833 */
1834 @Deprecated
1835 public int startUsingNetworkFeature(int networkType, String feature) {
1836 checkLegacyRoutingApiAccess();
1837 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1838 if (netCap == null) {
1839 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1840 feature);
1841 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1842 }
1843
1844 NetworkRequest request = null;
1845 synchronized (sLegacyRequests) {
1846 LegacyRequest l = sLegacyRequests.get(netCap);
1847 if (l != null) {
1848 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1849 renewRequestLocked(l);
1850 if (l.currentNetwork != null) {
1851 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1852 } else {
1853 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1854 }
1855 }
1856
1857 request = requestNetworkForFeatureLocked(netCap);
1858 }
1859 if (request != null) {
1860 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1861 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1862 } else {
1863 Log.d(TAG, " request Failed");
1864 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1865 }
1866 }
1867
1868 /**
1869 * Tells the underlying networking system that the caller is finished
1870 * using the named feature. The interpretation of {@code feature}
1871 * is completely up to each networking implementation.
1872 *
1873 * <p>This method requires the caller to hold either the
1874 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1875 * or the ability to modify system settings as determined by
1876 * {@link android.provider.Settings.System#canWrite}.</p>
1877 *
1878 * @param networkType specifies which network the request pertains to
1879 * @param feature the name of the feature that is no longer needed
1880 * @return an integer value representing the outcome of the request.
1881 * The interpretation of this value is specific to each networking
1882 * implementation+feature combination, except that the value {@code -1}
1883 * always indicates failure.
1884 *
1885 * @deprecated Deprecated in favor of the cleaner
1886 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1887 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1888 * throw {@code UnsupportedOperationException} if called.
1889 * @removed
1890 */
1891 @Deprecated
1892 public int stopUsingNetworkFeature(int networkType, String feature) {
1893 checkLegacyRoutingApiAccess();
1894 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1895 if (netCap == null) {
1896 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1897 feature);
1898 return -1;
1899 }
1900
1901 if (removeRequestForFeature(netCap)) {
1902 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1903 }
1904 return 1;
1905 }
1906
1907 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1908 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1909 if (networkType == TYPE_MOBILE) {
1910 switch (feature) {
1911 case "enableCBS":
1912 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1913 case "enableDUN":
1914 case "enableDUNAlways":
1915 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1916 case "enableFOTA":
1917 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1918 case "enableHIPRI":
1919 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1920 case "enableIMS":
1921 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1922 case "enableMMS":
1923 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1924 case "enableSUPL":
1925 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1926 default:
1927 return null;
1928 }
1929 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1930 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1931 }
1932 return null;
1933 }
1934
1935 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1936 if (netCap == null) return TYPE_NONE;
1937 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1938 return TYPE_MOBILE_CBS;
1939 }
1940 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1941 return TYPE_MOBILE_IMS;
1942 }
1943 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1944 return TYPE_MOBILE_FOTA;
1945 }
1946 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1947 return TYPE_MOBILE_DUN;
1948 }
1949 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1950 return TYPE_MOBILE_SUPL;
1951 }
1952 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1953 return TYPE_MOBILE_MMS;
1954 }
1955 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1956 return TYPE_MOBILE_HIPRI;
1957 }
1958 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1959 return TYPE_WIFI_P2P;
1960 }
1961 return TYPE_NONE;
1962 }
1963
1964 private static class LegacyRequest {
1965 NetworkCapabilities networkCapabilities;
1966 NetworkRequest networkRequest;
1967 int expireSequenceNumber;
1968 Network currentNetwork;
1969 int delay = -1;
1970
1971 private void clearDnsBinding() {
1972 if (currentNetwork != null) {
1973 currentNetwork = null;
1974 setProcessDefaultNetworkForHostResolution(null);
1975 }
1976 }
1977
1978 NetworkCallback networkCallback = new NetworkCallback() {
1979 @Override
1980 public void onAvailable(Network network) {
1981 currentNetwork = network;
1982 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1983 setProcessDefaultNetworkForHostResolution(network);
1984 }
1985 @Override
1986 public void onLost(Network network) {
1987 if (network.equals(currentNetwork)) clearDnsBinding();
1988 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1989 }
1990 };
1991 }
1992
1993 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1994 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1995 new HashMap<>();
1996
1997 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1998 synchronized (sLegacyRequests) {
1999 LegacyRequest l = sLegacyRequests.get(netCap);
2000 if (l != null) return l.networkRequest;
2001 }
2002 return null;
2003 }
2004
2005 private void renewRequestLocked(LegacyRequest l) {
2006 l.expireSequenceNumber++;
2007 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2008 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2009 }
2010
2011 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2012 int ourSeqNum = -1;
2013 synchronized (sLegacyRequests) {
2014 LegacyRequest l = sLegacyRequests.get(netCap);
2015 if (l == null) return;
2016 ourSeqNum = l.expireSequenceNumber;
2017 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2018 }
2019 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2020 }
2021
2022 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2023 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2024 int delay = -1;
2025 int type = legacyTypeForNetworkCapabilities(netCap);
2026 try {
2027 delay = mService.getRestoreDefaultNetworkDelay(type);
2028 } catch (RemoteException e) {
2029 throw e.rethrowFromSystemServer();
2030 }
2031 LegacyRequest l = new LegacyRequest();
2032 l.networkCapabilities = netCap;
2033 l.delay = delay;
2034 l.expireSequenceNumber = 0;
2035 l.networkRequest = sendRequestForNetwork(
2036 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2037 if (l.networkRequest == null) return null;
2038 sLegacyRequests.put(netCap, l);
2039 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2040 return l.networkRequest;
2041 }
2042
2043 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2044 if (delay >= 0) {
2045 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2046 CallbackHandler handler = getDefaultHandler();
2047 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2048 handler.sendMessageDelayed(msg, delay);
2049 }
2050 }
2051
2052 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2053 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2054 final LegacyRequest l;
2055 synchronized (sLegacyRequests) {
2056 l = sLegacyRequests.remove(netCap);
2057 }
2058 if (l == null) return false;
2059 unregisterNetworkCallback(l.networkCallback);
2060 l.clearDnsBinding();
2061 return true;
2062 }
2063
2064 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2065 static {
2066 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2067 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2068 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2069 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2070 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2071 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2072 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2073 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2074 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2075 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2076 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2077 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2078 }
2079
2080 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2081 static {
2082 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2083 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2084 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2085 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2086 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2087 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2088 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2089 }
2090
2091 /**
2092 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2093 * instance suitable for registering a request or callback. Throws an
2094 * IllegalArgumentException if no mapping from the legacy type to
2095 * NetworkCapabilities is known.
2096 *
2097 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2098 * to find the network instead.
2099 * @hide
2100 */
2101 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2102 final NetworkCapabilities nc = new NetworkCapabilities();
2103
2104 // Map from type to transports.
2105 final int NOT_FOUND = -1;
2106 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002107 if (transport == NOT_FOUND) {
2108 throw new IllegalArgumentException("unknown legacy type: " + type);
2109 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002110 nc.addTransportType(transport);
2111
2112 // Map from type to capabilities.
2113 nc.addCapability(sLegacyTypeToCapability.get(
2114 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2115 nc.maybeMarkCapabilitiesRestricted();
2116 return nc;
2117 }
2118
2119 /** @hide */
2120 public static class PacketKeepaliveCallback {
2121 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2122 public PacketKeepaliveCallback() {
2123 }
2124 /** The requested keepalive was successfully started. */
2125 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2126 public void onStarted() {}
2127 /** The keepalive was successfully stopped. */
2128 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2129 public void onStopped() {}
2130 /** An error occurred. */
2131 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2132 public void onError(int error) {}
2133 }
2134
2135 /**
2136 * Allows applications to request that the system periodically send specific packets on their
2137 * behalf, using hardware offload to save battery power.
2138 *
2139 * To request that the system send keepalives, call one of the methods that return a
2140 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2141 * passing in a non-null callback. If the callback is successfully started, the callback's
2142 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2143 * specifying one of the {@code ERROR_*} constants in this class.
2144 *
2145 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2146 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2147 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2148 *
2149 * @deprecated Use {@link SocketKeepalive} instead.
2150 *
2151 * @hide
2152 */
2153 public class PacketKeepalive {
2154
2155 private static final String TAG = "PacketKeepalive";
2156
2157 /** @hide */
2158 public static final int SUCCESS = 0;
2159
2160 /** @hide */
2161 public static final int NO_KEEPALIVE = -1;
2162
2163 /** @hide */
2164 public static final int BINDER_DIED = -10;
2165
2166 /** The specified {@code Network} is not connected. */
2167 public static final int ERROR_INVALID_NETWORK = -20;
2168 /** The specified IP addresses are invalid. For example, the specified source IP address is
2169 * not configured on the specified {@code Network}. */
2170 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2171 /** The requested port is invalid. */
2172 public static final int ERROR_INVALID_PORT = -22;
2173 /** The packet length is invalid (e.g., too long). */
2174 public static final int ERROR_INVALID_LENGTH = -23;
2175 /** The packet transmission interval is invalid (e.g., too short). */
2176 public static final int ERROR_INVALID_INTERVAL = -24;
2177
2178 /** The hardware does not support this request. */
2179 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2180 /** The hardware returned an error. */
2181 public static final int ERROR_HARDWARE_ERROR = -31;
2182
2183 /** The NAT-T destination port for IPsec */
2184 public static final int NATT_PORT = 4500;
2185
2186 /** The minimum interval in seconds between keepalive packet transmissions */
2187 public static final int MIN_INTERVAL = 10;
2188
2189 private final Network mNetwork;
2190 private final ISocketKeepaliveCallback mCallback;
2191 private final ExecutorService mExecutor;
2192
2193 private volatile Integer mSlot;
2194
2195 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2196 public void stop() {
2197 try {
2198 mExecutor.execute(() -> {
2199 try {
2200 if (mSlot != null) {
2201 mService.stopKeepalive(mNetwork, mSlot);
2202 }
2203 } catch (RemoteException e) {
2204 Log.e(TAG, "Error stopping packet keepalive: ", e);
2205 throw e.rethrowFromSystemServer();
2206 }
2207 });
2208 } catch (RejectedExecutionException e) {
2209 // The internal executor has already stopped due to previous event.
2210 }
2211 }
2212
2213 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002214 Objects.requireNonNull(network, "network cannot be null");
2215 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002216 mNetwork = network;
2217 mExecutor = Executors.newSingleThreadExecutor();
2218 mCallback = new ISocketKeepaliveCallback.Stub() {
2219 @Override
2220 public void onStarted(int slot) {
2221 final long token = Binder.clearCallingIdentity();
2222 try {
2223 mExecutor.execute(() -> {
2224 mSlot = slot;
2225 callback.onStarted();
2226 });
2227 } finally {
2228 Binder.restoreCallingIdentity(token);
2229 }
2230 }
2231
2232 @Override
2233 public void onStopped() {
2234 final long token = Binder.clearCallingIdentity();
2235 try {
2236 mExecutor.execute(() -> {
2237 mSlot = null;
2238 callback.onStopped();
2239 });
2240 } finally {
2241 Binder.restoreCallingIdentity(token);
2242 }
2243 mExecutor.shutdown();
2244 }
2245
2246 @Override
2247 public void onError(int error) {
2248 final long token = Binder.clearCallingIdentity();
2249 try {
2250 mExecutor.execute(() -> {
2251 mSlot = null;
2252 callback.onError(error);
2253 });
2254 } finally {
2255 Binder.restoreCallingIdentity(token);
2256 }
2257 mExecutor.shutdown();
2258 }
2259
2260 @Override
2261 public void onDataReceived() {
2262 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2263 // this callback when data is received.
2264 }
2265 };
2266 }
2267 }
2268
2269 /**
2270 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2271 *
2272 * @deprecated Use {@link #createSocketKeepalive} instead.
2273 *
2274 * @hide
2275 */
2276 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2277 public PacketKeepalive startNattKeepalive(
2278 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2279 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2280 final PacketKeepalive k = new PacketKeepalive(network, callback);
2281 try {
2282 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2283 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2284 } catch (RemoteException e) {
2285 Log.e(TAG, "Error starting packet keepalive: ", e);
2286 throw e.rethrowFromSystemServer();
2287 }
2288 return k;
2289 }
2290
2291 // Construct an invalid fd.
2292 private ParcelFileDescriptor createInvalidFd() {
2293 final int invalidFd = -1;
2294 return ParcelFileDescriptor.adoptFd(invalidFd);
2295 }
2296
2297 /**
2298 * Request that keepalives be started on a IPsec NAT-T socket.
2299 *
2300 * @param network The {@link Network} the socket is on.
2301 * @param socket The socket that needs to be kept alive.
2302 * @param source The source address of the {@link UdpEncapsulationSocket}.
2303 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2304 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2305 * must run callback sequentially, otherwise the order of callbacks cannot be
2306 * guaranteed.
2307 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2308 * changes. Must be extended by applications that use this API.
2309 *
2310 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2311 * given socket.
2312 **/
2313 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2314 @NonNull UdpEncapsulationSocket socket,
2315 @NonNull InetAddress source,
2316 @NonNull InetAddress destination,
2317 @NonNull @CallbackExecutor Executor executor,
2318 @NonNull Callback callback) {
2319 ParcelFileDescriptor dup;
2320 try {
2321 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2322 // which cannot be obtained by the app process.
2323 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2324 } catch (IOException ignored) {
2325 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2326 // ERROR_INVALID_SOCKET.
2327 dup = createInvalidFd();
2328 }
2329 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2330 destination, executor, callback);
2331 }
2332
2333 /**
2334 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2335 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2336 *
2337 * @param network The {@link Network} the socket is on.
2338 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2339 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2340 * from that port.
2341 * @param source The source address of the {@link UdpEncapsulationSocket}.
2342 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2343 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2344 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2345 * must run callback sequentially, otherwise the order of callbacks cannot be
2346 * guaranteed.
2347 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2348 * changes. Must be extended by applications that use this API.
2349 *
2350 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2351 * given socket.
2352 * @hide
2353 */
2354 @SystemApi
2355 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2356 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2357 @NonNull ParcelFileDescriptor pfd,
2358 @NonNull InetAddress source,
2359 @NonNull InetAddress destination,
2360 @NonNull @CallbackExecutor Executor executor,
2361 @NonNull Callback callback) {
2362 ParcelFileDescriptor dup;
2363 try {
2364 // TODO: Consider remove unnecessary dup.
2365 dup = pfd.dup();
2366 } catch (IOException ignored) {
2367 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2368 // ERROR_INVALID_SOCKET.
2369 dup = createInvalidFd();
2370 }
2371 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002372 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002373 }
2374
2375 /**
2376 * Request that keepalives be started on a TCP socket.
2377 * The socket must be established.
2378 *
2379 * @param network The {@link Network} the socket is on.
2380 * @param socket The socket that needs to be kept alive.
2381 * @param executor The executor on which callback will be invoked. This implementation assumes
2382 * the provided {@link Executor} runs the callbacks in sequence with no
2383 * concurrency. Failing this, no guarantee of correctness can be made. It is
2384 * the responsibility of the caller to ensure the executor provides this
2385 * guarantee. A simple way of creating such an executor is with the standard
2386 * tool {@code Executors.newSingleThreadExecutor}.
2387 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2388 * changes. Must be extended by applications that use this API.
2389 *
2390 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2391 * given socket.
2392 * @hide
2393 */
2394 @SystemApi
2395 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2396 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2397 @NonNull Socket socket,
2398 @NonNull Executor executor,
2399 @NonNull Callback callback) {
2400 ParcelFileDescriptor dup;
2401 try {
2402 dup = ParcelFileDescriptor.fromSocket(socket);
2403 } catch (UncheckedIOException ignored) {
2404 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2405 // ERROR_INVALID_SOCKET.
2406 dup = createInvalidFd();
2407 }
2408 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2409 }
2410
2411 /**
2412 * Ensure that a network route exists to deliver traffic to the specified
2413 * host via the specified network interface. An attempt to add a route that
2414 * already exists is ignored, but treated as successful.
2415 *
2416 * <p>This method requires the caller to hold either the
2417 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2418 * or the ability to modify system settings as determined by
2419 * {@link android.provider.Settings.System#canWrite}.</p>
2420 *
2421 * @param networkType the type of the network over which traffic to the specified
2422 * host is to be routed
2423 * @param hostAddress the IP address of the host to which the route is desired
2424 * @return {@code true} on success, {@code false} on failure
2425 *
2426 * @deprecated Deprecated in favor of the
2427 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2428 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2429 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2430 * throw {@code UnsupportedOperationException} if called.
2431 * @removed
2432 */
2433 @Deprecated
2434 public boolean requestRouteToHost(int networkType, int hostAddress) {
2435 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2436 }
2437
2438 /**
2439 * Ensure that a network route exists to deliver traffic to the specified
2440 * host via the specified network interface. An attempt to add a route that
2441 * already exists is ignored, but treated as successful.
2442 *
2443 * <p>This method requires the caller to hold either the
2444 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2445 * or the ability to modify system settings as determined by
2446 * {@link android.provider.Settings.System#canWrite}.</p>
2447 *
2448 * @param networkType the type of the network over which traffic to the specified
2449 * host is to be routed
2450 * @param hostAddress the IP address of the host to which the route is desired
2451 * @return {@code true} on success, {@code false} on failure
2452 * @hide
2453 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2454 * {@link #bindProcessToNetwork} API.
2455 */
2456 @Deprecated
2457 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002458 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002459 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2460 checkLegacyRoutingApiAccess();
2461 try {
2462 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2463 mContext.getOpPackageName(), getAttributionTag());
2464 } catch (RemoteException e) {
2465 throw e.rethrowFromSystemServer();
2466 }
2467 }
2468
2469 /**
2470 * @return the context's attribution tag
2471 */
2472 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2473 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002474 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002475 }
2476
2477 /**
2478 * Returns the value of the setting for background data usage. If false,
2479 * applications should not use the network if the application is not in the
2480 * foreground. Developers should respect this setting, and check the value
2481 * of this before performing any background data operations.
2482 * <p>
2483 * All applications that have background services that use the network
2484 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2485 * <p>
2486 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2487 * background data depends on several combined factors, and this method will
2488 * always return {@code true}. Instead, when background data is unavailable,
2489 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2490 *
2491 * @return Whether background data usage is allowed.
2492 */
2493 @Deprecated
2494 public boolean getBackgroundDataSetting() {
2495 // assume that background data is allowed; final authority is
2496 // NetworkInfo which may be blocked.
2497 return true;
2498 }
2499
2500 /**
2501 * Sets the value of the setting for background data usage.
2502 *
2503 * @param allowBackgroundData Whether an application should use data while
2504 * it is in the background.
2505 *
2506 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2507 * @see #getBackgroundDataSetting()
2508 * @hide
2509 */
2510 @Deprecated
2511 @UnsupportedAppUsage
2512 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2513 // ignored
2514 }
2515
2516 /**
2517 * @hide
2518 * @deprecated Talk to TelephonyManager directly
2519 */
2520 @Deprecated
2521 @UnsupportedAppUsage
2522 public boolean getMobileDataEnabled() {
2523 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2524 if (tm != null) {
2525 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2526 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2527 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2528 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2529 + " retVal=" + retVal);
2530 return retVal;
2531 }
2532 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2533 return false;
2534 }
2535
2536 /**
2537 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2538 * to find out when the system default network has gone in to a high power state.
2539 */
2540 public interface OnNetworkActiveListener {
2541 /**
2542 * Called on the main thread of the process to report that the current data network
2543 * has become active, and it is now a good time to perform any pending network
2544 * operations. Note that this listener only tells you when the network becomes
2545 * active; if at any other time you want to know whether it is active (and thus okay
2546 * to initiate network traffic), you can retrieve its instantaneous state with
2547 * {@link ConnectivityManager#isDefaultNetworkActive}.
2548 */
2549 void onNetworkActive();
2550 }
2551
Chiachang Wang2de41682021-09-23 10:46:03 +08002552 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002553 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2554 mNetworkActivityListeners = new ArrayMap<>();
2555
2556 /**
2557 * Start listening to reports when the system's default data network is active, meaning it is
2558 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2559 * to determine the current state of the system's default network after registering the
2560 * listener.
2561 * <p>
2562 * If the process default network has been set with
2563 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2564 * reflect the process's default, but the system default.
2565 *
2566 * @param l The listener to be told when the network is active.
2567 */
2568 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002569 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002570 @Override
2571 public void onNetworkActive() throws RemoteException {
2572 l.onNetworkActive();
2573 }
2574 };
2575
Chiachang Wang2de41682021-09-23 10:46:03 +08002576 synchronized (mNetworkActivityListeners) {
2577 try {
2578 mService.registerNetworkActivityListener(rl);
2579 mNetworkActivityListeners.put(l, rl);
2580 } catch (RemoteException e) {
2581 throw e.rethrowFromSystemServer();
2582 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002583 }
2584 }
2585
2586 /**
2587 * Remove network active listener previously registered with
2588 * {@link #addDefaultNetworkActiveListener}.
2589 *
2590 * @param l Previously registered listener.
2591 */
2592 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002593 synchronized (mNetworkActivityListeners) {
2594 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2595 if (rl == null) {
2596 throw new IllegalArgumentException("Listener was not registered.");
2597 }
2598 try {
2599 mService.unregisterNetworkActivityListener(rl);
2600 mNetworkActivityListeners.remove(l);
2601 } catch (RemoteException e) {
2602 throw e.rethrowFromSystemServer();
2603 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002604 }
2605 }
2606
2607 /**
2608 * Return whether the data network is currently active. An active network means that
2609 * it is currently in a high power state for performing data transmission. On some
2610 * types of networks, it may be expensive to move and stay in such a state, so it is
2611 * more power efficient to batch network traffic together when the radio is already in
2612 * this state. This method tells you whether right now is currently a good time to
2613 * initiate network traffic, as the network is already active.
2614 */
2615 public boolean isDefaultNetworkActive() {
2616 try {
lucaslin709eb842021-01-21 02:04:15 +08002617 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002618 } catch (RemoteException e) {
2619 throw e.rethrowFromSystemServer();
2620 }
2621 }
2622
2623 /**
2624 * {@hide}
2625 */
2626 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002627 this(context, service, true /* newStatic */);
2628 }
2629
2630 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002631 mContext = Objects.requireNonNull(context, "missing context");
2632 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002633 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2634 // different ConnectivityManager, but that's still OK considering its usage.
2635 if (sInstance == null && newStatic) {
2636 final Context appContext = mContext.getApplicationContext();
2637 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2638 // If the application context is null, we're either in the system process or
2639 // it's the application context very early in app initialization. In both these
2640 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2641 // service. http://b/27532714 .
2642 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2643 false /* newStatic */);
2644 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002645 }
2646
2647 /** {@hide} */
2648 @UnsupportedAppUsage
2649 public static ConnectivityManager from(Context context) {
2650 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2651 }
2652
2653 /** @hide */
2654 public NetworkRequest getDefaultRequest() {
2655 try {
2656 // This is not racy as the default request is final in ConnectivityService.
2657 return mService.getDefaultRequest();
2658 } catch (RemoteException e) {
2659 throw e.rethrowFromSystemServer();
2660 }
2661 }
2662
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002663 /**
2664 * Check if the package is a allowed to write settings. This also accounts that such an access
2665 * happened.
2666 *
2667 * @return {@code true} iff the package is allowed to write settings.
2668 */
2669 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2670 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2671 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2672 boolean throwException) {
2673 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002674 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002675 }
2676
2677 /**
2678 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2679 * situations where a Context pointer is unavailable.
2680 * @hide
2681 */
2682 @Deprecated
2683 static ConnectivityManager getInstanceOrNull() {
2684 return sInstance;
2685 }
2686
2687 /**
2688 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2689 * situations where a Context pointer is unavailable.
2690 * @hide
2691 */
2692 @Deprecated
2693 @UnsupportedAppUsage
2694 private static ConnectivityManager getInstance() {
2695 if (getInstanceOrNull() == null) {
2696 throw new IllegalStateException("No ConnectivityManager yet constructed");
2697 }
2698 return getInstanceOrNull();
2699 }
2700
2701 /**
2702 * Get the set of tetherable, available interfaces. This list is limited by
2703 * device configuration and current interface existence.
2704 *
2705 * @return an array of 0 or more Strings of tetherable interface names.
2706 *
2707 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2708 * {@hide}
2709 */
2710 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2711 @UnsupportedAppUsage
2712 @Deprecated
2713 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002714 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002715 }
2716
2717 /**
2718 * Get the set of tethered interfaces.
2719 *
2720 * @return an array of 0 or more String of currently tethered interface names.
2721 *
2722 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2723 * {@hide}
2724 */
2725 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2726 @UnsupportedAppUsage
2727 @Deprecated
2728 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002729 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002730 }
2731
2732 /**
2733 * Get the set of interface names which attempted to tether but
2734 * failed. Re-attempting to tether may cause them to reset to the Tethered
2735 * state. Alternatively, causing the interface to be destroyed and recreated
2736 * may cause them to reset to the available state.
2737 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2738 * information on the cause of the errors.
2739 *
2740 * @return an array of 0 or more String indicating the interface names
2741 * which failed to tether.
2742 *
2743 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2744 * {@hide}
2745 */
2746 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2747 @UnsupportedAppUsage
2748 @Deprecated
2749 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002750 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002751 }
2752
2753 /**
2754 * Get the set of tethered dhcp ranges.
2755 *
2756 * @deprecated This method is not supported.
2757 * TODO: remove this function when all of clients are removed.
2758 * {@hide}
2759 */
2760 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2761 @Deprecated
2762 public String[] getTetheredDhcpRanges() {
2763 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2764 }
2765
2766 /**
2767 * Attempt to tether the named interface. This will setup a dhcp server
2768 * on the interface, forward and NAT IP packets and forward DNS requests
2769 * to the best active upstream network interface. Note that if no upstream
2770 * IP network interface is available, dhcp will still run and traffic will be
2771 * allowed between the tethered devices and this device, though upstream net
2772 * access will of course fail until an upstream network interface becomes
2773 * active.
2774 *
2775 * <p>This method requires the caller to hold either the
2776 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2777 * or the ability to modify system settings as determined by
2778 * {@link android.provider.Settings.System#canWrite}.</p>
2779 *
2780 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2781 * and WifiStateMachine which need direct access. All other clients should use
2782 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2783 * logic.</p>
2784 *
2785 * @param iface the interface name to tether.
2786 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2787 * @deprecated Use {@link TetheringManager#startTethering} instead
2788 *
2789 * {@hide}
2790 */
2791 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2792 @Deprecated
2793 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002794 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002795 }
2796
2797 /**
2798 * Stop tethering the named interface.
2799 *
2800 * <p>This method requires the caller to hold either the
2801 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2802 * or the ability to modify system settings as determined by
2803 * {@link android.provider.Settings.System#canWrite}.</p>
2804 *
2805 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2806 * and WifiStateMachine which need direct access. All other clients should use
2807 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2808 * logic.</p>
2809 *
2810 * @param iface the interface name to untether.
2811 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2812 *
2813 * {@hide}
2814 */
2815 @UnsupportedAppUsage
2816 @Deprecated
2817 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002818 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002819 }
2820
2821 /**
2822 * Check if the device allows for tethering. It may be disabled via
2823 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2824 * due to device configuration.
2825 *
2826 * <p>If this app does not have permission to use this API, it will always
2827 * return false rather than throw an exception.</p>
2828 *
2829 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2830 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2831 *
2832 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2833 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2834 *
2835 * @return a boolean - {@code true} indicating Tethering is supported.
2836 *
2837 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2838 * {@hide}
2839 */
2840 @SystemApi
2841 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2842 android.Manifest.permission.WRITE_SETTINGS})
2843 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002844 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002845 }
2846
2847 /**
2848 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2849 *
2850 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2851 * @hide
2852 */
2853 @SystemApi
2854 @Deprecated
2855 public static abstract class OnStartTetheringCallback {
2856 /**
2857 * Called when tethering has been successfully started.
2858 */
2859 public void onTetheringStarted() {}
2860
2861 /**
2862 * Called when starting tethering failed.
2863 */
2864 public void onTetheringFailed() {}
2865 }
2866
2867 /**
2868 * Convenient overload for
2869 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2870 * handler to run on the current thread's {@link Looper}.
2871 *
2872 * @deprecated Use {@link TetheringManager#startTethering} instead.
2873 * @hide
2874 */
2875 @SystemApi
2876 @Deprecated
2877 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2878 public void startTethering(int type, boolean showProvisioningUi,
2879 final OnStartTetheringCallback callback) {
2880 startTethering(type, showProvisioningUi, callback, null);
2881 }
2882
2883 /**
2884 * Runs tether provisioning for the given type if needed and then starts tethering if
2885 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2886 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2887 * schedules tether provisioning re-checks if appropriate.
2888 *
2889 * @param type The type of tethering to start. Must be one of
2890 * {@link ConnectivityManager.TETHERING_WIFI},
2891 * {@link ConnectivityManager.TETHERING_USB}, or
2892 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2893 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2894 * is one. This should be true the first time this function is called and also any time
2895 * the user can see this UI. It gives users information from their carrier about the
2896 * check failing and how they can sign up for tethering if possible.
2897 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2898 * of the result of trying to tether.
2899 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2900 *
2901 * @deprecated Use {@link TetheringManager#startTethering} instead.
2902 * @hide
2903 */
2904 @SystemApi
2905 @Deprecated
2906 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2907 public void startTethering(int type, boolean showProvisioningUi,
2908 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002909 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002910
2911 final Executor executor = new Executor() {
2912 @Override
2913 public void execute(Runnable command) {
2914 if (handler == null) {
2915 command.run();
2916 } else {
2917 handler.post(command);
2918 }
2919 }
2920 };
2921
2922 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2923 @Override
2924 public void onTetheringStarted() {
2925 callback.onTetheringStarted();
2926 }
2927
2928 @Override
2929 public void onTetheringFailed(final int error) {
2930 callback.onTetheringFailed();
2931 }
2932 };
2933
2934 final TetheringRequest request = new TetheringRequest.Builder(type)
2935 .setShouldShowEntitlementUi(showProvisioningUi).build();
2936
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002937 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002938 }
2939
2940 /**
2941 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2942 * applicable.
2943 *
2944 * @param type The type of tethering to stop. Must be one of
2945 * {@link ConnectivityManager.TETHERING_WIFI},
2946 * {@link ConnectivityManager.TETHERING_USB}, or
2947 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2948 *
2949 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2950 * @hide
2951 */
2952 @SystemApi
2953 @Deprecated
2954 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2955 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002956 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002957 }
2958
2959 /**
2960 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2961 * upstream status.
2962 *
2963 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2964 * @hide
2965 */
2966 @SystemApi
2967 @Deprecated
2968 public abstract static class OnTetheringEventCallback {
2969
2970 /**
2971 * Called when tethering upstream changed. This can be called multiple times and can be
2972 * called any time.
2973 *
2974 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2975 * have any upstream.
2976 */
2977 public void onUpstreamChanged(@Nullable Network network) {}
2978 }
2979
2980 @GuardedBy("mTetheringEventCallbacks")
2981 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2982 mTetheringEventCallbacks = new ArrayMap<>();
2983
2984 /**
2985 * Start listening to tethering change events. Any new added callback will receive the last
2986 * tethering status right away. If callback is registered when tethering has no upstream or
2987 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2988 * with a null argument. The same callback object cannot be registered twice.
2989 *
2990 * @param executor the executor on which callback will be invoked.
2991 * @param callback the callback to be called when tethering has change events.
2992 *
2993 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2994 * @hide
2995 */
2996 @SystemApi
2997 @Deprecated
2998 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2999 public void registerTetheringEventCallback(
3000 @NonNull @CallbackExecutor Executor executor,
3001 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003002 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003003
3004 final TetheringEventCallback tetherCallback =
3005 new TetheringEventCallback() {
3006 @Override
3007 public void onUpstreamChanged(@Nullable Network network) {
3008 callback.onUpstreamChanged(network);
3009 }
3010 };
3011
3012 synchronized (mTetheringEventCallbacks) {
3013 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003014 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003015 }
3016 }
3017
3018 /**
3019 * Remove tethering event callback previously registered with
3020 * {@link #registerTetheringEventCallback}.
3021 *
3022 * @param callback previously registered callback.
3023 *
3024 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3025 * @hide
3026 */
3027 @SystemApi
3028 @Deprecated
3029 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3030 public void unregisterTetheringEventCallback(
3031 @NonNull final OnTetheringEventCallback callback) {
3032 Objects.requireNonNull(callback, "The callback must be non-null");
3033 synchronized (mTetheringEventCallbacks) {
3034 final TetheringEventCallback tetherCallback =
3035 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003036 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003037 }
3038 }
3039
3040
3041 /**
3042 * Get the list of regular expressions that define any tetherable
3043 * USB network interfaces. If USB tethering is not supported by the
3044 * device, this list should be empty.
3045 *
3046 * @return an array of 0 or more regular expression Strings defining
3047 * what interfaces are considered tetherable usb interfaces.
3048 *
3049 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3050 * {@hide}
3051 */
3052 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3053 @UnsupportedAppUsage
3054 @Deprecated
3055 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003056 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003057 }
3058
3059 /**
3060 * Get the list of regular expressions that define any tetherable
3061 * Wifi network interfaces. If Wifi tethering is not supported by the
3062 * device, this list should be empty.
3063 *
3064 * @return an array of 0 or more regular expression Strings defining
3065 * what interfaces are considered tetherable wifi interfaces.
3066 *
3067 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3068 * {@hide}
3069 */
3070 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3071 @UnsupportedAppUsage
3072 @Deprecated
3073 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003074 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003075 }
3076
3077 /**
3078 * Get the list of regular expressions that define any tetherable
3079 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3080 * device, this list should be empty.
3081 *
3082 * @return an array of 0 or more regular expression Strings defining
3083 * what interfaces are considered tetherable bluetooth interfaces.
3084 *
3085 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3086 *TetheringManager.TetheringInterfaceRegexps)} instead.
3087 * {@hide}
3088 */
3089 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3090 @UnsupportedAppUsage
3091 @Deprecated
3092 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003093 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003094 }
3095
3096 /**
3097 * Attempt to both alter the mode of USB and Tethering of USB. A
3098 * utility method to deal with some of the complexity of USB - will
3099 * attempt to switch to Rndis and subsequently tether the resulting
3100 * interface on {@code true} or turn off tethering and switch off
3101 * Rndis on {@code false}.
3102 *
3103 * <p>This method requires the caller to hold either the
3104 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3105 * or the ability to modify system settings as determined by
3106 * {@link android.provider.Settings.System#canWrite}.</p>
3107 *
3108 * @param enable a boolean - {@code true} to enable tethering
3109 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3110 * @deprecated Use {@link TetheringManager#startTethering} instead
3111 *
3112 * {@hide}
3113 */
3114 @UnsupportedAppUsage
3115 @Deprecated
3116 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003117 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003118 }
3119
3120 /**
3121 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3122 * {@hide}
3123 */
3124 @SystemApi
3125 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003126 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003127 /**
3128 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3129 * {@hide}
3130 */
3131 @Deprecated
3132 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3133 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3134 /**
3135 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3136 * {@hide}
3137 */
3138 @Deprecated
3139 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3140 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3141 /**
3142 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3143 * {@hide}
3144 */
3145 @Deprecated
3146 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3147 /**
3148 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3149 * {@hide}
3150 */
3151 @Deprecated
3152 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3153 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3154 /**
3155 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3156 * {@hide}
3157 */
3158 @Deprecated
3159 public static final int TETHER_ERROR_MASTER_ERROR =
3160 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3161 /**
3162 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3163 * {@hide}
3164 */
3165 @Deprecated
3166 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3167 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3168 /**
3169 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3170 * {@hide}
3171 */
3172 @Deprecated
3173 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3174 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3175 /**
3176 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3177 * {@hide}
3178 */
3179 @Deprecated
3180 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3181 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3182 /**
3183 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3184 * {@hide}
3185 */
3186 @Deprecated
3187 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3188 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3189 /**
3190 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3191 * {@hide}
3192 */
3193 @Deprecated
3194 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3195 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3196 /**
3197 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3198 * {@hide}
3199 */
3200 @SystemApi
3201 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003202 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003203 /**
3204 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3205 * {@hide}
3206 */
3207 @Deprecated
3208 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3209 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3210 /**
3211 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3212 * {@hide}
3213 */
3214 @SystemApi
3215 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003216 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003217
3218 /**
3219 * Get a more detailed error code after a Tethering or Untethering
3220 * request asynchronously failed.
3221 *
3222 * @param iface The name of the interface of interest
3223 * @return error The error code of the last error tethering or untethering the named
3224 * interface
3225 *
3226 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3227 * {@hide}
3228 */
3229 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3230 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3231 @Deprecated
3232 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003233 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003234 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3235 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3236 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3237 // instead.
3238 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3239 }
3240 return error;
3241 }
3242
3243 /** @hide */
3244 @Retention(RetentionPolicy.SOURCE)
3245 @IntDef(value = {
3246 TETHER_ERROR_NO_ERROR,
3247 TETHER_ERROR_PROVISION_FAILED,
3248 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3249 })
3250 public @interface EntitlementResultCode {
3251 }
3252
3253 /**
3254 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3255 * entitlement succeeded.
3256 *
3257 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3258 * @hide
3259 */
3260 @SystemApi
3261 @Deprecated
3262 public interface OnTetheringEntitlementResultListener {
3263 /**
3264 * Called to notify entitlement result.
3265 *
3266 * @param resultCode an int value of entitlement result. It may be one of
3267 * {@link #TETHER_ERROR_NO_ERROR},
3268 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3269 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3270 */
3271 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3272 }
3273
3274 /**
3275 * Get the last value of the entitlement check on this downstream. If the cached value is
3276 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3277 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3278 * guaranteed that the UI-based entitlement check will complete in any specific time period
3279 * and may in fact never complete. Any successful entitlement check the platform performs for
3280 * any reason will update the cached value.
3281 *
3282 * @param type the downstream type of tethering. Must be one of
3283 * {@link #TETHERING_WIFI},
3284 * {@link #TETHERING_USB}, or
3285 * {@link #TETHERING_BLUETOOTH}.
3286 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3287 * @param executor the executor on which callback will be invoked.
3288 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3289 * notify the caller of the result of entitlement check. The listener may be called zero
3290 * or one time.
3291 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3292 * {@hide}
3293 */
3294 @SystemApi
3295 @Deprecated
3296 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3297 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3298 @NonNull @CallbackExecutor Executor executor,
3299 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003300 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003301 ResultReceiver wrappedListener = new ResultReceiver(null) {
3302 @Override
3303 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003304 final long token = Binder.clearCallingIdentity();
3305 try {
3306 executor.execute(() -> {
3307 listener.onTetheringEntitlementResult(resultCode);
3308 });
3309 } finally {
3310 Binder.restoreCallingIdentity(token);
3311 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003312 }
3313 };
3314
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003315 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003316 showEntitlementUi);
3317 }
3318
3319 /**
3320 * Report network connectivity status. This is currently used only
3321 * to alter status bar UI.
3322 * <p>This method requires the caller to hold the permission
3323 * {@link android.Manifest.permission#STATUS_BAR}.
3324 *
3325 * @param networkType The type of network you want to report on
3326 * @param percentage The quality of the connection 0 is bad, 100 is good
3327 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3328 * {@hide}
3329 */
3330 public void reportInetCondition(int networkType, int percentage) {
3331 printStackTrace();
3332 try {
3333 mService.reportInetCondition(networkType, percentage);
3334 } catch (RemoteException e) {
3335 throw e.rethrowFromSystemServer();
3336 }
3337 }
3338
3339 /**
3340 * Report a problem network to the framework. This provides a hint to the system
3341 * that there might be connectivity problems on this network and may cause
3342 * the framework to re-evaluate network connectivity and/or switch to another
3343 * network.
3344 *
3345 * @param network The {@link Network} the application was attempting to use
3346 * or {@code null} to indicate the current default network.
3347 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3348 * working and non-working connectivity.
3349 */
3350 @Deprecated
3351 public void reportBadNetwork(@Nullable Network network) {
3352 printStackTrace();
3353 try {
3354 // One of these will be ignored because it matches system's current state.
3355 // The other will trigger the necessary reevaluation.
3356 mService.reportNetworkConnectivity(network, true);
3357 mService.reportNetworkConnectivity(network, false);
3358 } catch (RemoteException e) {
3359 throw e.rethrowFromSystemServer();
3360 }
3361 }
3362
3363 /**
3364 * Report to the framework whether a network has working connectivity.
3365 * This provides a hint to the system that a particular network is providing
3366 * working connectivity or not. In response the framework may re-evaluate
3367 * the network's connectivity and might take further action thereafter.
3368 *
3369 * @param network The {@link Network} the application was attempting to use
3370 * or {@code null} to indicate the current default network.
3371 * @param hasConnectivity {@code true} if the application was able to successfully access the
3372 * Internet using {@code network} or {@code false} if not.
3373 */
3374 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3375 printStackTrace();
3376 try {
3377 mService.reportNetworkConnectivity(network, hasConnectivity);
3378 } catch (RemoteException e) {
3379 throw e.rethrowFromSystemServer();
3380 }
3381 }
3382
3383 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003384 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003385 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003386 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3387 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3388 * accessing any network, regardless of what the settings for that network are.
3389 *
3390 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3391 * proxy is likely to break networking on multiple networks. This method is only meant
3392 * for device policy clients looking to do general internal filtering or similar use cases.
3393 *
3394 * {@see #getGlobalProxy}
3395 * {@see LinkProperties#getHttpProxy}
3396 *
3397 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3398 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003399 * @hide
3400 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003401 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003402 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003403 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003404 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003405 try {
3406 mService.setGlobalProxy(p);
3407 } catch (RemoteException e) {
3408 throw e.rethrowFromSystemServer();
3409 }
3410 }
3411
3412 /**
3413 * Retrieve any network-independent global HTTP proxy.
3414 *
3415 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3416 * if no global HTTP proxy is set.
3417 * @hide
3418 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003419 @SystemApi(client = MODULE_LIBRARIES)
3420 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003421 public ProxyInfo getGlobalProxy() {
3422 try {
3423 return mService.getGlobalProxy();
3424 } catch (RemoteException e) {
3425 throw e.rethrowFromSystemServer();
3426 }
3427 }
3428
3429 /**
3430 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3431 * network-specific HTTP proxy. If {@code network} is null, the
3432 * network-specific proxy returned is the proxy of the default active
3433 * network.
3434 *
3435 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3436 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3437 * or when {@code network} is {@code null},
3438 * the {@code ProxyInfo} for the default active network. Returns
3439 * {@code null} when no proxy applies or the caller doesn't have
3440 * permission to use {@code network}.
3441 * @hide
3442 */
3443 public ProxyInfo getProxyForNetwork(Network network) {
3444 try {
3445 return mService.getProxyForNetwork(network);
3446 } catch (RemoteException e) {
3447 throw e.rethrowFromSystemServer();
3448 }
3449 }
3450
3451 /**
3452 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3453 * otherwise if this process is bound to a {@link Network} using
3454 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3455 * the default network's proxy is returned.
3456 *
3457 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3458 * HTTP proxy is active.
3459 */
3460 @Nullable
3461 public ProxyInfo getDefaultProxy() {
3462 return getProxyForNetwork(getBoundNetworkForProcess());
3463 }
3464
3465 /**
3466 * Returns true if the hardware supports the given network type
3467 * else it returns false. This doesn't indicate we have coverage
3468 * or are authorized onto a network, just whether or not the
3469 * hardware supports it. For example a GSM phone without a SIM
3470 * should still return {@code true} for mobile data, but a wifi only
3471 * tablet would return {@code false}.
3472 *
3473 * @param networkType The network type we'd like to check
3474 * @return {@code true} if supported, else {@code false}
3475 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3476 * @hide
3477 */
3478 @Deprecated
3479 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3480 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3481 public boolean isNetworkSupported(int networkType) {
3482 try {
3483 return mService.isNetworkSupported(networkType);
3484 } catch (RemoteException e) {
3485 throw e.rethrowFromSystemServer();
3486 }
3487 }
3488
3489 /**
3490 * Returns if the currently active data network is metered. A network is
3491 * classified as metered when the user is sensitive to heavy data usage on
3492 * that connection due to monetary costs, data limitations or
3493 * battery/performance issues. You should check this before doing large
3494 * data transfers, and warn the user or delay the operation until another
3495 * network is available.
3496 *
3497 * @return {@code true} if large transfers should be avoided, otherwise
3498 * {@code false}.
3499 */
3500 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3501 public boolean isActiveNetworkMetered() {
3502 try {
3503 return mService.isActiveNetworkMetered();
3504 } catch (RemoteException e) {
3505 throw e.rethrowFromSystemServer();
3506 }
3507 }
3508
3509 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003510 * Set sign in error notification to visible or invisible
3511 *
3512 * @hide
3513 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3514 */
3515 @Deprecated
3516 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3517 String action) {
3518 try {
3519 mService.setProvisioningNotificationVisible(visible, networkType, action);
3520 } catch (RemoteException e) {
3521 throw e.rethrowFromSystemServer();
3522 }
3523 }
3524
3525 /**
3526 * Set the value for enabling/disabling airplane mode
3527 *
3528 * @param enable whether to enable airplane mode or not
3529 *
3530 * @hide
3531 */
3532 @RequiresPermission(anyOf = {
3533 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3534 android.Manifest.permission.NETWORK_SETTINGS,
3535 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3536 android.Manifest.permission.NETWORK_STACK})
3537 @SystemApi
3538 public void setAirplaneMode(boolean enable) {
3539 try {
3540 mService.setAirplaneMode(enable);
3541 } catch (RemoteException e) {
3542 throw e.rethrowFromSystemServer();
3543 }
3544 }
3545
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003546 /**
3547 * Registers the specified {@link NetworkProvider}.
3548 * Each listener must only be registered once. The listener can be unregistered with
3549 * {@link #unregisterNetworkProvider}.
3550 *
3551 * @param provider the provider to register
3552 * @return the ID of the provider. This ID must be used by the provider when registering
3553 * {@link android.net.NetworkAgent}s.
3554 * @hide
3555 */
3556 @SystemApi
3557 @RequiresPermission(anyOf = {
3558 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3559 android.Manifest.permission.NETWORK_FACTORY})
3560 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3561 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3562 throw new IllegalStateException("NetworkProviders can only be registered once");
3563 }
3564
3565 try {
3566 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3567 provider.getName());
3568 provider.setProviderId(providerId);
3569 } catch (RemoteException e) {
3570 throw e.rethrowFromSystemServer();
3571 }
3572 return provider.getProviderId();
3573 }
3574
3575 /**
3576 * Unregisters the specified NetworkProvider.
3577 *
3578 * @param provider the provider to unregister
3579 * @hide
3580 */
3581 @SystemApi
3582 @RequiresPermission(anyOf = {
3583 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3584 android.Manifest.permission.NETWORK_FACTORY})
3585 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3586 try {
3587 mService.unregisterNetworkProvider(provider.getMessenger());
3588 } catch (RemoteException e) {
3589 throw e.rethrowFromSystemServer();
3590 }
3591 provider.setProviderId(NetworkProvider.ID_NONE);
3592 }
3593
Chalard Jeand1b498b2021-01-05 08:40:09 +09003594 /**
3595 * Register or update a network offer with ConnectivityService.
3596 *
3597 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003598 * them to networking requests made by apps or the system. A callback identifies an offer
3599 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3600 * score and the capabilities of the network it might be able to bring up ; these act as
3601 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003602 * provider.
3603 *
3604 * The provider is under no obligation to be able to bring up the network it offers at any
3605 * given time. Instead, this mechanism is meant to limit requests received by providers
3606 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3607 * the quality of the network satisfying a given request to their own offer.
3608 *
3609 * An offer can be updated by calling this again with the same callback object. This is
3610 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3611 * provider with the changes caused by the changes in the offer.
3612 *
3613 * @param provider The provider making this offer.
3614 * @param score The prospective score of the network.
3615 * @param caps The prospective capabilities of the network.
3616 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003617 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003618 */
3619 @RequiresPermission(anyOf = {
3620 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3621 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003622 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003623 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3624 @NonNull final INetworkOfferCallback callback) {
3625 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003626 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003627 Objects.requireNonNull(score, "null score"),
3628 Objects.requireNonNull(caps, "null caps"),
3629 Objects.requireNonNull(callback, "null callback"));
3630 } catch (RemoteException e) {
3631 throw e.rethrowFromSystemServer();
3632 }
3633 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003634
Chalard Jeand1b498b2021-01-05 08:40:09 +09003635 /**
3636 * Withdraw a network offer made with {@link #offerNetwork}.
3637 *
3638 * @param callback The callback passed at registration time. This must be the same object
3639 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003640 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003641 */
3642 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3643 try {
3644 mService.unofferNetwork(Objects.requireNonNull(callback));
3645 } catch (RemoteException e) {
3646 throw e.rethrowFromSystemServer();
3647 }
3648 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003649 /** @hide exposed via the NetworkProvider class. */
3650 @RequiresPermission(anyOf = {
3651 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3652 android.Manifest.permission.NETWORK_FACTORY})
3653 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3654 try {
3655 mService.declareNetworkRequestUnfulfillable(request);
3656 } catch (RemoteException e) {
3657 throw e.rethrowFromSystemServer();
3658 }
3659 }
3660
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003661 /**
3662 * @hide
3663 * Register a NetworkAgent with ConnectivityService.
3664 * @return Network corresponding to NetworkAgent.
3665 */
3666 @RequiresPermission(anyOf = {
3667 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3668 android.Manifest.permission.NETWORK_FACTORY})
3669 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003670 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3671 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003672 try {
3673 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3674 } catch (RemoteException e) {
3675 throw e.rethrowFromSystemServer();
3676 }
3677 }
3678
3679 /**
3680 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3681 * changes. Should be extended by applications wanting notifications.
3682 *
3683 * A {@code NetworkCallback} is registered by calling
3684 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3685 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3686 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3687 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3688 * A {@code NetworkCallback} should be registered at most once at any time.
3689 * A {@code NetworkCallback} that has been unregistered can be registered again.
3690 */
3691 public static class NetworkCallback {
3692 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003693 * No flags associated with this callback.
3694 * @hide
3695 */
3696 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003697
Roshan Piuse08bc182020-12-22 15:10:42 -08003698 /**
lucaslinc582d502022-01-27 09:07:00 +08003699 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3700 *
3701 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3702 * Prior to Android 12, this information is always returned to apps holding the appropriate
3703 * permission, possibly noting that the app has used location.
3704 * <p>In Android 12 and above, by default the sent objects do not contain any location
3705 * information, even if the app holds the necessary permissions, and the system does not
3706 * take note of location usage by the app. Apps can request that location information is
3707 * included, in which case the system will check location permission and the location
3708 * toggle state, and take note of location usage by the app if any such information is
3709 * returned.
3710 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003711 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3712 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3713 * <p>
3714 * These include:
3715 * <li> Some transport info instances (retrieved via
3716 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3717 * contain location sensitive information.
3718 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003719 * sensitive for wifi suggestor apps (i.e using
3720 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003721 * </p>
3722 * <p>
3723 * Note:
3724 * <li> Retrieving this location sensitive information (subject to app's location
3725 * permissions) will be noted by system. </li>
3726 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003727 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003728 */
Roshan Pius189d0092021-03-11 21:16:44 -08003729 // Note: Some existing fields which are location sensitive may still be included without
3730 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003731 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3732
3733 /** @hide */
3734 @Retention(RetentionPolicy.SOURCE)
3735 @IntDef(flag = true, prefix = "FLAG_", value = {
3736 FLAG_NONE,
3737 FLAG_INCLUDE_LOCATION_INFO
3738 })
3739 public @interface Flag { }
3740
3741 /**
3742 * All the valid flags for error checking.
3743 */
3744 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3745
3746 public NetworkCallback() {
3747 this(FLAG_NONE);
3748 }
3749
3750 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003751 if ((flags & VALID_FLAGS) != flags) {
3752 throw new IllegalArgumentException("Invalid flags");
3753 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003754 mFlags = flags;
3755 }
3756
3757 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003758 * Called when the framework connects to a new network to evaluate whether it satisfies this
3759 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3760 * callback. There is no guarantee that this new network will satisfy any requests, or that
3761 * the network will stay connected for longer than the time necessary to evaluate it.
3762 * <p>
3763 * Most applications <b>should not</b> act on this callback, and should instead use
3764 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3765 * the framework in properly evaluating the network &mdash; for example, an application that
3766 * can automatically log in to a captive portal without user intervention.
3767 *
3768 * @param network The {@link Network} of the network that is being evaluated.
3769 *
3770 * @hide
3771 */
3772 public void onPreCheck(@NonNull Network network) {}
3773
3774 /**
3775 * Called when the framework connects and has declared a new network ready for use.
3776 * This callback may be called more than once if the {@link Network} that is
3777 * satisfying the request changes.
3778 *
3779 * @param network The {@link Network} of the satisfying network.
3780 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3781 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3782 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3783 * @hide
3784 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003785 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003786 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003787 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003788 // Internally only this method is called when a new network is available, and
3789 // it calls the callback in the same way and order that older versions used
3790 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003791 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3792 onBlockedStatusChanged(network, blocked);
3793 }
3794
3795 /**
3796 * Legacy variant of onAvailable that takes a boolean blocked reason.
3797 *
3798 * This method has never been public API, but it's not final, so there may be apps that
3799 * implemented it and rely on it being called. Do our best not to break them.
3800 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3801 * this method is called. There does not seem to be a way to avoid this.
3802 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3803 *
3804 * @hide
3805 */
3806 public void onAvailable(@NonNull Network network,
3807 @NonNull NetworkCapabilities networkCapabilities,
3808 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003809 onAvailable(network);
3810 if (!networkCapabilities.hasCapability(
3811 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3812 onNetworkSuspended(network);
3813 }
3814 onCapabilitiesChanged(network, networkCapabilities);
3815 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003816 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003817 }
3818
3819 /**
3820 * Called when the framework connects and has declared a new network ready for use.
3821 *
3822 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3823 * be available at the same time, and onAvailable will be called for each of these as they
3824 * appear.
3825 *
3826 * <p>For callbacks registered with {@link #requestNetwork} and
3827 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3828 * is the new best network for this request and is now tracked by this callback ; this
3829 * callback will no longer receive method calls about other networks that may have been
3830 * passed to this method previously. The previously-best network may have disconnected, or
3831 * it may still be around and the newly-best network may simply be better.
3832 *
3833 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3834 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3835 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3836 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3837 *
3838 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3839 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3840 * this callback as this is prone to race conditions (there is no guarantee the objects
3841 * returned by these methods will be current). Instead, wait for a call to
3842 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3843 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3844 * to be well-ordered with respect to other callbacks.
3845 *
3846 * @param network The {@link Network} of the satisfying network.
3847 */
3848 public void onAvailable(@NonNull Network network) {}
3849
3850 /**
3851 * Called when the network is about to be lost, typically because there are no outstanding
3852 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3853 * with the new replacement network for graceful handover. This method is not guaranteed
3854 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3855 * network is suddenly disconnected.
3856 *
3857 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3858 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3859 * this callback as this is prone to race conditions ; calling these methods while in a
3860 * callback may return an outdated or even a null object.
3861 *
3862 * @param network The {@link Network} that is about to be lost.
3863 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3864 * connected for graceful handover; note that the network may still
3865 * suffer a hard loss at any time.
3866 */
3867 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3868
3869 /**
3870 * Called when a network disconnects or otherwise no longer satisfies this request or
3871 * callback.
3872 *
3873 * <p>If the callback was registered with requestNetwork() or
3874 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3875 * returned by onAvailable() when that network is lost and no other network satisfies
3876 * the criteria of the request.
3877 *
3878 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3879 * each network which no longer satisfies the criteria of the callback.
3880 *
3881 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3882 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3883 * this callback as this is prone to race conditions ; calling these methods while in a
3884 * callback may return an outdated or even a null object.
3885 *
3886 * @param network The {@link Network} lost.
3887 */
3888 public void onLost(@NonNull Network network) {}
3889
3890 /**
3891 * Called if no network is found within the timeout time specified in
3892 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3893 * requested network request cannot be fulfilled (whether or not a timeout was
3894 * specified). When this callback is invoked the associated
3895 * {@link NetworkRequest} will have already been removed and released, as if
3896 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3897 */
3898 public void onUnavailable() {}
3899
3900 /**
3901 * Called when the network corresponding to this request changes capabilities but still
3902 * satisfies the requested criteria.
3903 *
3904 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3905 * to be called immediately after {@link #onAvailable}.
3906 *
3907 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3908 * ConnectivityManager methods in this callback as this is prone to race conditions :
3909 * calling these methods while in a callback may return an outdated or even a null object.
3910 *
3911 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003912 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003913 * network.
3914 */
3915 public void onCapabilitiesChanged(@NonNull Network network,
3916 @NonNull NetworkCapabilities networkCapabilities) {}
3917
3918 /**
3919 * Called when the network corresponding to this request changes {@link LinkProperties}.
3920 *
3921 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3922 * to be called immediately after {@link #onAvailable}.
3923 *
3924 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3925 * ConnectivityManager methods in this callback as this is prone to race conditions :
3926 * calling these methods while in a callback may return an outdated or even a null object.
3927 *
3928 * @param network The {@link Network} whose link properties have changed.
3929 * @param linkProperties The new {@link LinkProperties} for this network.
3930 */
3931 public void onLinkPropertiesChanged(@NonNull Network network,
3932 @NonNull LinkProperties linkProperties) {}
3933
3934 /**
3935 * Called when the network the framework connected to for this request suspends data
3936 * transmission temporarily.
3937 *
3938 * <p>This generally means that while the TCP connections are still live temporarily
3939 * network data fails to transfer. To give a specific example, this is used on cellular
3940 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3941 * means read operations on sockets on this network will block once the buffers are
3942 * drained, and write operations will block once the buffers are full.
3943 *
3944 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3945 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3946 * this callback as this is prone to race conditions (there is no guarantee the objects
3947 * returned by these methods will be current).
3948 *
3949 * @hide
3950 */
3951 public void onNetworkSuspended(@NonNull Network network) {}
3952
3953 /**
3954 * Called when the network the framework connected to for this request
3955 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3956 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3957
3958 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3959 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3960 * this callback as this is prone to race conditions : calling these methods while in a
3961 * callback may return an outdated or even a null object.
3962 *
3963 * @hide
3964 */
3965 public void onNetworkResumed(@NonNull Network network) {}
3966
3967 /**
3968 * Called when access to the specified network is blocked or unblocked.
3969 *
3970 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3971 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3972 * this callback as this is prone to race conditions : calling these methods while in a
3973 * callback may return an outdated or even a null object.
3974 *
3975 * @param network The {@link Network} whose blocked status has changed.
3976 * @param blocked The blocked status of this {@link Network}.
3977 */
3978 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3979
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003980 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09003981 * Called when access to the specified network is blocked or unblocked, or the reason for
3982 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003983 *
3984 * If a NetworkCallback object implements this method,
3985 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3986 *
3987 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3988 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3989 * this callback as this is prone to race conditions : calling these methods while in a
3990 * callback may return an outdated or even a null object.
3991 *
3992 * @param network The {@link Network} whose blocked status has changed.
3993 * @param blocked The blocked status of this {@link Network}.
3994 * @hide
3995 */
3996 @SystemApi(client = MODULE_LIBRARIES)
3997 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3998 onBlockedStatusChanged(network, blocked != 0);
3999 }
4000
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004001 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004002 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004003 }
4004
4005 /**
4006 * Constant error codes used by ConnectivityService to communicate about failures and errors
4007 * across a Binder boundary.
4008 * @hide
4009 */
4010 public interface Errors {
4011 int TOO_MANY_REQUESTS = 1;
4012 }
4013
4014 /** @hide */
4015 public static class TooManyRequestsException extends RuntimeException {}
4016
4017 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4018 switch (e.errorCode) {
4019 case Errors.TOO_MANY_REQUESTS:
4020 return new TooManyRequestsException();
4021 default:
4022 Log.w(TAG, "Unknown service error code " + e.errorCode);
4023 return new RuntimeException(e);
4024 }
4025 }
4026
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004027 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004028 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004029 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004030 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004031 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004032 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004033 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004034 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004035 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004036 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004037 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004038 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004039 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004040 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004041 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004042 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004043 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004044 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004045 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004046 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004047 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004048 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004049
4050 /** @hide */
4051 public static String getCallbackName(int whichCallback) {
4052 switch (whichCallback) {
4053 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4054 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4055 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4056 case CALLBACK_LOST: return "CALLBACK_LOST";
4057 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4058 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4059 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4060 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4061 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4062 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4063 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4064 default:
4065 return Integer.toString(whichCallback);
4066 }
4067 }
4068
4069 private class CallbackHandler extends Handler {
4070 private static final String TAG = "ConnectivityManager.CallbackHandler";
4071 private static final boolean DBG = false;
4072
4073 CallbackHandler(Looper looper) {
4074 super(looper);
4075 }
4076
4077 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004078 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004079 }
4080
4081 @Override
4082 public void handleMessage(Message message) {
4083 if (message.what == EXPIRE_LEGACY_REQUEST) {
4084 expireRequest((NetworkCapabilities) message.obj, message.arg1);
4085 return;
4086 }
4087
4088 final NetworkRequest request = getObject(message, NetworkRequest.class);
4089 final Network network = getObject(message, Network.class);
4090 final NetworkCallback callback;
4091 synchronized (sCallbacks) {
4092 callback = sCallbacks.get(request);
4093 if (callback == null) {
4094 Log.w(TAG,
4095 "callback not found for " + getCallbackName(message.what) + " message");
4096 return;
4097 }
4098 if (message.what == CALLBACK_UNAVAIL) {
4099 sCallbacks.remove(request);
4100 callback.networkRequest = ALREADY_UNREGISTERED;
4101 }
4102 }
4103 if (DBG) {
4104 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4105 }
4106
4107 switch (message.what) {
4108 case CALLBACK_PRECHECK: {
4109 callback.onPreCheck(network);
4110 break;
4111 }
4112 case CALLBACK_AVAILABLE: {
4113 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4114 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004115 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004116 break;
4117 }
4118 case CALLBACK_LOSING: {
4119 callback.onLosing(network, message.arg1);
4120 break;
4121 }
4122 case CALLBACK_LOST: {
4123 callback.onLost(network);
4124 break;
4125 }
4126 case CALLBACK_UNAVAIL: {
4127 callback.onUnavailable();
4128 break;
4129 }
4130 case CALLBACK_CAP_CHANGED: {
4131 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4132 callback.onCapabilitiesChanged(network, cap);
4133 break;
4134 }
4135 case CALLBACK_IP_CHANGED: {
4136 LinkProperties lp = getObject(message, LinkProperties.class);
4137 callback.onLinkPropertiesChanged(network, lp);
4138 break;
4139 }
4140 case CALLBACK_SUSPENDED: {
4141 callback.onNetworkSuspended(network);
4142 break;
4143 }
4144 case CALLBACK_RESUMED: {
4145 callback.onNetworkResumed(network);
4146 break;
4147 }
4148 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004149 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004150 }
4151 }
4152 }
4153
4154 private <T> T getObject(Message msg, Class<T> c) {
4155 return (T) msg.getData().getParcelable(c.getSimpleName());
4156 }
4157 }
4158
4159 private CallbackHandler getDefaultHandler() {
4160 synchronized (sCallbacks) {
4161 if (sCallbackHandler == null) {
4162 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4163 }
4164 return sCallbackHandler;
4165 }
4166 }
4167
4168 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4169 private static CallbackHandler sCallbackHandler;
4170
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004171 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4172 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4173 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004174 printStackTrace();
4175 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004176 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4177 throw new IllegalArgumentException("null NetworkCapabilities");
4178 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004179 final NetworkRequest request;
4180 final String callingPackageName = mContext.getOpPackageName();
4181 try {
4182 synchronized(sCallbacks) {
4183 if (callback.networkRequest != null
4184 && callback.networkRequest != ALREADY_UNREGISTERED) {
4185 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4186 // and requests (http://b/20701525).
4187 Log.e(TAG, "NetworkCallback was already registered");
4188 }
4189 Messenger messenger = new Messenger(handler);
4190 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004191 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004192 if (reqType == LISTEN) {
4193 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004194 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004195 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004196 } else {
4197 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004198 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4199 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004200 }
4201 if (request != null) {
4202 sCallbacks.put(request, callback);
4203 }
4204 callback.networkRequest = request;
4205 }
4206 } catch (RemoteException e) {
4207 throw e.rethrowFromSystemServer();
4208 } catch (ServiceSpecificException e) {
4209 throw convertServiceException(e);
4210 }
4211 return request;
4212 }
4213
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004214 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4215 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4216 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4217 legacyType, handler);
4218 }
4219
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004220 /**
4221 * Helper function to request a network with a particular legacy type.
4222 *
4223 * This API is only for use in internal system code that requests networks with legacy type and
4224 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4225 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4226 *
4227 * @param request {@link NetworkRequest} describing this request.
4228 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4229 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4230 * be a positive value (i.e. >0).
4231 * @param legacyType to specify the network type(#TYPE_*).
4232 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4233 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4234 * the callback must not be shared - it uniquely specifies this request.
4235 *
4236 * @hide
4237 */
4238 @SystemApi
4239 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4240 public void requestNetwork(@NonNull NetworkRequest request,
4241 int timeoutMs, int legacyType, @NonNull Handler handler,
4242 @NonNull NetworkCallback networkCallback) {
4243 if (legacyType == TYPE_NONE) {
4244 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4245 }
4246 CallbackHandler cbHandler = new CallbackHandler(handler);
4247 NetworkCapabilities nc = request.networkCapabilities;
4248 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4249 }
4250
4251 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004252 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004253 *
4254 * <p>This method will attempt to find the best network that matches the passed
4255 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4256 * criteria. The platform will evaluate which network is the best at its own discretion.
4257 * Throughput, latency, cost per byte, policy, user preference and other considerations
4258 * may be factored in the decision of what is considered the best network.
4259 *
4260 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4261 * matching this request, while always attempting to match the request to a better network if
4262 * possible. If a better match is found, the platform will switch this request to the now-best
4263 * network and inform the app of the newly best network by invoking
4264 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4265 * will not try to maintain any other network than the best one currently matching the request:
4266 * a network not matching any network request may be disconnected at any time.
4267 *
4268 * <p>For example, an application could use this method to obtain a connected cellular network
4269 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4270 * radio to consume additional power. Or, an application could inform the system that it wants
4271 * a network supporting sending MMSes and have the system let it know about the currently best
4272 * MMS-supporting network through the provided {@link NetworkCallback}.
4273 *
4274 * <p>The status of the request can be followed by listening to the various callbacks described
4275 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4276 * used to direct traffic to the network (although accessing some networks may be subject to
4277 * holding specific permissions). Callers will learn about the specific characteristics of the
4278 * network through
4279 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4280 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4281 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4282 * matching the request at any given time; therefore when a better network matching the request
4283 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4284 * with the new network after which no further updates are given about the previously-best
4285 * network, unless it becomes the best again at some later time. All callbacks are invoked
4286 * in order on the same thread, which by default is a thread created by the framework running
4287 * in the app.
4288 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4289 * callbacks are invoked.
4290 *
4291 * <p>This{@link NetworkRequest} will live until released via
4292 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4293 * which point the system may let go of the network at any time.
4294 *
4295 * <p>A version of this method which takes a timeout is
4296 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4297 * wait for a limited amount of time for the network to become unavailable.
4298 *
4299 * <p>It is presently unsupported to request a network with mutable
4300 * {@link NetworkCapabilities} such as
4301 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4302 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4303 * as these {@code NetworkCapabilities} represent states that a particular
4304 * network may never attain, and whether a network will attain these states
4305 * is unknown prior to bringing up the network so the framework does not
4306 * know how to go about satisfying a request with these capabilities.
4307 *
4308 * <p>This method requires the caller to hold either the
4309 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4310 * or the ability to modify system settings as determined by
4311 * {@link android.provider.Settings.System#canWrite}.</p>
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 #registerNetworkCallback} 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} to be utilized for this request. Note
4324 * the callback must not be shared - it uniquely specifies this request.
4325 * The callback is invoked on the default internal Handler.
4326 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4327 * @throws SecurityException if missing the appropriate permissions.
4328 * @throws RuntimeException if the app already has too many callbacks registered.
4329 */
4330 public void requestNetwork(@NonNull NetworkRequest request,
4331 @NonNull NetworkCallback networkCallback) {
4332 requestNetwork(request, networkCallback, getDefaultHandler());
4333 }
4334
4335 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004336 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004337 *
4338 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4339 * but runs all the callbacks on the passed Handler.
4340 *
4341 * <p>This method has the same permission requirements as
4342 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4343 * and throws the same exceptions in the same conditions.
4344 *
4345 * @param request {@link NetworkRequest} describing this request.
4346 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4347 * the callback must not be shared - it uniquely specifies this request.
4348 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4349 */
4350 public void requestNetwork(@NonNull NetworkRequest request,
4351 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4352 CallbackHandler cbHandler = new CallbackHandler(handler);
4353 NetworkCapabilities nc = request.networkCapabilities;
4354 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4355 }
4356
4357 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004358 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004359 * by a timeout.
4360 *
4361 * This function behaves identically to the non-timed-out version
4362 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4363 * is not found within the given time (in milliseconds) the
4364 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4365 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4366 * not have to be released if timed-out (it is automatically released). Unregistering a
4367 * request that timed out is not an error.
4368 *
4369 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4370 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4371 * for that purpose. Calling this method will attempt to bring up the requested network.
4372 *
4373 * <p>This method has the same permission requirements as
4374 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4375 * and throws the same exceptions in the same conditions.
4376 *
4377 * @param request {@link NetworkRequest} describing this request.
4378 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4379 * the callback must not be shared - it uniquely specifies this request.
4380 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4381 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4382 * be a positive value (i.e. >0).
4383 */
4384 public void requestNetwork(@NonNull NetworkRequest request,
4385 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4386 checkTimeout(timeoutMs);
4387 NetworkCapabilities nc = request.networkCapabilities;
4388 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4389 getDefaultHandler());
4390 }
4391
4392 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004393 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004394 * by a timeout.
4395 *
4396 * This method behaves identically to
4397 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4398 * on the passed Handler.
4399 *
4400 * <p>This method has the same permission requirements as
4401 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4402 * and throws the same exceptions in the same conditions.
4403 *
4404 * @param request {@link NetworkRequest} describing this request.
4405 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4406 * the callback must not be shared - it uniquely specifies this request.
4407 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4408 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4409 * before {@link NetworkCallback#onUnavailable} is called.
4410 */
4411 public void requestNetwork(@NonNull NetworkRequest request,
4412 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4413 checkTimeout(timeoutMs);
4414 CallbackHandler cbHandler = new CallbackHandler(handler);
4415 NetworkCapabilities nc = request.networkCapabilities;
4416 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4417 }
4418
4419 /**
4420 * The lookup key for a {@link Network} object included with the intent after
4421 * successfully finding a network for the applications request. Retrieve it with
4422 * {@link android.content.Intent#getParcelableExtra(String)}.
4423 * <p>
4424 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4425 * then you must get a ConnectivityManager instance before doing so.
4426 */
4427 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4428
4429 /**
4430 * The lookup key for a {@link NetworkRequest} object included with the intent after
4431 * successfully finding a network for the applications request. Retrieve it with
4432 * {@link android.content.Intent#getParcelableExtra(String)}.
4433 */
4434 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4435
4436
4437 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004438 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004439 *
4440 * This function behaves identically to the version that takes a NetworkCallback, but instead
4441 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4442 * the request may outlive the calling application and get called back when a suitable
4443 * network is found.
4444 * <p>
4445 * The operation is an Intent broadcast that goes to a broadcast receiver that
4446 * you registered with {@link Context#registerReceiver} or through the
4447 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4448 * <p>
4449 * The operation Intent is delivered with two extras, a {@link Network} typed
4450 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4451 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4452 * the original requests parameters. It is important to create a new,
4453 * {@link NetworkCallback} based request before completing the processing of the
4454 * Intent to reserve the network or it will be released shortly after the Intent
4455 * is processed.
4456 * <p>
4457 * If there is already a request for this Intent registered (with the equality of
4458 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4459 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4460 * <p>
4461 * The request may be released normally by calling
4462 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4463 * <p>It is presently unsupported to request a network with either
4464 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4465 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4466 * as these {@code NetworkCapabilities} represent states that a particular
4467 * network may never attain, and whether a network will attain these states
4468 * is unknown prior to bringing up the network so the framework does not
4469 * know how to go about satisfying a request with these capabilities.
4470 *
4471 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4472 * number of outstanding requests to 100 per app (identified by their UID), shared with
4473 * all variants of this method, of {@link #registerNetworkCallback} as well as
4474 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4475 * Requesting a network with this method will count toward this limit. If this limit is
4476 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4477 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4478 * or {@link #releaseNetworkRequest(PendingIntent)}.
4479 *
4480 * <p>This method requires the caller to hold either the
4481 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4482 * or the ability to modify system settings as determined by
4483 * {@link android.provider.Settings.System#canWrite}.</p>
4484 *
4485 * @param request {@link NetworkRequest} describing this request.
4486 * @param operation Action to perform when the network is available (corresponds
4487 * to the {@link NetworkCallback#onAvailable} call. Typically
4488 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4489 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4490 * @throws SecurityException if missing the appropriate permissions.
4491 * @throws RuntimeException if the app already has too many callbacks registered.
4492 */
4493 public void requestNetwork(@NonNull NetworkRequest request,
4494 @NonNull PendingIntent operation) {
4495 printStackTrace();
4496 checkPendingIntentNotNull(operation);
4497 try {
4498 mService.pendingRequestForNetwork(
4499 request.networkCapabilities, operation, mContext.getOpPackageName(),
4500 getAttributionTag());
4501 } catch (RemoteException e) {
4502 throw e.rethrowFromSystemServer();
4503 } catch (ServiceSpecificException e) {
4504 throw convertServiceException(e);
4505 }
4506 }
4507
4508 /**
4509 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4510 * <p>
4511 * This method has the same behavior as
4512 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4513 * releasing network resources and disconnecting.
4514 *
4515 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4516 * PendingIntent passed to
4517 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4518 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4519 */
4520 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4521 printStackTrace();
4522 checkPendingIntentNotNull(operation);
4523 try {
4524 mService.releasePendingNetworkRequest(operation);
4525 } catch (RemoteException e) {
4526 throw e.rethrowFromSystemServer();
4527 }
4528 }
4529
4530 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004531 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004532 }
4533
4534 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004535 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004536 }
4537
4538 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004539 if (timeoutMs <= 0) {
4540 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4541 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004542 }
4543
4544 /**
4545 * Registers to receive notifications about all networks which satisfy the given
4546 * {@link NetworkRequest}. The callbacks will continue to be called until
4547 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4548 * called.
4549 *
4550 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4551 * number of outstanding requests to 100 per app (identified by their UID), shared with
4552 * all variants of this method, of {@link #requestNetwork} as well as
4553 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4554 * Requesting a network with this method will count toward this limit. If this limit is
4555 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4556 * make sure to unregister the callbacks with
4557 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4558 *
4559 * @param request {@link NetworkRequest} describing this request.
4560 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4561 * networks change state.
4562 * The callback is invoked on the default internal Handler.
4563 * @throws RuntimeException if the app already has too many callbacks registered.
4564 */
4565 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4566 public void registerNetworkCallback(@NonNull NetworkRequest request,
4567 @NonNull NetworkCallback networkCallback) {
4568 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4569 }
4570
4571 /**
4572 * Registers to receive notifications about all networks which satisfy the given
4573 * {@link NetworkRequest}. The callbacks will continue to be called until
4574 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4575 * called.
4576 *
4577 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4578 * number of outstanding requests to 100 per app (identified by their UID), shared with
4579 * all variants of this method, of {@link #requestNetwork} as well as
4580 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4581 * Requesting a network with this method will count toward this limit. If this limit is
4582 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4583 * make sure to unregister the callbacks with
4584 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4585 *
4586 *
4587 * @param request {@link NetworkRequest} describing this request.
4588 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4589 * networks change state.
4590 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4591 * @throws RuntimeException if the app already has too many callbacks registered.
4592 */
4593 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4594 public void registerNetworkCallback(@NonNull NetworkRequest request,
4595 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4596 CallbackHandler cbHandler = new CallbackHandler(handler);
4597 NetworkCapabilities nc = request.networkCapabilities;
4598 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4599 }
4600
4601 /**
4602 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4603 * {@link NetworkRequest}.
4604 *
4605 * This function behaves identically to the version that takes a NetworkCallback, but instead
4606 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4607 * the request may outlive the calling application and get called back when a suitable
4608 * network is found.
4609 * <p>
4610 * The operation is an Intent broadcast that goes to a broadcast receiver that
4611 * you registered with {@link Context#registerReceiver} or through the
4612 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4613 * <p>
4614 * The operation Intent is delivered with two extras, a {@link Network} typed
4615 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4616 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4617 * the original requests parameters.
4618 * <p>
4619 * If there is already a request for this Intent registered (with the equality of
4620 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4621 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4622 * <p>
4623 * The request may be released normally by calling
4624 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4625 *
4626 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4627 * number of outstanding requests to 100 per app (identified by their UID), shared with
4628 * all variants of this method, of {@link #requestNetwork} as well as
4629 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4630 * Requesting a network with this method will count toward this limit. If this limit is
4631 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4632 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4633 * or {@link #releaseNetworkRequest(PendingIntent)}.
4634 *
4635 * @param request {@link NetworkRequest} describing this request.
4636 * @param operation Action to perform when the network is available (corresponds
4637 * to the {@link NetworkCallback#onAvailable} call. Typically
4638 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4639 * @throws RuntimeException if the app already has too many callbacks registered.
4640 */
4641 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4642 public void registerNetworkCallback(@NonNull NetworkRequest request,
4643 @NonNull PendingIntent operation) {
4644 printStackTrace();
4645 checkPendingIntentNotNull(operation);
4646 try {
4647 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004648 request.networkCapabilities, operation, mContext.getOpPackageName(),
4649 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004650 } catch (RemoteException e) {
4651 throw e.rethrowFromSystemServer();
4652 } catch (ServiceSpecificException e) {
4653 throw convertServiceException(e);
4654 }
4655 }
4656
4657 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004658 * Registers to receive notifications about changes in the application's default network. This
4659 * may be a physical network or a virtual network, such as a VPN that applies to the
4660 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004661 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4662 *
4663 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4664 * number of outstanding requests to 100 per app (identified by their UID), shared with
4665 * all variants of this method, of {@link #requestNetwork} as well as
4666 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4667 * Requesting a network with this method will count toward this limit. If this limit is
4668 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4669 * make sure to unregister the callbacks with
4670 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4671 *
4672 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004673 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004674 * The callback is invoked on the default internal Handler.
4675 * @throws RuntimeException if the app already has too many callbacks registered.
4676 */
4677 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4678 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4679 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4680 }
4681
4682 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004683 * Registers to receive notifications about changes in the application's default network. This
4684 * may be a physical network or a virtual network, such as a VPN that applies to the
4685 * application. The callbacks will continue to be called until either the application exits or
4686 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4687 *
4688 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4689 * number of outstanding requests to 100 per app (identified by their UID), shared with
4690 * all variants of this method, of {@link #requestNetwork} as well as
4691 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4692 * Requesting a network with this method will count toward this limit. If this limit is
4693 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4694 * make sure to unregister the callbacks with
4695 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4696 *
4697 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4698 * application's default network changes.
4699 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4700 * @throws RuntimeException if the app already has too many callbacks registered.
4701 */
4702 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4703 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4704 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004705 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004706 }
4707
4708 /**
4709 * Registers to receive notifications about changes in the default network for the specified
4710 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4711 * UID. The callbacks will continue to be called until either the application exits or
4712 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4713 *
4714 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4715 * number of outstanding requests to 100 per app (identified by their UID), shared with
4716 * all variants of this method, of {@link #requestNetwork} as well as
4717 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4718 * Requesting a network with this method will count toward this limit. If this limit is
4719 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4720 * make sure to unregister the callbacks with
4721 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4722 *
4723 * @param uid the UID for which to track default network changes.
4724 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4725 * UID's default network changes.
4726 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4727 * @throws RuntimeException if the app already has too many callbacks registered.
4728 * @hide
4729 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004730 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004731 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4732 @RequiresPermission(anyOf = {
4733 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4734 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004735 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004736 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004737 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004738 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004739 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4740 }
4741
4742 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004743 * Registers to receive notifications about changes in the system default network. The callbacks
4744 * will continue to be called until either the application exits or
4745 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4746 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004747 * This method should not be used to determine networking state seen by applications, because in
4748 * many cases, most or even all application traffic may not use the default network directly,
4749 * and traffic from different applications may go on different networks by default. As an
4750 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4751 * and not onto the system default network. Applications or system components desiring to do
4752 * determine network state as seen by applications should use other methods such as
4753 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4754 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004755 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4756 * number of outstanding requests to 100 per app (identified by their UID), shared with
4757 * all variants of this method, of {@link #requestNetwork} as well as
4758 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4759 * Requesting a network with this method will count toward this limit. If this limit is
4760 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4761 * make sure to unregister the callbacks with
4762 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4763 *
4764 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4765 * system default network changes.
4766 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4767 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004768 *
4769 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004770 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004771 @SystemApi(client = MODULE_LIBRARIES)
4772 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4773 @RequiresPermission(anyOf = {
4774 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4775 android.Manifest.permission.NETWORK_SETTINGS})
4776 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004777 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004778 CallbackHandler cbHandler = new CallbackHandler(handler);
4779 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004780 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004781 }
4782
4783 /**
junyulaibd123062021-03-15 11:48:48 +08004784 * Registers to receive notifications about the best matching network which satisfy the given
4785 * {@link NetworkRequest}. The callbacks will continue to be called until
4786 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4787 * called.
4788 *
4789 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4790 * number of outstanding requests to 100 per app (identified by their UID), shared with
4791 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4792 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4793 * Requesting a network with this method will count toward this limit. If this limit is
4794 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4795 * make sure to unregister the callbacks with
4796 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4797 *
4798 *
4799 * @param request {@link NetworkRequest} describing this request.
4800 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4801 * networks change state.
4802 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4803 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004804 */
junyulai5a5c99b2021-03-05 15:51:17 +08004805 @SuppressLint("ExecutorRegistration")
4806 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4807 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4808 final NetworkCapabilities nc = request.networkCapabilities;
4809 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004810 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004811 }
4812
4813 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004814 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4815 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4816 * network connection for updated bandwidth information. The caller will be notified via
4817 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4818 * method assumes that the caller has previously called
4819 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4820 * changes.
4821 *
4822 * @param network {@link Network} specifying which network you're interested.
4823 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4824 */
4825 public boolean requestBandwidthUpdate(@NonNull Network network) {
4826 try {
4827 return mService.requestBandwidthUpdate(network);
4828 } catch (RemoteException e) {
4829 throw e.rethrowFromSystemServer();
4830 }
4831 }
4832
4833 /**
4834 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4835 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4836 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4837 * If the given {@code NetworkCallback} had previously been used with
4838 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4839 * will be disconnected.
4840 *
4841 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4842 * triggering it as soon as this call returns.
4843 *
4844 * @param networkCallback The {@link NetworkCallback} used when making the request.
4845 */
4846 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4847 printStackTrace();
4848 checkCallbackNotNull(networkCallback);
4849 final List<NetworkRequest> reqs = new ArrayList<>();
4850 // Find all requests associated to this callback and stop callback triggers immediately.
4851 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4852 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004853 if (networkCallback.networkRequest == null) {
4854 throw new IllegalArgumentException("NetworkCallback was not registered");
4855 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004856 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4857 Log.d(TAG, "NetworkCallback was already unregistered");
4858 return;
4859 }
4860 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4861 if (e.getValue() == networkCallback) {
4862 reqs.add(e.getKey());
4863 }
4864 }
4865 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4866 for (NetworkRequest r : reqs) {
4867 try {
4868 mService.releaseNetworkRequest(r);
4869 } catch (RemoteException e) {
4870 throw e.rethrowFromSystemServer();
4871 }
4872 // Only remove mapping if rpc was successful.
4873 sCallbacks.remove(r);
4874 }
4875 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4876 }
4877 }
4878
4879 /**
4880 * Unregisters a callback previously registered via
4881 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4882 *
4883 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4884 * PendingIntent passed to
4885 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4886 * Cannot be null.
4887 */
4888 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4889 releaseNetworkRequest(operation);
4890 }
4891
4892 /**
4893 * Informs the system whether it should switch to {@code network} regardless of whether it is
4894 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4895 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4896 * the system default network regardless of any other network that's currently connected. If
4897 * {@code always} is true, then the choice is remembered, so that the next time the user
4898 * connects to this network, the system will switch to it.
4899 *
4900 * @param network The network to accept.
4901 * @param accept Whether to accept the network even if unvalidated.
4902 * @param always Whether to remember this choice in the future.
4903 *
4904 * @hide
4905 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004906 @SystemApi(client = MODULE_LIBRARIES)
4907 @RequiresPermission(anyOf = {
4908 android.Manifest.permission.NETWORK_SETTINGS,
4909 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4910 android.Manifest.permission.NETWORK_STACK,
4911 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4912 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004913 try {
4914 mService.setAcceptUnvalidated(network, accept, always);
4915 } catch (RemoteException e) {
4916 throw e.rethrowFromSystemServer();
4917 }
4918 }
4919
4920 /**
4921 * Informs the system whether it should consider the network as validated even if it only has
4922 * partial connectivity. If {@code accept} is true, then the network will be considered as
4923 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4924 * is remembered, so that the next time the user connects to this network, the system will
4925 * switch to it.
4926 *
4927 * @param network The network to accept.
4928 * @param accept Whether to consider the network as validated even if it has partial
4929 * connectivity.
4930 * @param always Whether to remember this choice in the future.
4931 *
4932 * @hide
4933 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004934 @SystemApi(client = MODULE_LIBRARIES)
4935 @RequiresPermission(anyOf = {
4936 android.Manifest.permission.NETWORK_SETTINGS,
4937 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4938 android.Manifest.permission.NETWORK_STACK,
4939 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4940 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4941 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004942 try {
4943 mService.setAcceptPartialConnectivity(network, accept, always);
4944 } catch (RemoteException e) {
4945 throw e.rethrowFromSystemServer();
4946 }
4947 }
4948
4949 /**
4950 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4951 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4952 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4953 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4954 *
4955 * @param network The network to accept.
4956 *
4957 * @hide
4958 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004959 @SystemApi(client = MODULE_LIBRARIES)
4960 @RequiresPermission(anyOf = {
4961 android.Manifest.permission.NETWORK_SETTINGS,
4962 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4963 android.Manifest.permission.NETWORK_STACK,
4964 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4965 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004966 try {
4967 mService.setAvoidUnvalidated(network);
4968 } catch (RemoteException e) {
4969 throw e.rethrowFromSystemServer();
4970 }
4971 }
4972
4973 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004974 * Temporarily allow bad wifi to override {@code config_networkAvoidBadWifi} configuration.
4975 *
4976 * @param timeMs The expired current time. The value should be set within a limited time from
4977 * now.
4978 *
4979 * @hide
4980 */
4981 public void setTestAllowBadWifiUntil(long timeMs) {
4982 try {
4983 mService.setTestAllowBadWifiUntil(timeMs);
4984 } catch (RemoteException e) {
4985 throw e.rethrowFromSystemServer();
4986 }
4987 }
4988
4989 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004990 * Requests that the system open the captive portal app on the specified network.
4991 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004992 * <p>This is to be used on networks where a captive portal was detected, as per
4993 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4994 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004995 * @param network The network to log into.
4996 *
4997 * @hide
4998 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004999 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5000 @RequiresPermission(anyOf = {
5001 android.Manifest.permission.NETWORK_SETTINGS,
5002 android.Manifest.permission.NETWORK_STACK,
5003 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5004 })
5005 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005006 try {
5007 mService.startCaptivePortalApp(network);
5008 } catch (RemoteException e) {
5009 throw e.rethrowFromSystemServer();
5010 }
5011 }
5012
5013 /**
5014 * Requests that the system open the captive portal app with the specified extras.
5015 *
5016 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5017 * corresponding permission.
5018 * @param network Network on which the captive portal was detected.
5019 * @param appExtras Extras to include in the app start intent.
5020 * @hide
5021 */
5022 @SystemApi
5023 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5024 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5025 try {
5026 mService.startCaptivePortalAppInternal(network, appExtras);
5027 } catch (RemoteException e) {
5028 throw e.rethrowFromSystemServer();
5029 }
5030 }
5031
5032 /**
5033 * Determine whether the device is configured to avoid bad wifi.
5034 * @hide
5035 */
5036 @SystemApi
5037 @RequiresPermission(anyOf = {
5038 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5039 android.Manifest.permission.NETWORK_STACK})
5040 public boolean shouldAvoidBadWifi() {
5041 try {
5042 return mService.shouldAvoidBadWifi();
5043 } catch (RemoteException e) {
5044 throw e.rethrowFromSystemServer();
5045 }
5046 }
5047
5048 /**
5049 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5050 * time-sensitive user-facing operations when the system default network is temporarily
5051 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5052 * this method), and the operation should be infrequent to ensure that data usage is limited.
5053 *
5054 * An example of such an operation might be a time-sensitive foreground activity, such as a
5055 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5056 */
5057 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5058
5059 /**
5060 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5061 * a backup channel for traffic that is primarily going over another network.
5062 *
5063 * An example might be maintaining backup connections to peers or servers for the purpose of
5064 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5065 * on backup paths should be negligible compared to the traffic on the main path.
5066 */
5067 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5068
5069 /**
5070 * It is acceptable to use metered data to improve network latency and performance.
5071 */
5072 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5073
5074 /**
5075 * Return value to use for unmetered networks. On such networks we currently set all the flags
5076 * to true.
5077 * @hide
5078 */
5079 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5080 MULTIPATH_PREFERENCE_HANDOVER |
5081 MULTIPATH_PREFERENCE_RELIABILITY |
5082 MULTIPATH_PREFERENCE_PERFORMANCE;
5083
Aaron Huangcff22942021-05-27 16:31:26 +08005084 /** @hide */
5085 @Retention(RetentionPolicy.SOURCE)
5086 @IntDef(flag = true, value = {
5087 MULTIPATH_PREFERENCE_HANDOVER,
5088 MULTIPATH_PREFERENCE_RELIABILITY,
5089 MULTIPATH_PREFERENCE_PERFORMANCE,
5090 })
5091 public @interface MultipathPreference {
5092 }
5093
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005094 /**
5095 * Provides a hint to the calling application on whether it is desirable to use the
5096 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5097 * for multipath data transfer on this network when it is not the system default network.
5098 * Applications desiring to use multipath network protocols should call this method before
5099 * each such operation.
5100 *
5101 * @param network The network on which the application desires to use multipath data.
5102 * If {@code null}, this method will return the a preference that will generally
5103 * apply to metered networks.
5104 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
5105 */
5106 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5107 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5108 try {
5109 return mService.getMultipathPreference(network);
5110 } catch (RemoteException e) {
5111 throw e.rethrowFromSystemServer();
5112 }
5113 }
5114
5115 /**
5116 * Resets all connectivity manager settings back to factory defaults.
5117 * @hide
5118 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005119 @SystemApi(client = MODULE_LIBRARIES)
5120 @RequiresPermission(anyOf = {
5121 android.Manifest.permission.NETWORK_SETTINGS,
5122 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005123 public void factoryReset() {
5124 try {
5125 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005126 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005127 } catch (RemoteException e) {
5128 throw e.rethrowFromSystemServer();
5129 }
5130 }
5131
5132 /**
5133 * Binds the current process to {@code network}. All Sockets created in the future
5134 * (and not explicitly bound via a bound SocketFactory from
5135 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5136 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5137 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5138 * work and all host name resolutions will fail. This is by design so an application doesn't
5139 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5140 * To clear binding pass {@code null} for {@code network}. Using individually bound
5141 * Sockets created by Network.getSocketFactory().createSocket() and
5142 * performing network-specific host name resolutions via
5143 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5144 * {@code bindProcessToNetwork}.
5145 *
5146 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5147 * the current binding.
5148 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5149 */
5150 public boolean bindProcessToNetwork(@Nullable Network network) {
5151 // Forcing callers to call through non-static function ensures ConnectivityManager
5152 // instantiated.
5153 return setProcessDefaultNetwork(network);
5154 }
5155
5156 /**
5157 * Binds the current process to {@code network}. All Sockets created in the future
5158 * (and not explicitly bound via a bound SocketFactory from
5159 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5160 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5161 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5162 * work and all host name resolutions will fail. This is by design so an application doesn't
5163 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5164 * To clear binding pass {@code null} for {@code network}. Using individually bound
5165 * Sockets created by Network.getSocketFactory().createSocket() and
5166 * performing network-specific host name resolutions via
5167 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5168 * {@code setProcessDefaultNetwork}.
5169 *
5170 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5171 * the current binding.
5172 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5173 * @deprecated This function can throw {@link IllegalStateException}. Use
5174 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5175 * is a direct replacement.
5176 */
5177 @Deprecated
5178 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5179 int netId = (network == null) ? NETID_UNSET : network.netId;
5180 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5181
5182 if (netId != NETID_UNSET) {
5183 netId = network.getNetIdForResolv();
5184 }
5185
5186 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5187 return false;
5188 }
5189
5190 if (!isSameNetId) {
5191 // Set HTTP proxy system properties to match network.
5192 // TODO: Deprecate this static method and replace it with a non-static version.
5193 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005194 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005195 } catch (SecurityException e) {
5196 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5197 Log.e(TAG, "Can't set proxy properties", e);
5198 }
5199 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005200 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005201 // Must flush socket pool as idle sockets will be bound to previous network and may
5202 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005203 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005204 }
5205
5206 return true;
5207 }
5208
5209 /**
5210 * Returns the {@link Network} currently bound to this process via
5211 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5212 *
5213 * @return {@code Network} to which this process is bound, or {@code null}.
5214 */
5215 @Nullable
5216 public Network getBoundNetworkForProcess() {
5217 // Forcing callers to call thru non-static function ensures ConnectivityManager
5218 // instantiated.
5219 return getProcessDefaultNetwork();
5220 }
5221
5222 /**
5223 * Returns the {@link Network} currently bound to this process via
5224 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5225 *
5226 * @return {@code Network} to which this process is bound, or {@code null}.
5227 * @deprecated Using this function can lead to other functions throwing
5228 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5229 * {@code getBoundNetworkForProcess} is a direct replacement.
5230 */
5231 @Deprecated
5232 @Nullable
5233 public static Network getProcessDefaultNetwork() {
5234 int netId = NetworkUtils.getBoundNetworkForProcess();
5235 if (netId == NETID_UNSET) return null;
5236 return new Network(netId);
5237 }
5238
5239 private void unsupportedStartingFrom(int version) {
5240 if (Process.myUid() == Process.SYSTEM_UID) {
5241 // The getApplicationInfo() call we make below is not supported in system context. Let
5242 // the call through here, and rely on the fact that ConnectivityService will refuse to
5243 // allow the system to use these APIs anyway.
5244 return;
5245 }
5246
5247 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5248 throw new UnsupportedOperationException(
5249 "This method is not supported in target SDK version " + version + " and above");
5250 }
5251 }
5252
5253 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5254 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5255 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5256 // remove these exemptions. Note that this check is not secure, and apps can still access these
5257 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5258 // so is unsupported and may break in the future. http://b/22728205
5259 private void checkLegacyRoutingApiAccess() {
5260 unsupportedStartingFrom(VERSION_CODES.M);
5261 }
5262
5263 /**
5264 * Binds host resolutions performed by this process to {@code network}.
5265 * {@link #bindProcessToNetwork} takes precedence over this setting.
5266 *
5267 * @param network The {@link Network} to bind host resolutions from the current process to, or
5268 * {@code null} to clear the current binding.
5269 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5270 * @hide
5271 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5272 */
5273 @Deprecated
5274 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5275 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5276 return NetworkUtils.bindProcessToNetworkForHostResolution(
5277 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5278 }
5279
5280 /**
5281 * Device is not restricting metered network activity while application is running on
5282 * background.
5283 */
5284 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5285
5286 /**
5287 * Device is restricting metered network activity while application is running on background,
5288 * but application is allowed to bypass it.
5289 * <p>
5290 * In this state, application should take action to mitigate metered network access.
5291 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5292 */
5293 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5294
5295 /**
5296 * Device is restricting metered network activity while application is running on background.
5297 * <p>
5298 * In this state, application should not try to use the network while running on background,
5299 * because it would be denied.
5300 */
5301 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5302
5303 /**
5304 * A change in the background metered network activity restriction has occurred.
5305 * <p>
5306 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5307 * applies to them.
5308 * <p>
5309 * This is only sent to registered receivers, not manifest receivers.
5310 */
5311 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5312 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5313 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5314
Aaron Huangcff22942021-05-27 16:31:26 +08005315 /** @hide */
5316 @Retention(RetentionPolicy.SOURCE)
5317 @IntDef(flag = false, value = {
5318 RESTRICT_BACKGROUND_STATUS_DISABLED,
5319 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5320 RESTRICT_BACKGROUND_STATUS_ENABLED,
5321 })
5322 public @interface RestrictBackgroundStatus {
5323 }
5324
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005325 /**
5326 * Determines if the calling application is subject to metered network restrictions while
5327 * running on background.
5328 *
5329 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5330 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5331 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5332 */
5333 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5334 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005335 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005336 } catch (RemoteException e) {
5337 throw e.rethrowFromSystemServer();
5338 }
5339 }
5340
5341 /**
5342 * The network watchlist is a list of domains and IP addresses that are associated with
5343 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5344 * currently used by the system for validation purposes.
5345 *
5346 * @return Hash of network watchlist config file. Null if config does not exist.
5347 */
5348 @Nullable
5349 public byte[] getNetworkWatchlistConfigHash() {
5350 try {
5351 return mService.getNetworkWatchlistConfigHash();
5352 } catch (RemoteException e) {
5353 Log.e(TAG, "Unable to get watchlist config hash");
5354 throw e.rethrowFromSystemServer();
5355 }
5356 }
5357
5358 /**
5359 * Returns the {@code uid} of the owner of a network connection.
5360 *
5361 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5362 * IPPROTO_UDP} currently supported.
5363 * @param local The local {@link InetSocketAddress} of a connection.
5364 * @param remote The remote {@link InetSocketAddress} of a connection.
5365 * @return {@code uid} if the connection is found and the app has permission to observe it
5366 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5367 * android.os.Process#INVALID_UID} if the connection is not found.
5368 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5369 * user.
5370 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5371 */
5372 public int getConnectionOwnerUid(
5373 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5374 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5375 try {
5376 return mService.getConnectionOwnerUid(connectionInfo);
5377 } catch (RemoteException e) {
5378 throw e.rethrowFromSystemServer();
5379 }
5380 }
5381
5382 private void printStackTrace() {
5383 if (DEBUG) {
5384 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5385 final StringBuffer sb = new StringBuffer();
5386 for (int i = 3; i < callStack.length; i++) {
5387 final String stackTrace = callStack[i].toString();
5388 if (stackTrace == null || stackTrace.contains("android.os")) {
5389 break;
5390 }
5391 sb.append(" [").append(stackTrace).append("]");
5392 }
5393 Log.d(TAG, "StackLog:" + sb.toString());
5394 }
5395 }
5396
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005397 /** @hide */
5398 public TestNetworkManager startOrGetTestNetworkManager() {
5399 final IBinder tnBinder;
5400 try {
5401 tnBinder = mService.startOrGetTestNetworkService();
5402 } catch (RemoteException e) {
5403 throw e.rethrowFromSystemServer();
5404 }
5405
5406 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5407 }
5408
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005409 /** @hide */
5410 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5411 return new ConnectivityDiagnosticsManager(mContext, mService);
5412 }
5413
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005414 /**
5415 * Simulates a Data Stall for the specified Network.
5416 *
5417 * <p>This method should only be used for tests.
5418 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005419 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5420 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005421 *
5422 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005423 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5424 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5425 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005426 * @param network The Network for which a Data Stall is being simluated.
5427 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5428 * @throws SecurityException if the caller is not the owner of the given network.
5429 * @hide
5430 */
5431 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5432 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5433 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005434 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005435 @NonNull Network network, @NonNull PersistableBundle extras) {
5436 try {
5437 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5438 } catch (RemoteException e) {
5439 e.rethrowFromSystemServer();
5440 }
5441 }
5442
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005443 @NonNull
5444 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5445
5446 /**
5447 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5448 * receive available QoS events related to the {@link Network} and local ip + port
5449 * specified within socketInfo.
5450 * <p/>
5451 * The same {@link QosCallback} must be unregistered before being registered a second time,
5452 * otherwise {@link QosCallbackRegistrationException} is thrown.
5453 * <p/>
5454 * This API does not, in itself, require any permission if called with a network that is not
5455 * restricted. However, the underlying implementation currently only supports the IMS network,
5456 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5457 * useful, because they'd never be called back on networks that they would have access to.
5458 *
5459 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5460 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5461 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5462 * @throws RuntimeException if the app already has too many callbacks registered.
5463 *
5464 * Exceptions after the time of registration is passed through
5465 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5466 *
5467 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005468 * @param executor The executor on which the callback will be invoked. The provided
5469 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005470 * callbacks cannot be guaranteed.onQosCallbackRegistered
5471 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005472 *
5473 * @hide
5474 */
5475 @SystemApi
5476 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005477 @CallbackExecutor @NonNull final Executor executor,
5478 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005479 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005480 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005481 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005482
5483 try {
5484 synchronized (mQosCallbackConnections) {
5485 if (getQosCallbackConnection(callback) == null) {
5486 final QosCallbackConnection connection =
5487 new QosCallbackConnection(this, callback, executor);
5488 mQosCallbackConnections.add(connection);
5489 mService.registerQosSocketCallback(socketInfo, connection);
5490 } else {
5491 Log.e(TAG, "registerQosCallback: Callback already registered");
5492 throw new QosCallbackRegistrationException();
5493 }
5494 }
5495 } catch (final RemoteException e) {
5496 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5497
5498 // The same unregister method method is called for consistency even though nothing
5499 // will be sent to the ConnectivityService since the callback was never successfully
5500 // registered.
5501 unregisterQosCallback(callback);
5502 e.rethrowFromSystemServer();
5503 } catch (final ServiceSpecificException e) {
5504 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5505 unregisterQosCallback(callback);
5506 throw convertServiceException(e);
5507 }
5508 }
5509
5510 /**
5511 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5512 * events once unregistered and can be registered a second time.
5513 * <p/>
5514 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5515 *
5516 * @param callback the callback being unregistered
5517 *
5518 * @hide
5519 */
5520 @SystemApi
5521 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5522 Objects.requireNonNull(callback, "The callback must be non-null");
5523 try {
5524 synchronized (mQosCallbackConnections) {
5525 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5526 if (connection != null) {
5527 connection.stopReceivingMessages();
5528 mService.unregisterQosCallback(connection);
5529 mQosCallbackConnections.remove(connection);
5530 } else {
5531 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5532 }
5533 }
5534 } catch (final RemoteException e) {
5535 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5536 e.rethrowFromSystemServer();
5537 }
5538 }
5539
5540 /**
5541 * Gets the connection related to the callback.
5542 *
5543 * @param callback the callback to look up
5544 * @return the related connection
5545 */
5546 @Nullable
5547 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5548 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5549 // Checking by reference here is intentional
5550 if (connection.getCallback() == callback) {
5551 return connection;
5552 }
5553 }
5554 return null;
5555 }
5556
5557 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005558 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005559 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5560 * be used to request that the system provide a network without causing the network to be
5561 * in the foreground.
5562 *
5563 * <p>This method will attempt to find the best network that matches the passed
5564 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5565 * criteria. The platform will evaluate which network is the best at its own discretion.
5566 * Throughput, latency, cost per byte, policy, user preference and other considerations
5567 * may be factored in the decision of what is considered the best network.
5568 *
5569 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5570 * matching this request, while always attempting to match the request to a better network if
5571 * possible. If a better match is found, the platform will switch this request to the now-best
5572 * network and inform the app of the newly best network by invoking
5573 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5574 * will not try to maintain any other network than the best one currently matching the request:
5575 * a network not matching any network request may be disconnected at any time.
5576 *
5577 * <p>For example, an application could use this method to obtain a connected cellular network
5578 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5579 * radio to consume additional power. Or, an application could inform the system that it wants
5580 * a network supporting sending MMSes and have the system let it know about the currently best
5581 * MMS-supporting network through the provided {@link NetworkCallback}.
5582 *
5583 * <p>The status of the request can be followed by listening to the various callbacks described
5584 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5585 * used to direct traffic to the network (although accessing some networks may be subject to
5586 * holding specific permissions). Callers will learn about the specific characteristics of the
5587 * network through
5588 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5589 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5590 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5591 * matching the request at any given time; therefore when a better network matching the request
5592 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5593 * with the new network after which no further updates are given about the previously-best
5594 * network, unless it becomes the best again at some later time. All callbacks are invoked
5595 * in order on the same thread, which by default is a thread created by the framework running
5596 * in the app.
5597 *
5598 * <p>This{@link NetworkRequest} will live until released via
5599 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5600 * which point the system may let go of the network at any time.
5601 *
5602 * <p>It is presently unsupported to request a network with mutable
5603 * {@link NetworkCapabilities} such as
5604 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5605 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5606 * as these {@code NetworkCapabilities} represent states that a particular
5607 * network may never attain, and whether a network will attain these states
5608 * is unknown prior to bringing up the network so the framework does not
5609 * know how to go about satisfying a request with these capabilities.
5610 *
5611 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5612 * number of outstanding requests to 100 per app (identified by their UID), shared with
5613 * all variants of this method, of {@link #registerNetworkCallback} as well as
5614 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5615 * Requesting a network with this method will count toward this limit. If this limit is
5616 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5617 * make sure to unregister the callbacks with
5618 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5619 *
5620 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005621 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5622 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005623 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5624 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005625 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5626 * @throws SecurityException if missing the appropriate permissions.
5627 * @throws RuntimeException if the app already has too many callbacks registered.
5628 *
5629 * @hide
5630 */
5631 @SystemApi(client = MODULE_LIBRARIES)
5632 @SuppressLint("ExecutorRegistration")
5633 @RequiresPermission(anyOf = {
5634 android.Manifest.permission.NETWORK_SETTINGS,
5635 android.Manifest.permission.NETWORK_STACK,
5636 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5637 })
5638 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005639 @NonNull NetworkCallback networkCallback,
5640 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005641 final NetworkCapabilities nc = request.networkCapabilities;
5642 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005643 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005644 }
James Mattis12aeab82021-01-10 14:24:24 -08005645
5646 /**
James Mattis12aeab82021-01-10 14:24:24 -08005647 * Used by automotive devices to set the network preferences used to direct traffic at an
5648 * application level as per the given OemNetworkPreferences. An example use-case would be an
5649 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5650 * vehicle via a particular network.
5651 *
5652 * Calling this will overwrite the existing preference.
5653 *
5654 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5655 * @param executor the executor on which listener will be invoked.
5656 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5657 * communicate completion of setOemNetworkPreference(). This will only be
5658 * called once upon successful completion of setOemNetworkPreference().
5659 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5660 * @throws SecurityException if missing the appropriate permissions.
5661 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005662 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005663 */
James Mattis6e2d7022021-01-26 16:23:52 -08005664 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005665 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005666 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005667 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005668 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005669 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5670 if (null != listener) {
5671 Objects.requireNonNull(executor, "Executor must be non-null");
5672 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005673 final IOnCompleteListener listenerInternal = listener == null ? null :
5674 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005675 @Override
5676 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005677 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005678 }
5679 };
5680
5681 try {
5682 mService.setOemNetworkPreference(preference, listenerInternal);
5683 } catch (RemoteException e) {
5684 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5685 throw e.rethrowFromSystemServer();
5686 }
5687 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005688
Chalard Jeanad565e22021-02-25 17:23:40 +09005689 /**
5690 * Request that a user profile is put by default on a network matching a given preference.
5691 *
5692 * See the documentation for the individual preferences for a description of the supported
5693 * behaviors.
5694 *
5695 * @param profile the profile concerned.
5696 * @param preference the preference for this profile.
5697 * @param executor an executor to execute the listener on. Optional if listener is null.
5698 * @param listener an optional listener to listen for completion of the operation.
5699 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5700 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005701 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5702 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005703 * @hide
5704 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005705 // This function is for establishing per-profile default networking and can only be called by
5706 // the device policy manager, running as the system server. It would make no sense to call it
5707 // on a context for a user because it does not establish a setting on behalf of a user, rather
5708 // it establishes a setting for a user on behalf of the DPM.
5709 @SuppressLint({"UserHandle"})
5710 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005711 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005712 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005713 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005714 @ProfileNetworkPreferencePolicy final int preference,
5715 @Nullable @CallbackExecutor final Executor executor,
5716 @Nullable final Runnable listener) {
5717
5718 ProfileNetworkPreference.Builder preferenceBuilder =
5719 new ProfileNetworkPreference.Builder();
5720 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005721 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5722 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5723 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005724 setProfileNetworkPreferences(profile,
5725 List.of(preferenceBuilder.build()), executor, listener);
5726 }
5727
5728 /**
5729 * Set a list of default network selection policies for a user profile.
5730 *
5731 * Calling this API with a user handle defines the entire policy for that user handle.
5732 * It will overwrite any setting previously set for the same user profile,
5733 * and not affect previously set settings for other handles.
5734 *
5735 * Call this API with an empty list to remove settings for this user profile.
5736 *
5737 * See {@link ProfileNetworkPreference} for more details on each preference
5738 * parameter.
5739 *
5740 * @param profile the user profile for which the preference is being set.
5741 * @param profileNetworkPreferences the list of profile network preferences for the
5742 * provided profile.
5743 * @param executor an executor to execute the listener on. Optional if listener is null.
5744 * @param listener an optional listener to listen for completion of the operation.
5745 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5746 * @throws SecurityException if missing the appropriate permissions.
5747 * @hide
5748 */
5749 @SystemApi(client = MODULE_LIBRARIES)
5750 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5751 public void setProfileNetworkPreferences(
5752 @NonNull final UserHandle profile,
5753 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005754 @Nullable @CallbackExecutor final Executor executor,
5755 @Nullable final Runnable listener) {
5756 if (null != listener) {
5757 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5758 }
5759 final IOnCompleteListener proxy;
5760 if (null == listener) {
5761 proxy = null;
5762 } else {
5763 proxy = new IOnCompleteListener.Stub() {
5764 @Override
5765 public void onComplete() {
5766 executor.execute(listener::run);
5767 }
5768 };
5769 }
5770 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005771 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005772 } catch (RemoteException e) {
5773 throw e.rethrowFromSystemServer();
5774 }
5775 }
5776
lucaslin5cdbcfb2021-03-12 00:46:33 +08005777 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005778 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005779 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005780 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005781
5782 /**
5783 * Get the network ID range reserved for IPSec tunnel interfaces.
5784 *
5785 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5786 * @hide
5787 */
5788 @SystemApi(client = MODULE_LIBRARIES)
5789 @NonNull
5790 public static Range<Integer> getIpSecNetIdRange() {
5791 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5792 }
markchien738ad912021-12-09 18:15:45 +08005793
5794 /**
markchiene46042b2022-03-02 18:07:35 +08005795 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5796 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005797 *
5798 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005799 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005800 * @hide
5801 */
5802 @SystemApi(client = MODULE_LIBRARIES)
5803 @RequiresPermission(anyOf = {
5804 android.Manifest.permission.NETWORK_SETTINGS,
5805 android.Manifest.permission.NETWORK_STACK,
5806 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5807 })
markchiene46042b2022-03-02 18:07:35 +08005808 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005809 try {
markchiene46042b2022-03-02 18:07:35 +08005810 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08005811 } catch (RemoteException e) {
5812 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005813 }
5814 }
5815
5816 /**
markchiene46042b2022-03-02 18:07:35 +08005817 * Removes the specified UID from the list of UIDs that are allowed to use background data on
5818 * metered networks when background data is restricted. The deny list takes precedence over
5819 * the allow list.
5820 *
5821 * @param uid uid of target app
5822 * @throws IllegalStateException if updating allow list failed.
5823 * @hide
5824 */
5825 @SystemApi(client = MODULE_LIBRARIES)
5826 @RequiresPermission(anyOf = {
5827 android.Manifest.permission.NETWORK_SETTINGS,
5828 android.Manifest.permission.NETWORK_STACK,
5829 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5830 })
5831 public void removeUidFromMeteredNetworkAllowList(final int uid) {
5832 try {
5833 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
5834 } catch (RemoteException e) {
5835 throw e.rethrowFromSystemServer();
5836 }
5837 }
5838
5839 /**
5840 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
5841 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08005842 *
5843 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005844 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08005845 * @hide
5846 */
5847 @SystemApi(client = MODULE_LIBRARIES)
5848 @RequiresPermission(anyOf = {
5849 android.Manifest.permission.NETWORK_SETTINGS,
5850 android.Manifest.permission.NETWORK_STACK,
5851 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5852 })
markchiene46042b2022-03-02 18:07:35 +08005853 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005854 try {
markchiene46042b2022-03-02 18:07:35 +08005855 mService.updateMeteredNetworkDenyList(uid, true /* add */);
5856 } catch (RemoteException e) {
5857 throw e.rethrowFromSystemServer();
5858 }
5859 }
5860
5861 /**
5862 * Removes the specified UID from the list of UIds that can use use background data on metered
5863 * networks if background data is not restricted. The deny list takes precedence over the
5864 * allow list.
5865 *
5866 * @param uid uid of target app
5867 * @throws IllegalStateException if updating deny list failed.
5868 * @hide
5869 */
5870 @SystemApi(client = MODULE_LIBRARIES)
5871 @RequiresPermission(anyOf = {
5872 android.Manifest.permission.NETWORK_SETTINGS,
5873 android.Manifest.permission.NETWORK_STACK,
5874 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5875 })
5876 public void removeUidFromMeteredNetworkDenyList(final int uid) {
5877 try {
5878 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08005879 } catch (RemoteException e) {
5880 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08005881 }
5882 }
5883
5884 /**
5885 * Sets a firewall rule for the specified UID on the specified chain.
5886 *
5887 * @param chain target chain.
5888 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08005889 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08005890 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08005891 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08005892 * @hide
5893 */
5894 @SystemApi(client = MODULE_LIBRARIES)
5895 @RequiresPermission(anyOf = {
5896 android.Manifest.permission.NETWORK_SETTINGS,
5897 android.Manifest.permission.NETWORK_STACK,
5898 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5899 })
markchien3c04e662022-03-22 16:29:56 +08005900 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
5901 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08005902 try {
markchien3c04e662022-03-22 16:29:56 +08005903 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08005904 } catch (RemoteException e) {
5905 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005906 }
5907 }
markchien98a6f952022-01-13 23:43:53 +08005908
5909 /**
5910 * Enables or disables the specified firewall chain.
5911 *
5912 * @param chain target chain.
5913 * @param enable whether the chain should be enabled.
markchien68cfadc2022-01-14 13:39:54 +08005914 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08005915 * @hide
5916 */
5917 @SystemApi(client = MODULE_LIBRARIES)
5918 @RequiresPermission(anyOf = {
5919 android.Manifest.permission.NETWORK_SETTINGS,
5920 android.Manifest.permission.NETWORK_STACK,
5921 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5922 })
5923 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
5924 try {
5925 mService.setFirewallChainEnabled(chain, enable);
5926 } catch (RemoteException e) {
5927 throw e.rethrowFromSystemServer();
5928 }
5929 }
markchien00a0bed2022-01-13 23:46:13 +08005930
5931 /**
5932 * Replaces the contents of the specified UID-based firewall chain.
5933 *
5934 * @param chain target chain to replace.
5935 * @param uids The list of UIDs to be placed into chain.
markchien68cfadc2022-01-14 13:39:54 +08005936 * @throws IllegalStateException if replacing the firewall chain failed.
markchien00a0bed2022-01-13 23:46:13 +08005937 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
5938 * @hide
5939 */
5940 @SystemApi(client = MODULE_LIBRARIES)
5941 @RequiresPermission(anyOf = {
5942 android.Manifest.permission.NETWORK_SETTINGS,
5943 android.Manifest.permission.NETWORK_STACK,
5944 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5945 })
5946 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
5947 Objects.requireNonNull(uids);
5948 try {
5949 mService.replaceFirewallChain(chain, uids);
5950 } catch (RemoteException e) {
5951 throw e.rethrowFromSystemServer();
5952 }
5953 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005954}