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