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