blob: 60bc68c04777f4bb7092b29d3c6084a301bae5c2 [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
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001110 * @return {@code true} if the type is valid, else {@code false}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001111 * @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";
Junyu Laic9f1ca62022-07-25 16:31:59 +08001170 case TYPE_TEST:
1171 return "TEST";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001172 default:
1173 return Integer.toString(type);
1174 }
1175 }
1176
1177 /**
1178 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001179 */
lucaslin10774b72021-03-17 14:16:01 +08001180 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001181 public void systemReady() {
1182 try {
1183 mService.systemReady();
1184 } catch (RemoteException e) {
1185 throw e.rethrowFromSystemServer();
1186 }
1187 }
1188
1189 /**
1190 * Checks if a given type uses the cellular data connection.
1191 * This should be replaced in the future by a network property.
1192 * @param networkType the type to check
1193 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1194 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1195 * {@hide}
1196 */
1197 @Deprecated
1198 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1199 public static boolean isNetworkTypeMobile(int networkType) {
1200 switch (networkType) {
1201 case TYPE_MOBILE:
1202 case TYPE_MOBILE_MMS:
1203 case TYPE_MOBILE_SUPL:
1204 case TYPE_MOBILE_DUN:
1205 case TYPE_MOBILE_HIPRI:
1206 case TYPE_MOBILE_FOTA:
1207 case TYPE_MOBILE_IMS:
1208 case TYPE_MOBILE_CBS:
1209 case TYPE_MOBILE_IA:
1210 case TYPE_MOBILE_EMERGENCY:
1211 return true;
1212 default:
1213 return false;
1214 }
1215 }
1216
1217 /**
1218 * Checks if the given network type is backed by a Wi-Fi radio.
1219 *
1220 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1221 * @hide
1222 */
1223 @Deprecated
1224 public static boolean isNetworkTypeWifi(int networkType) {
1225 switch (networkType) {
1226 case TYPE_WIFI:
1227 case TYPE_WIFI_P2P:
1228 return true;
1229 default:
1230 return false;
1231 }
1232 }
1233
1234 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001235 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001236 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001237 * Specify that the traffic for this user should by follow the default rules.
1238 * @hide
1239 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001240 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001241 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1242
1243 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001244 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001245 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001246 * Specify that the traffic for this user should by default go on a network with
1247 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1248 * if no such network is available.
1249 * @hide
1250 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001251 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001252 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1253
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001254 /**
1255 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001256 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001257 * Specify that the traffic for this user should by default go on a network with
1258 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
1259 * should not go on the system default network
1260 * @hide
1261 */
1262 @SystemApi(client = MODULE_LIBRARIES)
1263 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1264
Chalard Jeanad565e22021-02-25 17:23:40 +09001265 /** @hide */
1266 @Retention(RetentionPolicy.SOURCE)
1267 @IntDef(value = {
1268 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001269 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1270 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001271 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001272 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001273 }
1274
1275 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001276 * Specifies the preferred network type. When the device has more
1277 * than one type available the preferred network type will be used.
1278 *
1279 * @param preference the network type to prefer over all others. It is
1280 * unspecified what happens to the old preferred network in the
1281 * overall ordering.
1282 * @deprecated Functionality has been removed as it no longer makes sense,
1283 * with many more than two networks - we'd need an array to express
1284 * preference. Instead we use dynamic network properties of
1285 * the networks to describe their precedence.
1286 */
1287 @Deprecated
1288 public void setNetworkPreference(int preference) {
1289 }
1290
1291 /**
1292 * Retrieves the current preferred network type.
1293 *
1294 * @return an integer representing the preferred network type
1295 *
1296 * @deprecated Functionality has been removed as it no longer makes sense,
1297 * with many more than two networks - we'd need an array to express
1298 * preference. Instead we use dynamic network properties of
1299 * the networks to describe their precedence.
1300 */
1301 @Deprecated
1302 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1303 public int getNetworkPreference() {
1304 return TYPE_NONE;
1305 }
1306
1307 /**
1308 * Returns details about the currently active default data network. When
1309 * connected, this network is the default route for outgoing connections.
1310 * You should always check {@link NetworkInfo#isConnected()} before initiating
1311 * network traffic. This may return {@code null} when there is no default
1312 * network.
1313 * Note that if the default network is a VPN, this method will return the
1314 * NetworkInfo for one of its underlying networks instead, or null if the
1315 * VPN agent did not specify any. Apps interested in learning about VPNs
1316 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1317 *
1318 * @return a {@link NetworkInfo} object for the current default network
1319 * or {@code null} if no default network is currently active
1320 * @deprecated See {@link NetworkInfo}.
1321 */
1322 @Deprecated
1323 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1324 @Nullable
1325 public NetworkInfo getActiveNetworkInfo() {
1326 try {
1327 return mService.getActiveNetworkInfo();
1328 } catch (RemoteException e) {
1329 throw e.rethrowFromSystemServer();
1330 }
1331 }
1332
1333 /**
1334 * Returns a {@link Network} object corresponding to the currently active
1335 * default data network. In the event that the current active default data
1336 * network disconnects, the returned {@code Network} object will no longer
1337 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001338 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001339 *
1340 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001341 * {@code null} if no default network is currently active or if
1342 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001343 */
1344 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1345 @Nullable
1346 public Network getActiveNetwork() {
1347 try {
1348 return mService.getActiveNetwork();
1349 } catch (RemoteException e) {
1350 throw e.rethrowFromSystemServer();
1351 }
1352 }
1353
1354 /**
1355 * Returns a {@link Network} object corresponding to the currently active
1356 * default data network for a specific UID. In the event that the default data
1357 * network disconnects, the returned {@code Network} object will no longer
1358 * be usable. This will return {@code null} when there is no default
1359 * network for the UID.
1360 *
1361 * @return a {@link Network} object for the current default network for the
1362 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001363 *
1364 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001365 */
1366 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1367 @Nullable
1368 public Network getActiveNetworkForUid(int uid) {
1369 return getActiveNetworkForUid(uid, false);
1370 }
1371
1372 /** {@hide} */
1373 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1374 try {
1375 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1376 } catch (RemoteException e) {
1377 throw e.rethrowFromSystemServer();
1378 }
1379 }
1380
lucaslin3ba7cc22022-12-19 02:35:33 +00001381 private static UidRange[] getUidRangeArray(@NonNull Collection<Range<Integer>> ranges) {
1382 Objects.requireNonNull(ranges);
1383 final UidRange[] rangesArray = new UidRange[ranges.size()];
1384 int index = 0;
1385 for (Range<Integer> range : ranges) {
1386 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1387 }
1388
1389 return rangesArray;
1390 }
1391
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001392 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001393 * Adds or removes a requirement for given UID ranges to use the VPN.
1394 *
1395 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1396 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1397 * otherwise have permission to bypass the VPN (e.g., because they have the
1398 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1399 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1400 * set to {@code false}, a previously-added restriction is removed.
1401 * <p>
1402 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1403 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1404 * remove a previously-added range, the exact range must be removed as is.
1405 * <p>
1406 * The changes are applied asynchronously and may not have been applied by the time the method
1407 * returns. Apps will be notified about any changes that apply to them via
1408 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1409 * effect.
1410 * <p>
lucaslin3ba7cc22022-12-19 02:35:33 +00001411 * This method will block the specified UIDs from accessing non-VPN networks, but does not
1412 * affect what the UIDs get as their default network.
1413 * Compare {@link #setVpnDefaultForUids(String, Collection)}, which declares that the UIDs
1414 * should only have a VPN as their default network, but does not block them from accessing other
1415 * networks if they request them explicitly with the {@link Network} API.
1416 * <p>
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001417 * This method should be called only by the VPN code.
1418 *
1419 * @param ranges the UID ranges to restrict
1420 * @param requireVpn whether the specified UID ranges must use a VPN
1421 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001422 * @hide
1423 */
1424 @RequiresPermission(anyOf = {
1425 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001426 android.Manifest.permission.NETWORK_STACK,
1427 android.Manifest.permission.NETWORK_SETTINGS})
1428 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001429 public void setRequireVpnForUids(boolean requireVpn,
1430 @NonNull Collection<Range<Integer>> ranges) {
1431 Objects.requireNonNull(ranges);
1432 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1433 // This method is not necessarily expected to be used outside the system server, so
1434 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1435 // stack process, or by tests.
lucaslin3ba7cc22022-12-19 02:35:33 +00001436 final UidRange[] rangesArray = getUidRangeArray(ranges);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001437 try {
1438 mService.setRequireVpnForUids(requireVpn, rangesArray);
1439 } catch (RemoteException e) {
1440 throw e.rethrowFromSystemServer();
1441 }
1442 }
1443
1444 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001445 * Inform the system that this VPN session should manage the passed UIDs.
1446 *
1447 * A VPN with the specified session ID may call this method to inform the system that the UIDs
1448 * in the specified range are subject to a VPN.
1449 * When this is called, the system will only choose a VPN for the default network of the UIDs in
1450 * the specified ranges.
1451 *
1452 * This method declares that the UIDs in the range will only have a VPN for their default
1453 * network, but does not block the UIDs from accessing other networks (permissions allowing) by
1454 * explicitly requesting it with the {@link Network} API.
1455 * Compare {@link #setRequireVpnForUids(boolean, Collection)}, which does not affect what
1456 * network the UIDs get as default, but will block them from accessing non-VPN networks.
1457 *
1458 * @param session The VPN session which manages the passed UIDs.
1459 * @param ranges The uid ranges which will treat VPN as their only default network.
1460 *
1461 * @hide
1462 */
1463 @RequiresPermission(anyOf = {
1464 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1465 android.Manifest.permission.NETWORK_STACK,
1466 android.Manifest.permission.NETWORK_SETTINGS})
1467 @SystemApi(client = MODULE_LIBRARIES)
1468 public void setVpnDefaultForUids(@NonNull String session,
1469 @NonNull Collection<Range<Integer>> ranges) {
1470 Objects.requireNonNull(ranges);
1471 final UidRange[] rangesArray = getUidRangeArray(ranges);
1472 try {
1473 mService.setVpnNetworkPreference(session, rangesArray);
1474 } catch (RemoteException e) {
1475 throw e.rethrowFromSystemServer();
1476 }
1477 }
1478
1479 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001480 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1481 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1482 * but is still supported for backwards compatibility.
1483 * <p>
1484 * This type of VPN is assumed always to use the system default network, and must always declare
1485 * exactly one underlying network, which is the network that was the default when the VPN
1486 * connected.
1487 * <p>
1488 * Calling this method with {@code true} enables legacy behaviour, specifically:
1489 * <ul>
1490 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1491 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1492 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1493 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1494 * underlying the VPN.</li>
1495 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1496 * similarly replaced by the VPN network state.</li>
1497 * <li>Information on current network interfaces passed to NetworkStatsService will not
1498 * include any VPN interfaces.</li>
1499 * </ul>
1500 *
1501 * @param enabled whether legacy lockdown VPN is enabled or disabled
1502 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001503 * @hide
1504 */
1505 @RequiresPermission(anyOf = {
1506 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001507 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001508 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001509 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001510 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1511 try {
1512 mService.setLegacyLockdownVpnEnabled(enabled);
1513 } catch (RemoteException e) {
1514 throw e.rethrowFromSystemServer();
1515 }
1516 }
1517
1518 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001519 * Returns details about the currently active default data network for a given uid.
1520 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001521 *
1522 * @return a {@link NetworkInfo} object for the current default network
1523 * for the given uid or {@code null} if no default network is
1524 * available for the specified uid.
1525 *
1526 * {@hide}
1527 */
1528 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1529 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1530 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1531 return getActiveNetworkInfoForUid(uid, false);
1532 }
1533
1534 /** {@hide} */
1535 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1536 try {
1537 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1538 } catch (RemoteException e) {
1539 throw e.rethrowFromSystemServer();
1540 }
1541 }
1542
1543 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001544 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001545 *
1546 * @param networkType integer specifying which networkType in
1547 * which you're interested.
1548 * @return a {@link NetworkInfo} object for the requested
1549 * network type or {@code null} if the type is not
1550 * supported by the device. If {@code networkType} is
1551 * TYPE_VPN and a VPN is active for the calling app,
1552 * then this method will try to return one of the
1553 * underlying networks for the VPN or null if the
1554 * VPN agent didn't specify any.
1555 *
1556 * @deprecated This method does not support multiple connected networks
1557 * of the same type. Use {@link #getAllNetworks} and
1558 * {@link #getNetworkInfo(android.net.Network)} instead.
1559 */
1560 @Deprecated
1561 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1562 @Nullable
1563 public NetworkInfo getNetworkInfo(int networkType) {
1564 try {
1565 return mService.getNetworkInfo(networkType);
1566 } catch (RemoteException e) {
1567 throw e.rethrowFromSystemServer();
1568 }
1569 }
1570
1571 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001572 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001573 *
1574 * @param network {@link Network} specifying which network
1575 * in which you're interested.
1576 * @return a {@link NetworkInfo} object for the requested
1577 * network or {@code null} if the {@code Network}
1578 * is not valid.
1579 * @deprecated See {@link NetworkInfo}.
1580 */
1581 @Deprecated
1582 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1583 @Nullable
1584 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1585 return getNetworkInfoForUid(network, Process.myUid(), false);
1586 }
1587
1588 /** {@hide} */
1589 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1590 try {
1591 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1592 } catch (RemoteException e) {
1593 throw e.rethrowFromSystemServer();
1594 }
1595 }
1596
1597 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001598 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001599 *
1600 * @return an array of {@link NetworkInfo} objects. Check each
1601 * {@link NetworkInfo#getType} for which type each applies.
1602 *
1603 * @deprecated This method does not support multiple connected networks
1604 * of the same type. Use {@link #getAllNetworks} and
1605 * {@link #getNetworkInfo(android.net.Network)} instead.
1606 */
1607 @Deprecated
1608 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1609 @NonNull
1610 public NetworkInfo[] getAllNetworkInfo() {
1611 try {
1612 return mService.getAllNetworkInfo();
1613 } catch (RemoteException e) {
1614 throw e.rethrowFromSystemServer();
1615 }
1616 }
1617
1618 /**
junyulaib1211372021-03-03 12:09:05 +08001619 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1620 * connected.
1621 * @hide
1622 */
1623 @SystemApi(client = MODULE_LIBRARIES)
1624 @RequiresPermission(anyOf = {
1625 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1626 android.Manifest.permission.NETWORK_STACK,
1627 android.Manifest.permission.NETWORK_SETTINGS})
1628 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001629 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001630 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001631 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001632 } catch (RemoteException e) {
1633 throw e.rethrowFromSystemServer();
1634 }
1635 }
1636
1637 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001638 * Returns the {@link Network} object currently serving a given type, or
1639 * null if the given type is not connected.
1640 *
1641 * @hide
1642 * @deprecated This method does not support multiple connected networks
1643 * of the same type. Use {@link #getAllNetworks} and
1644 * {@link #getNetworkInfo(android.net.Network)} instead.
1645 */
1646 @Deprecated
1647 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1648 @UnsupportedAppUsage
1649 public Network getNetworkForType(int networkType) {
1650 try {
1651 return mService.getNetworkForType(networkType);
1652 } catch (RemoteException e) {
1653 throw e.rethrowFromSystemServer();
1654 }
1655 }
1656
1657 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001658 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001659 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001660 * @deprecated This method does not provide any notification of network state changes, forcing
1661 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1662 * Apps should use methods such as
1663 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1664 * Apps that desire to obtain information about networks that do not apply to them
1665 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1666 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001667 * @return an array of {@link Network} objects.
1668 */
1669 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1670 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001671 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001672 public Network[] getAllNetworks() {
1673 try {
1674 return mService.getAllNetworks();
1675 } catch (RemoteException e) {
1676 throw e.rethrowFromSystemServer();
1677 }
1678 }
1679
1680 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001681 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001682 * the Networks that applications run by the given user will use by default.
1683 * @hide
1684 */
1685 @UnsupportedAppUsage
1686 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1687 try {
1688 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001689 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001690 } catch (RemoteException e) {
1691 throw e.rethrowFromSystemServer();
1692 }
1693 }
1694
1695 /**
1696 * Returns the IP information for the current default network.
1697 *
1698 * @return a {@link LinkProperties} object describing the IP info
1699 * for the current default network, or {@code null} if there
1700 * is no current default network.
1701 *
1702 * {@hide}
1703 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1704 * value of {@link #getActiveNetwork()} instead. In particular,
1705 * this method will return non-null LinkProperties even if the
1706 * app is blocked by policy from using this network.
1707 */
1708 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1709 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1710 public LinkProperties getActiveLinkProperties() {
1711 try {
1712 return mService.getActiveLinkProperties();
1713 } catch (RemoteException e) {
1714 throw e.rethrowFromSystemServer();
1715 }
1716 }
1717
1718 /**
1719 * Returns the IP information for a given network type.
1720 *
1721 * @param networkType the network type of interest.
1722 * @return a {@link LinkProperties} object describing the IP info
1723 * for the given networkType, or {@code null} if there is
1724 * no current default network.
1725 *
1726 * {@hide}
1727 * @deprecated This method does not support multiple connected networks
1728 * of the same type. Use {@link #getAllNetworks},
1729 * {@link #getNetworkInfo(android.net.Network)}, and
1730 * {@link #getLinkProperties(android.net.Network)} instead.
1731 */
1732 @Deprecated
1733 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1734 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1735 public LinkProperties getLinkProperties(int networkType) {
1736 try {
1737 return mService.getLinkPropertiesForType(networkType);
1738 } catch (RemoteException e) {
1739 throw e.rethrowFromSystemServer();
1740 }
1741 }
1742
1743 /**
1744 * Get the {@link LinkProperties} for the given {@link Network}. This
1745 * will return {@code null} if the network is unknown.
1746 *
1747 * @param network The {@link Network} object identifying the network in question.
1748 * @return The {@link LinkProperties} for the network, or {@code null}.
1749 */
1750 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1751 @Nullable
1752 public LinkProperties getLinkProperties(@Nullable Network network) {
1753 try {
1754 return mService.getLinkProperties(network);
1755 } catch (RemoteException e) {
1756 throw e.rethrowFromSystemServer();
1757 }
1758 }
1759
1760 /**
lucaslinc582d502022-01-27 09:07:00 +08001761 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001762 *
lucaslinc582d502022-01-27 09:07:00 +08001763 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1764 * given package, considering its permissions.
1765 *
1766 * @param lp A {@link LinkProperties} which will be redacted.
1767 * @param uid The target uid.
1768 * @param packageName The name of the package, for appops logging.
1769 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1770 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1771 * @hide
1772 */
1773 @RequiresPermission(anyOf = {
1774 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1775 android.Manifest.permission.NETWORK_STACK,
1776 android.Manifest.permission.NETWORK_SETTINGS})
1777 @SystemApi(client = MODULE_LIBRARIES)
1778 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001779 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001780 @NonNull String packageName) {
1781 try {
lucaslind2b06132022-03-02 10:56:57 +08001782 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001783 lp, uid, packageName, getAttributionTag());
1784 } catch (RemoteException e) {
1785 throw e.rethrowFromSystemServer();
1786 }
1787 }
1788
1789 /**
1790 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1791 *
1792 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1793 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1794 * sensitive information. To retrieve this location sensitive information (subject to
1795 * the caller's location permissions), use a {@link NetworkCallback} with the
1796 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1797 *
1798 * This method returns {@code null} if the network is unknown or if the |network| argument
1799 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001800 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001801 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001802 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001803 */
1804 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1805 @Nullable
1806 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1807 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001808 return mService.getNetworkCapabilities(
1809 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001810 } catch (RemoteException e) {
1811 throw e.rethrowFromSystemServer();
1812 }
1813 }
1814
1815 /**
lucaslinc582d502022-01-27 09:07:00 +08001816 * Redact {@link NetworkCapabilities} for a given package.
1817 *
1818 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001819 * to the given package, considering its permissions. If the passed capabilities contain
1820 * location-sensitive information, they will be redacted to the correct degree for the location
1821 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1822 * that level of location. If the UID holds no location permission, the returned object will
1823 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001824 *
1825 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1826 * @param uid The target uid.
1827 * @param packageName The name of the package, for appops logging.
1828 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1829 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1830 * @hide
1831 */
1832 @RequiresPermission(anyOf = {
1833 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1834 android.Manifest.permission.NETWORK_STACK,
1835 android.Manifest.permission.NETWORK_SETTINGS})
1836 @SystemApi(client = MODULE_LIBRARIES)
1837 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001838 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001839 @NonNull NetworkCapabilities nc,
1840 int uid, @NonNull String packageName) {
1841 try {
lucaslind2b06132022-03-02 10:56:57 +08001842 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001843 getAttributionTag());
1844 } catch (RemoteException e) {
1845 throw e.rethrowFromSystemServer();
1846 }
1847 }
1848
1849 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001850 * Gets a URL that can be used for resolving whether a captive portal is present.
1851 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1852 * portal is present.
1853 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1854 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1855 *
1856 * The system network validation may be using different strategies to detect captive portals,
1857 * so this method does not necessarily return a URL used by the system. It only returns a URL
1858 * that may be relevant for other components trying to detect captive portals.
1859 *
1860 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001861 * @deprecated This API returns a URL which is not guaranteed to be one of the URLs used by the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001862 * system.
1863 */
1864 @Deprecated
1865 @SystemApi
1866 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1867 public String getCaptivePortalServerUrl() {
1868 try {
1869 return mService.getCaptivePortalServerUrl();
1870 } catch (RemoteException e) {
1871 throw e.rethrowFromSystemServer();
1872 }
1873 }
1874
1875 /**
1876 * Tells the underlying networking system that the caller wants to
1877 * begin using the named feature. The interpretation of {@code feature}
1878 * is completely up to each networking implementation.
1879 *
1880 * <p>This method requires the caller to hold either the
1881 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1882 * or the ability to modify system settings as determined by
1883 * {@link android.provider.Settings.System#canWrite}.</p>
1884 *
1885 * @param networkType specifies which network the request pertains to
1886 * @param feature the name of the feature to be used
1887 * @return an integer value representing the outcome of the request.
1888 * The interpretation of this value is specific to each networking
1889 * implementation+feature combination, except that the value {@code -1}
1890 * always indicates failure.
1891 *
1892 * @deprecated Deprecated in favor of the cleaner
1893 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1894 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1895 * throw {@code UnsupportedOperationException} if called.
1896 * @removed
1897 */
1898 @Deprecated
1899 public int startUsingNetworkFeature(int networkType, String feature) {
1900 checkLegacyRoutingApiAccess();
1901 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1902 if (netCap == null) {
1903 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1904 feature);
1905 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1906 }
1907
1908 NetworkRequest request = null;
1909 synchronized (sLegacyRequests) {
1910 LegacyRequest l = sLegacyRequests.get(netCap);
1911 if (l != null) {
1912 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1913 renewRequestLocked(l);
1914 if (l.currentNetwork != null) {
1915 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1916 } else {
1917 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1918 }
1919 }
1920
1921 request = requestNetworkForFeatureLocked(netCap);
1922 }
1923 if (request != null) {
1924 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1925 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1926 } else {
1927 Log.d(TAG, " request Failed");
1928 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1929 }
1930 }
1931
1932 /**
1933 * Tells the underlying networking system that the caller is finished
1934 * using the named feature. The interpretation of {@code feature}
1935 * is completely up to each networking implementation.
1936 *
1937 * <p>This method requires the caller to hold either the
1938 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1939 * or the ability to modify system settings as determined by
1940 * {@link android.provider.Settings.System#canWrite}.</p>
1941 *
1942 * @param networkType specifies which network the request pertains to
1943 * @param feature the name of the feature that is no longer needed
1944 * @return an integer value representing the outcome of the request.
1945 * The interpretation of this value is specific to each networking
1946 * implementation+feature combination, except that the value {@code -1}
1947 * always indicates failure.
1948 *
1949 * @deprecated Deprecated in favor of the cleaner
1950 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1951 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1952 * throw {@code UnsupportedOperationException} if called.
1953 * @removed
1954 */
1955 @Deprecated
1956 public int stopUsingNetworkFeature(int networkType, String feature) {
1957 checkLegacyRoutingApiAccess();
1958 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1959 if (netCap == null) {
1960 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1961 feature);
1962 return -1;
1963 }
1964
1965 if (removeRequestForFeature(netCap)) {
1966 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1967 }
1968 return 1;
1969 }
1970
1971 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1972 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1973 if (networkType == TYPE_MOBILE) {
1974 switch (feature) {
1975 case "enableCBS":
1976 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1977 case "enableDUN":
1978 case "enableDUNAlways":
1979 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1980 case "enableFOTA":
1981 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1982 case "enableHIPRI":
1983 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1984 case "enableIMS":
1985 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1986 case "enableMMS":
1987 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1988 case "enableSUPL":
1989 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1990 default:
1991 return null;
1992 }
1993 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1994 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1995 }
1996 return null;
1997 }
1998
1999 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
2000 if (netCap == null) return TYPE_NONE;
2001 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
2002 return TYPE_MOBILE_CBS;
2003 }
2004 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2005 return TYPE_MOBILE_IMS;
2006 }
2007 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
2008 return TYPE_MOBILE_FOTA;
2009 }
2010 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
2011 return TYPE_MOBILE_DUN;
2012 }
2013 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
2014 return TYPE_MOBILE_SUPL;
2015 }
2016 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2017 return TYPE_MOBILE_MMS;
2018 }
2019 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
2020 return TYPE_MOBILE_HIPRI;
2021 }
2022 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
2023 return TYPE_WIFI_P2P;
2024 }
2025 return TYPE_NONE;
2026 }
2027
2028 private static class LegacyRequest {
2029 NetworkCapabilities networkCapabilities;
2030 NetworkRequest networkRequest;
2031 int expireSequenceNumber;
2032 Network currentNetwork;
2033 int delay = -1;
2034
2035 private void clearDnsBinding() {
2036 if (currentNetwork != null) {
2037 currentNetwork = null;
2038 setProcessDefaultNetworkForHostResolution(null);
2039 }
2040 }
2041
2042 NetworkCallback networkCallback = new NetworkCallback() {
2043 @Override
2044 public void onAvailable(Network network) {
2045 currentNetwork = network;
2046 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
2047 setProcessDefaultNetworkForHostResolution(network);
2048 }
2049 @Override
2050 public void onLost(Network network) {
2051 if (network.equals(currentNetwork)) clearDnsBinding();
2052 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2053 }
2054 };
2055 }
2056
2057 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2058 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2059 new HashMap<>();
2060
2061 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2062 synchronized (sLegacyRequests) {
2063 LegacyRequest l = sLegacyRequests.get(netCap);
2064 if (l != null) return l.networkRequest;
2065 }
2066 return null;
2067 }
2068
2069 private void renewRequestLocked(LegacyRequest l) {
2070 l.expireSequenceNumber++;
2071 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2072 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2073 }
2074
2075 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2076 int ourSeqNum = -1;
2077 synchronized (sLegacyRequests) {
2078 LegacyRequest l = sLegacyRequests.get(netCap);
2079 if (l == null) return;
2080 ourSeqNum = l.expireSequenceNumber;
2081 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2082 }
2083 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2084 }
2085
2086 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2087 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2088 int delay = -1;
2089 int type = legacyTypeForNetworkCapabilities(netCap);
2090 try {
2091 delay = mService.getRestoreDefaultNetworkDelay(type);
2092 } catch (RemoteException e) {
2093 throw e.rethrowFromSystemServer();
2094 }
2095 LegacyRequest l = new LegacyRequest();
2096 l.networkCapabilities = netCap;
2097 l.delay = delay;
2098 l.expireSequenceNumber = 0;
2099 l.networkRequest = sendRequestForNetwork(
2100 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2101 if (l.networkRequest == null) return null;
2102 sLegacyRequests.put(netCap, l);
2103 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2104 return l.networkRequest;
2105 }
2106
2107 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2108 if (delay >= 0) {
2109 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2110 CallbackHandler handler = getDefaultHandler();
2111 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2112 handler.sendMessageDelayed(msg, delay);
2113 }
2114 }
2115
2116 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2117 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2118 final LegacyRequest l;
2119 synchronized (sLegacyRequests) {
2120 l = sLegacyRequests.remove(netCap);
2121 }
2122 if (l == null) return false;
2123 unregisterNetworkCallback(l.networkCallback);
2124 l.clearDnsBinding();
2125 return true;
2126 }
2127
2128 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2129 static {
2130 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2131 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2132 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2133 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2134 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2135 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2136 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2137 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2138 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2139 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2140 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2141 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2142 }
2143
2144 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2145 static {
2146 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2147 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2148 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2149 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2150 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2151 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2152 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2153 }
2154
2155 /**
2156 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2157 * instance suitable for registering a request or callback. Throws an
2158 * IllegalArgumentException if no mapping from the legacy type to
2159 * NetworkCapabilities is known.
2160 *
2161 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2162 * to find the network instead.
2163 * @hide
2164 */
2165 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2166 final NetworkCapabilities nc = new NetworkCapabilities();
2167
2168 // Map from type to transports.
2169 final int NOT_FOUND = -1;
2170 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002171 if (transport == NOT_FOUND) {
2172 throw new IllegalArgumentException("unknown legacy type: " + type);
2173 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002174 nc.addTransportType(transport);
2175
2176 // Map from type to capabilities.
2177 nc.addCapability(sLegacyTypeToCapability.get(
2178 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2179 nc.maybeMarkCapabilitiesRestricted();
2180 return nc;
2181 }
2182
2183 /** @hide */
2184 public static class PacketKeepaliveCallback {
2185 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2186 public PacketKeepaliveCallback() {
2187 }
2188 /** The requested keepalive was successfully started. */
2189 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2190 public void onStarted() {}
2191 /** The keepalive was successfully stopped. */
2192 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2193 public void onStopped() {}
2194 /** An error occurred. */
2195 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2196 public void onError(int error) {}
2197 }
2198
2199 /**
2200 * Allows applications to request that the system periodically send specific packets on their
2201 * behalf, using hardware offload to save battery power.
2202 *
2203 * To request that the system send keepalives, call one of the methods that return a
2204 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2205 * passing in a non-null callback. If the callback is successfully started, the callback's
2206 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2207 * specifying one of the {@code ERROR_*} constants in this class.
2208 *
2209 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2210 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2211 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2212 *
2213 * @deprecated Use {@link SocketKeepalive} instead.
2214 *
2215 * @hide
2216 */
2217 public class PacketKeepalive {
2218
2219 private static final String TAG = "PacketKeepalive";
2220
2221 /** @hide */
2222 public static final int SUCCESS = 0;
2223
2224 /** @hide */
2225 public static final int NO_KEEPALIVE = -1;
2226
2227 /** @hide */
2228 public static final int BINDER_DIED = -10;
2229
2230 /** The specified {@code Network} is not connected. */
2231 public static final int ERROR_INVALID_NETWORK = -20;
2232 /** The specified IP addresses are invalid. For example, the specified source IP address is
2233 * not configured on the specified {@code Network}. */
2234 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2235 /** The requested port is invalid. */
2236 public static final int ERROR_INVALID_PORT = -22;
2237 /** The packet length is invalid (e.g., too long). */
2238 public static final int ERROR_INVALID_LENGTH = -23;
2239 /** The packet transmission interval is invalid (e.g., too short). */
2240 public static final int ERROR_INVALID_INTERVAL = -24;
2241
2242 /** The hardware does not support this request. */
2243 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2244 /** The hardware returned an error. */
2245 public static final int ERROR_HARDWARE_ERROR = -31;
2246
2247 /** The NAT-T destination port for IPsec */
2248 public static final int NATT_PORT = 4500;
2249
2250 /** The minimum interval in seconds between keepalive packet transmissions */
2251 public static final int MIN_INTERVAL = 10;
2252
2253 private final Network mNetwork;
2254 private final ISocketKeepaliveCallback mCallback;
2255 private final ExecutorService mExecutor;
2256
2257 private volatile Integer mSlot;
2258
2259 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2260 public void stop() {
2261 try {
2262 mExecutor.execute(() -> {
2263 try {
2264 if (mSlot != null) {
2265 mService.stopKeepalive(mNetwork, mSlot);
2266 }
2267 } catch (RemoteException e) {
2268 Log.e(TAG, "Error stopping packet keepalive: ", e);
2269 throw e.rethrowFromSystemServer();
2270 }
2271 });
2272 } catch (RejectedExecutionException e) {
2273 // The internal executor has already stopped due to previous event.
2274 }
2275 }
2276
2277 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002278 Objects.requireNonNull(network, "network cannot be null");
2279 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002280 mNetwork = network;
2281 mExecutor = Executors.newSingleThreadExecutor();
2282 mCallback = new ISocketKeepaliveCallback.Stub() {
2283 @Override
2284 public void onStarted(int slot) {
2285 final long token = Binder.clearCallingIdentity();
2286 try {
2287 mExecutor.execute(() -> {
2288 mSlot = slot;
2289 callback.onStarted();
2290 });
2291 } finally {
2292 Binder.restoreCallingIdentity(token);
2293 }
2294 }
2295
2296 @Override
2297 public void onStopped() {
2298 final long token = Binder.clearCallingIdentity();
2299 try {
2300 mExecutor.execute(() -> {
2301 mSlot = null;
2302 callback.onStopped();
2303 });
2304 } finally {
2305 Binder.restoreCallingIdentity(token);
2306 }
2307 mExecutor.shutdown();
2308 }
2309
2310 @Override
2311 public void onError(int error) {
2312 final long token = Binder.clearCallingIdentity();
2313 try {
2314 mExecutor.execute(() -> {
2315 mSlot = null;
2316 callback.onError(error);
2317 });
2318 } finally {
2319 Binder.restoreCallingIdentity(token);
2320 }
2321 mExecutor.shutdown();
2322 }
2323
2324 @Override
2325 public void onDataReceived() {
2326 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2327 // this callback when data is received.
2328 }
2329 };
2330 }
2331 }
2332
2333 /**
2334 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2335 *
2336 * @deprecated Use {@link #createSocketKeepalive} instead.
2337 *
2338 * @hide
2339 */
2340 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2341 public PacketKeepalive startNattKeepalive(
2342 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2343 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2344 final PacketKeepalive k = new PacketKeepalive(network, callback);
2345 try {
2346 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2347 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2348 } catch (RemoteException e) {
2349 Log.e(TAG, "Error starting packet keepalive: ", e);
2350 throw e.rethrowFromSystemServer();
2351 }
2352 return k;
2353 }
2354
2355 // Construct an invalid fd.
2356 private ParcelFileDescriptor createInvalidFd() {
2357 final int invalidFd = -1;
2358 return ParcelFileDescriptor.adoptFd(invalidFd);
2359 }
2360
2361 /**
2362 * Request that keepalives be started on a IPsec NAT-T socket.
2363 *
2364 * @param network The {@link Network} the socket is on.
2365 * @param socket The socket that needs to be kept alive.
2366 * @param source The source address of the {@link UdpEncapsulationSocket}.
2367 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2368 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2369 * must run callback sequentially, otherwise the order of callbacks cannot be
2370 * guaranteed.
2371 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2372 * changes. Must be extended by applications that use this API.
2373 *
2374 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2375 * given socket.
2376 **/
2377 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2378 @NonNull UdpEncapsulationSocket socket,
2379 @NonNull InetAddress source,
2380 @NonNull InetAddress destination,
2381 @NonNull @CallbackExecutor Executor executor,
2382 @NonNull Callback callback) {
2383 ParcelFileDescriptor dup;
2384 try {
2385 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2386 // which cannot be obtained by the app process.
2387 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2388 } catch (IOException ignored) {
2389 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2390 // ERROR_INVALID_SOCKET.
2391 dup = createInvalidFd();
2392 }
2393 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2394 destination, executor, callback);
2395 }
2396
2397 /**
2398 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2399 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2400 *
2401 * @param network The {@link Network} the socket is on.
2402 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2403 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2404 * from that port.
2405 * @param source The source address of the {@link UdpEncapsulationSocket}.
2406 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2407 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2408 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2409 * must run callback sequentially, otherwise the order of callbacks cannot be
2410 * guaranteed.
2411 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2412 * changes. Must be extended by applications that use this API.
2413 *
2414 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2415 * given socket.
2416 * @hide
2417 */
2418 @SystemApi
2419 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2420 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2421 @NonNull ParcelFileDescriptor pfd,
2422 @NonNull InetAddress source,
2423 @NonNull InetAddress destination,
2424 @NonNull @CallbackExecutor Executor executor,
2425 @NonNull Callback callback) {
2426 ParcelFileDescriptor dup;
2427 try {
2428 // TODO: Consider remove unnecessary dup.
2429 dup = pfd.dup();
2430 } catch (IOException ignored) {
2431 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2432 // ERROR_INVALID_SOCKET.
2433 dup = createInvalidFd();
2434 }
2435 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002436 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002437 }
2438
2439 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002440 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002441 *
2442 * @param network The {@link Network} the socket is on.
2443 * @param socket The socket that needs to be kept alive.
2444 * @param executor The executor on which callback will be invoked. This implementation assumes
2445 * the provided {@link Executor} runs the callbacks in sequence with no
2446 * concurrency. Failing this, no guarantee of correctness can be made. It is
2447 * the responsibility of the caller to ensure the executor provides this
2448 * guarantee. A simple way of creating such an executor is with the standard
2449 * tool {@code Executors.newSingleThreadExecutor}.
2450 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2451 * changes. Must be extended by applications that use this API.
2452 *
2453 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2454 * given socket.
2455 * @hide
2456 */
2457 @SystemApi
2458 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2459 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2460 @NonNull Socket socket,
2461 @NonNull Executor executor,
2462 @NonNull Callback callback) {
2463 ParcelFileDescriptor dup;
2464 try {
2465 dup = ParcelFileDescriptor.fromSocket(socket);
2466 } catch (UncheckedIOException ignored) {
2467 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2468 // ERROR_INVALID_SOCKET.
2469 dup = createInvalidFd();
2470 }
2471 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2472 }
2473
2474 /**
2475 * Ensure that a network route exists to deliver traffic to the specified
2476 * host via the specified network interface. An attempt to add a route that
2477 * already exists is ignored, but treated as successful.
2478 *
2479 * <p>This method requires the caller to hold either the
2480 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2481 * or the ability to modify system settings as determined by
2482 * {@link android.provider.Settings.System#canWrite}.</p>
2483 *
2484 * @param networkType the type of the network over which traffic to the specified
2485 * host is to be routed
2486 * @param hostAddress the IP address of the host to which the route is desired
2487 * @return {@code true} on success, {@code false} on failure
2488 *
2489 * @deprecated Deprecated in favor of the
2490 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2491 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2492 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2493 * throw {@code UnsupportedOperationException} if called.
2494 * @removed
2495 */
2496 @Deprecated
2497 public boolean requestRouteToHost(int networkType, int hostAddress) {
2498 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2499 }
2500
2501 /**
2502 * Ensure that a network route exists to deliver traffic to the specified
2503 * host via the specified network interface. An attempt to add a route that
2504 * already exists is ignored, but treated as successful.
2505 *
2506 * <p>This method requires the caller to hold either the
2507 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2508 * or the ability to modify system settings as determined by
2509 * {@link android.provider.Settings.System#canWrite}.</p>
2510 *
2511 * @param networkType the type of the network over which traffic to the specified
2512 * host is to be routed
2513 * @param hostAddress the IP address of the host to which the route is desired
2514 * @return {@code true} on success, {@code false} on failure
2515 * @hide
2516 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2517 * {@link #bindProcessToNetwork} API.
2518 */
2519 @Deprecated
2520 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002521 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002522 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2523 checkLegacyRoutingApiAccess();
2524 try {
2525 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2526 mContext.getOpPackageName(), getAttributionTag());
2527 } catch (RemoteException e) {
2528 throw e.rethrowFromSystemServer();
2529 }
2530 }
2531
2532 /**
2533 * @return the context's attribution tag
2534 */
2535 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2536 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002537 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002538 }
2539
2540 /**
2541 * Returns the value of the setting for background data usage. If false,
2542 * applications should not use the network if the application is not in the
2543 * foreground. Developers should respect this setting, and check the value
2544 * of this before performing any background data operations.
2545 * <p>
2546 * All applications that have background services that use the network
2547 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2548 * <p>
2549 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2550 * background data depends on several combined factors, and this method will
2551 * always return {@code true}. Instead, when background data is unavailable,
2552 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2553 *
2554 * @return Whether background data usage is allowed.
2555 */
2556 @Deprecated
2557 public boolean getBackgroundDataSetting() {
2558 // assume that background data is allowed; final authority is
2559 // NetworkInfo which may be blocked.
2560 return true;
2561 }
2562
2563 /**
2564 * Sets the value of the setting for background data usage.
2565 *
2566 * @param allowBackgroundData Whether an application should use data while
2567 * it is in the background.
2568 *
2569 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2570 * @see #getBackgroundDataSetting()
2571 * @hide
2572 */
2573 @Deprecated
2574 @UnsupportedAppUsage
2575 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2576 // ignored
2577 }
2578
2579 /**
2580 * @hide
2581 * @deprecated Talk to TelephonyManager directly
2582 */
2583 @Deprecated
2584 @UnsupportedAppUsage
2585 public boolean getMobileDataEnabled() {
2586 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2587 if (tm != null) {
2588 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2589 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2590 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2591 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2592 + " retVal=" + retVal);
2593 return retVal;
2594 }
2595 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2596 return false;
2597 }
2598
2599 /**
2600 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2601 * to find out when the system default network has gone in to a high power state.
2602 */
2603 public interface OnNetworkActiveListener {
2604 /**
2605 * Called on the main thread of the process to report that the current data network
2606 * has become active, and it is now a good time to perform any pending network
2607 * operations. Note that this listener only tells you when the network becomes
2608 * active; if at any other time you want to know whether it is active (and thus okay
2609 * to initiate network traffic), you can retrieve its instantaneous state with
2610 * {@link ConnectivityManager#isDefaultNetworkActive}.
2611 */
2612 void onNetworkActive();
2613 }
2614
Chiachang Wang2de41682021-09-23 10:46:03 +08002615 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002616 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2617 mNetworkActivityListeners = new ArrayMap<>();
2618
2619 /**
2620 * Start listening to reports when the system's default data network is active, meaning it is
2621 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2622 * to determine the current state of the system's default network after registering the
2623 * listener.
2624 * <p>
2625 * If the process default network has been set with
2626 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2627 * reflect the process's default, but the system default.
2628 *
2629 * @param l The listener to be told when the network is active.
2630 */
2631 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002632 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002633 @Override
2634 public void onNetworkActive() throws RemoteException {
2635 l.onNetworkActive();
2636 }
2637 };
2638
Chiachang Wang2de41682021-09-23 10:46:03 +08002639 synchronized (mNetworkActivityListeners) {
2640 try {
2641 mService.registerNetworkActivityListener(rl);
2642 mNetworkActivityListeners.put(l, rl);
2643 } catch (RemoteException e) {
2644 throw e.rethrowFromSystemServer();
2645 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002646 }
2647 }
2648
2649 /**
2650 * Remove network active listener previously registered with
2651 * {@link #addDefaultNetworkActiveListener}.
2652 *
2653 * @param l Previously registered listener.
2654 */
2655 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002656 synchronized (mNetworkActivityListeners) {
2657 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2658 if (rl == null) {
2659 throw new IllegalArgumentException("Listener was not registered.");
2660 }
2661 try {
2662 mService.unregisterNetworkActivityListener(rl);
2663 mNetworkActivityListeners.remove(l);
2664 } catch (RemoteException e) {
2665 throw e.rethrowFromSystemServer();
2666 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002667 }
2668 }
2669
2670 /**
2671 * Return whether the data network is currently active. An active network means that
2672 * it is currently in a high power state for performing data transmission. On some
2673 * types of networks, it may be expensive to move and stay in such a state, so it is
2674 * more power efficient to batch network traffic together when the radio is already in
2675 * this state. This method tells you whether right now is currently a good time to
2676 * initiate network traffic, as the network is already active.
2677 */
2678 public boolean isDefaultNetworkActive() {
2679 try {
lucaslin709eb842021-01-21 02:04:15 +08002680 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002681 } catch (RemoteException e) {
2682 throw e.rethrowFromSystemServer();
2683 }
2684 }
2685
2686 /**
2687 * {@hide}
2688 */
2689 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002690 this(context, service, true /* newStatic */);
2691 }
2692
2693 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002694 mContext = Objects.requireNonNull(context, "missing context");
2695 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002696 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2697 // different ConnectivityManager, but that's still OK considering its usage.
2698 if (sInstance == null && newStatic) {
2699 final Context appContext = mContext.getApplicationContext();
2700 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2701 // If the application context is null, we're either in the system process or
2702 // it's the application context very early in app initialization. In both these
2703 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2704 // service. http://b/27532714 .
2705 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2706 false /* newStatic */);
2707 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002708 }
2709
2710 /** {@hide} */
2711 @UnsupportedAppUsage
2712 public static ConnectivityManager from(Context context) {
2713 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2714 }
2715
2716 /** @hide */
2717 public NetworkRequest getDefaultRequest() {
2718 try {
2719 // This is not racy as the default request is final in ConnectivityService.
2720 return mService.getDefaultRequest();
2721 } catch (RemoteException e) {
2722 throw e.rethrowFromSystemServer();
2723 }
2724 }
2725
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002726 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002727 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002728 * happened.
2729 *
2730 * @return {@code true} iff the package is allowed to write settings.
2731 */
2732 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2733 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2734 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2735 boolean throwException) {
2736 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002737 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002738 }
2739
2740 /**
2741 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2742 * situations where a Context pointer is unavailable.
2743 * @hide
2744 */
2745 @Deprecated
2746 static ConnectivityManager getInstanceOrNull() {
2747 return sInstance;
2748 }
2749
2750 /**
2751 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2752 * situations where a Context pointer is unavailable.
2753 * @hide
2754 */
2755 @Deprecated
2756 @UnsupportedAppUsage
2757 private static ConnectivityManager getInstance() {
2758 if (getInstanceOrNull() == null) {
2759 throw new IllegalStateException("No ConnectivityManager yet constructed");
2760 }
2761 return getInstanceOrNull();
2762 }
2763
2764 /**
2765 * Get the set of tetherable, available interfaces. This list is limited by
2766 * device configuration and current interface existence.
2767 *
2768 * @return an array of 0 or more Strings of tetherable interface names.
2769 *
2770 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2771 * {@hide}
2772 */
2773 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2774 @UnsupportedAppUsage
2775 @Deprecated
2776 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002777 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002778 }
2779
2780 /**
2781 * Get the set of tethered interfaces.
2782 *
2783 * @return an array of 0 or more String of currently tethered interface names.
2784 *
2785 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2786 * {@hide}
2787 */
2788 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2789 @UnsupportedAppUsage
2790 @Deprecated
2791 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002792 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002793 }
2794
2795 /**
2796 * Get the set of interface names which attempted to tether but
2797 * failed. Re-attempting to tether may cause them to reset to the Tethered
2798 * state. Alternatively, causing the interface to be destroyed and recreated
2799 * may cause them to reset to the available state.
2800 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2801 * information on the cause of the errors.
2802 *
2803 * @return an array of 0 or more String indicating the interface names
2804 * which failed to tether.
2805 *
2806 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2807 * {@hide}
2808 */
2809 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2810 @UnsupportedAppUsage
2811 @Deprecated
2812 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002813 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002814 }
2815
2816 /**
2817 * Get the set of tethered dhcp ranges.
2818 *
2819 * @deprecated This method is not supported.
2820 * TODO: remove this function when all of clients are removed.
2821 * {@hide}
2822 */
2823 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2824 @Deprecated
2825 public String[] getTetheredDhcpRanges() {
2826 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2827 }
2828
2829 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002830 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002831 * on the interface, forward and NAT IP packets and forward DNS requests
2832 * to the best active upstream network interface. Note that if no upstream
2833 * IP network interface is available, dhcp will still run and traffic will be
2834 * allowed between the tethered devices and this device, though upstream net
2835 * access will of course fail until an upstream network interface becomes
2836 * active.
2837 *
2838 * <p>This method requires the caller to hold either the
2839 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2840 * or the ability to modify system settings as determined by
2841 * {@link android.provider.Settings.System#canWrite}.</p>
2842 *
2843 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2844 * and WifiStateMachine which need direct access. All other clients should use
2845 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2846 * logic.</p>
2847 *
2848 * @param iface the interface name to tether.
2849 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2850 * @deprecated Use {@link TetheringManager#startTethering} instead
2851 *
2852 * {@hide}
2853 */
2854 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2855 @Deprecated
2856 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002857 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002858 }
2859
2860 /**
2861 * Stop tethering the named interface.
2862 *
2863 * <p>This method requires the caller to hold either the
2864 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2865 * or the ability to modify system settings as determined by
2866 * {@link android.provider.Settings.System#canWrite}.</p>
2867 *
2868 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2869 * and WifiStateMachine which need direct access. All other clients should use
2870 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2871 * logic.</p>
2872 *
2873 * @param iface the interface name to untether.
2874 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2875 *
2876 * {@hide}
2877 */
2878 @UnsupportedAppUsage
2879 @Deprecated
2880 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002881 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002882 }
2883
2884 /**
2885 * Check if the device allows for tethering. It may be disabled via
2886 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2887 * due to device configuration.
2888 *
2889 * <p>If this app does not have permission to use this API, it will always
2890 * return false rather than throw an exception.</p>
2891 *
2892 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2893 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2894 *
2895 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2896 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2897 *
2898 * @return a boolean - {@code true} indicating Tethering is supported.
2899 *
2900 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2901 * {@hide}
2902 */
2903 @SystemApi
2904 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2905 android.Manifest.permission.WRITE_SETTINGS})
2906 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002907 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002908 }
2909
2910 /**
2911 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2912 *
2913 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2914 * @hide
2915 */
2916 @SystemApi
2917 @Deprecated
2918 public static abstract class OnStartTetheringCallback {
2919 /**
2920 * Called when tethering has been successfully started.
2921 */
2922 public void onTetheringStarted() {}
2923
2924 /**
2925 * Called when starting tethering failed.
2926 */
2927 public void onTetheringFailed() {}
2928 }
2929
2930 /**
2931 * Convenient overload for
2932 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2933 * handler to run on the current thread's {@link Looper}.
2934 *
2935 * @deprecated Use {@link TetheringManager#startTethering} instead.
2936 * @hide
2937 */
2938 @SystemApi
2939 @Deprecated
2940 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2941 public void startTethering(int type, boolean showProvisioningUi,
2942 final OnStartTetheringCallback callback) {
2943 startTethering(type, showProvisioningUi, callback, null);
2944 }
2945
2946 /**
2947 * Runs tether provisioning for the given type if needed and then starts tethering if
2948 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2949 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2950 * schedules tether provisioning re-checks if appropriate.
2951 *
2952 * @param type The type of tethering to start. Must be one of
2953 * {@link ConnectivityManager.TETHERING_WIFI},
2954 * {@link ConnectivityManager.TETHERING_USB}, or
2955 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2956 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2957 * is one. This should be true the first time this function is called and also any time
2958 * the user can see this UI. It gives users information from their carrier about the
2959 * check failing and how they can sign up for tethering if possible.
2960 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2961 * of the result of trying to tether.
2962 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2963 *
2964 * @deprecated Use {@link TetheringManager#startTethering} instead.
2965 * @hide
2966 */
2967 @SystemApi
2968 @Deprecated
2969 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2970 public void startTethering(int type, boolean showProvisioningUi,
2971 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002972 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002973
2974 final Executor executor = new Executor() {
2975 @Override
2976 public void execute(Runnable command) {
2977 if (handler == null) {
2978 command.run();
2979 } else {
2980 handler.post(command);
2981 }
2982 }
2983 };
2984
2985 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2986 @Override
2987 public void onTetheringStarted() {
2988 callback.onTetheringStarted();
2989 }
2990
2991 @Override
2992 public void onTetheringFailed(final int error) {
2993 callback.onTetheringFailed();
2994 }
2995 };
2996
2997 final TetheringRequest request = new TetheringRequest.Builder(type)
2998 .setShouldShowEntitlementUi(showProvisioningUi).build();
2999
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003000 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003001 }
3002
3003 /**
3004 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
3005 * applicable.
3006 *
3007 * @param type The type of tethering to stop. Must be one of
3008 * {@link ConnectivityManager.TETHERING_WIFI},
3009 * {@link ConnectivityManager.TETHERING_USB}, or
3010 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3011 *
3012 * @deprecated Use {@link TetheringManager#stopTethering} instead.
3013 * @hide
3014 */
3015 @SystemApi
3016 @Deprecated
3017 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3018 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003019 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003020 }
3021
3022 /**
3023 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
3024 * upstream status.
3025 *
3026 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
3027 * @hide
3028 */
3029 @SystemApi
3030 @Deprecated
3031 public abstract static class OnTetheringEventCallback {
3032
3033 /**
3034 * Called when tethering upstream changed. This can be called multiple times and can be
3035 * called any time.
3036 *
3037 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
3038 * have any upstream.
3039 */
3040 public void onUpstreamChanged(@Nullable Network network) {}
3041 }
3042
3043 @GuardedBy("mTetheringEventCallbacks")
3044 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
3045 mTetheringEventCallbacks = new ArrayMap<>();
3046
3047 /**
3048 * Start listening to tethering change events. Any new added callback will receive the last
3049 * tethering status right away. If callback is registered when tethering has no upstream or
3050 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3051 * with a null argument. The same callback object cannot be registered twice.
3052 *
3053 * @param executor the executor on which callback will be invoked.
3054 * @param callback the callback to be called when tethering has change events.
3055 *
3056 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3057 * @hide
3058 */
3059 @SystemApi
3060 @Deprecated
3061 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3062 public void registerTetheringEventCallback(
3063 @NonNull @CallbackExecutor Executor executor,
3064 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003065 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003066
3067 final TetheringEventCallback tetherCallback =
3068 new TetheringEventCallback() {
3069 @Override
3070 public void onUpstreamChanged(@Nullable Network network) {
3071 callback.onUpstreamChanged(network);
3072 }
3073 };
3074
3075 synchronized (mTetheringEventCallbacks) {
3076 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003077 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003078 }
3079 }
3080
3081 /**
3082 * Remove tethering event callback previously registered with
3083 * {@link #registerTetheringEventCallback}.
3084 *
3085 * @param callback previously registered callback.
3086 *
3087 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3088 * @hide
3089 */
3090 @SystemApi
3091 @Deprecated
3092 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3093 public void unregisterTetheringEventCallback(
3094 @NonNull final OnTetheringEventCallback callback) {
3095 Objects.requireNonNull(callback, "The callback must be non-null");
3096 synchronized (mTetheringEventCallbacks) {
3097 final TetheringEventCallback tetherCallback =
3098 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003099 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003100 }
3101 }
3102
3103
3104 /**
3105 * Get the list of regular expressions that define any tetherable
3106 * USB network interfaces. If USB tethering is not supported by the
3107 * device, this list should be empty.
3108 *
3109 * @return an array of 0 or more regular expression Strings defining
3110 * what interfaces are considered tetherable usb interfaces.
3111 *
3112 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3113 * {@hide}
3114 */
3115 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3116 @UnsupportedAppUsage
3117 @Deprecated
3118 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003119 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003120 }
3121
3122 /**
3123 * Get the list of regular expressions that define any tetherable
3124 * Wifi network interfaces. If Wifi tethering is not supported by the
3125 * device, this list should be empty.
3126 *
3127 * @return an array of 0 or more regular expression Strings defining
3128 * what interfaces are considered tetherable wifi interfaces.
3129 *
3130 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3131 * {@hide}
3132 */
3133 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3134 @UnsupportedAppUsage
3135 @Deprecated
3136 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003137 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003138 }
3139
3140 /**
3141 * Get the list of regular expressions that define any tetherable
3142 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3143 * device, this list should be empty.
3144 *
3145 * @return an array of 0 or more regular expression Strings defining
3146 * what interfaces are considered tetherable bluetooth interfaces.
3147 *
3148 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3149 *TetheringManager.TetheringInterfaceRegexps)} instead.
3150 * {@hide}
3151 */
3152 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3153 @UnsupportedAppUsage
3154 @Deprecated
3155 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003156 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003157 }
3158
3159 /**
3160 * Attempt to both alter the mode of USB and Tethering of USB. A
3161 * utility method to deal with some of the complexity of USB - will
3162 * attempt to switch to Rndis and subsequently tether the resulting
3163 * interface on {@code true} or turn off tethering and switch off
3164 * Rndis on {@code false}.
3165 *
3166 * <p>This method requires the caller to hold either the
3167 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3168 * or the ability to modify system settings as determined by
3169 * {@link android.provider.Settings.System#canWrite}.</p>
3170 *
3171 * @param enable a boolean - {@code true} to enable tethering
3172 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3173 * @deprecated Use {@link TetheringManager#startTethering} instead
3174 *
3175 * {@hide}
3176 */
3177 @UnsupportedAppUsage
3178 @Deprecated
3179 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003180 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003181 }
3182
3183 /**
3184 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3185 * {@hide}
3186 */
3187 @SystemApi
3188 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003189 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003190 /**
3191 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3192 * {@hide}
3193 */
3194 @Deprecated
3195 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3196 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3197 /**
3198 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3199 * {@hide}
3200 */
3201 @Deprecated
3202 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3203 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3204 /**
3205 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3206 * {@hide}
3207 */
3208 @Deprecated
3209 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3210 /**
3211 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3212 * {@hide}
3213 */
3214 @Deprecated
3215 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3216 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3217 /**
3218 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3219 * {@hide}
3220 */
3221 @Deprecated
3222 public static final int TETHER_ERROR_MASTER_ERROR =
3223 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3224 /**
3225 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3226 * {@hide}
3227 */
3228 @Deprecated
3229 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3230 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3231 /**
3232 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3233 * {@hide}
3234 */
3235 @Deprecated
3236 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3237 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3238 /**
3239 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3240 * {@hide}
3241 */
3242 @Deprecated
3243 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3244 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3245 /**
3246 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3247 * {@hide}
3248 */
3249 @Deprecated
3250 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3251 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3252 /**
3253 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3254 * {@hide}
3255 */
3256 @Deprecated
3257 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3258 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3259 /**
3260 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3261 * {@hide}
3262 */
3263 @SystemApi
3264 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003265 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003266 /**
3267 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3268 * {@hide}
3269 */
3270 @Deprecated
3271 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3272 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3273 /**
3274 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3275 * {@hide}
3276 */
3277 @SystemApi
3278 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003279 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003280
3281 /**
3282 * Get a more detailed error code after a Tethering or Untethering
3283 * request asynchronously failed.
3284 *
3285 * @param iface The name of the interface of interest
3286 * @return error The error code of the last error tethering or untethering the named
3287 * interface
3288 *
3289 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3290 * {@hide}
3291 */
3292 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3293 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3294 @Deprecated
3295 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003296 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003297 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3298 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3299 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3300 // instead.
3301 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3302 }
3303 return error;
3304 }
3305
3306 /** @hide */
3307 @Retention(RetentionPolicy.SOURCE)
3308 @IntDef(value = {
3309 TETHER_ERROR_NO_ERROR,
3310 TETHER_ERROR_PROVISION_FAILED,
3311 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3312 })
3313 public @interface EntitlementResultCode {
3314 }
3315
3316 /**
3317 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3318 * entitlement succeeded.
3319 *
3320 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3321 * @hide
3322 */
3323 @SystemApi
3324 @Deprecated
3325 public interface OnTetheringEntitlementResultListener {
3326 /**
3327 * Called to notify entitlement result.
3328 *
3329 * @param resultCode an int value of entitlement result. It may be one of
3330 * {@link #TETHER_ERROR_NO_ERROR},
3331 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3332 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3333 */
3334 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3335 }
3336
3337 /**
3338 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003339 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3340 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003341 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003342 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003343 * any reason will update the cached value.
3344 *
3345 * @param type the downstream type of tethering. Must be one of
3346 * {@link #TETHERING_WIFI},
3347 * {@link #TETHERING_USB}, or
3348 * {@link #TETHERING_BLUETOOTH}.
3349 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3350 * @param executor the executor on which callback will be invoked.
3351 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3352 * notify the caller of the result of entitlement check. The listener may be called zero
3353 * or one time.
3354 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3355 * {@hide}
3356 */
3357 @SystemApi
3358 @Deprecated
3359 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3360 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3361 @NonNull @CallbackExecutor Executor executor,
3362 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003363 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003364 ResultReceiver wrappedListener = new ResultReceiver(null) {
3365 @Override
3366 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003367 final long token = Binder.clearCallingIdentity();
3368 try {
3369 executor.execute(() -> {
3370 listener.onTetheringEntitlementResult(resultCode);
3371 });
3372 } finally {
3373 Binder.restoreCallingIdentity(token);
3374 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003375 }
3376 };
3377
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003378 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003379 showEntitlementUi);
3380 }
3381
3382 /**
3383 * Report network connectivity status. This is currently used only
3384 * to alter status bar UI.
3385 * <p>This method requires the caller to hold the permission
3386 * {@link android.Manifest.permission#STATUS_BAR}.
3387 *
3388 * @param networkType The type of network you want to report on
3389 * @param percentage The quality of the connection 0 is bad, 100 is good
3390 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3391 * {@hide}
3392 */
3393 public void reportInetCondition(int networkType, int percentage) {
3394 printStackTrace();
3395 try {
3396 mService.reportInetCondition(networkType, percentage);
3397 } catch (RemoteException e) {
3398 throw e.rethrowFromSystemServer();
3399 }
3400 }
3401
3402 /**
3403 * Report a problem network to the framework. This provides a hint to the system
3404 * that there might be connectivity problems on this network and may cause
3405 * the framework to re-evaluate network connectivity and/or switch to another
3406 * network.
3407 *
3408 * @param network The {@link Network} the application was attempting to use
3409 * or {@code null} to indicate the current default network.
3410 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3411 * working and non-working connectivity.
3412 */
3413 @Deprecated
3414 public void reportBadNetwork(@Nullable Network network) {
3415 printStackTrace();
3416 try {
3417 // One of these will be ignored because it matches system's current state.
3418 // The other will trigger the necessary reevaluation.
3419 mService.reportNetworkConnectivity(network, true);
3420 mService.reportNetworkConnectivity(network, false);
3421 } catch (RemoteException e) {
3422 throw e.rethrowFromSystemServer();
3423 }
3424 }
3425
3426 /**
3427 * Report to the framework whether a network has working connectivity.
3428 * This provides a hint to the system that a particular network is providing
3429 * working connectivity or not. In response the framework may re-evaluate
3430 * the network's connectivity and might take further action thereafter.
3431 *
3432 * @param network The {@link Network} the application was attempting to use
3433 * or {@code null} to indicate the current default network.
3434 * @param hasConnectivity {@code true} if the application was able to successfully access the
3435 * Internet using {@code network} or {@code false} if not.
3436 */
3437 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3438 printStackTrace();
3439 try {
3440 mService.reportNetworkConnectivity(network, hasConnectivity);
3441 } catch (RemoteException e) {
3442 throw e.rethrowFromSystemServer();
3443 }
3444 }
3445
3446 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003447 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003448 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003449 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3450 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3451 * accessing any network, regardless of what the settings for that network are.
3452 *
3453 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3454 * proxy is likely to break networking on multiple networks. This method is only meant
3455 * for device policy clients looking to do general internal filtering or similar use cases.
3456 *
chiachangwang9473c592022-07-15 02:25:52 +00003457 * @see #getGlobalProxy
3458 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003459 *
3460 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3461 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003462 * @hide
3463 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003464 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003465 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003466 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003467 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003468 try {
3469 mService.setGlobalProxy(p);
3470 } catch (RemoteException e) {
3471 throw e.rethrowFromSystemServer();
3472 }
3473 }
3474
3475 /**
3476 * Retrieve any network-independent global HTTP proxy.
3477 *
3478 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3479 * if no global HTTP proxy is set.
3480 * @hide
3481 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003482 @SystemApi(client = MODULE_LIBRARIES)
3483 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003484 public ProxyInfo getGlobalProxy() {
3485 try {
3486 return mService.getGlobalProxy();
3487 } catch (RemoteException e) {
3488 throw e.rethrowFromSystemServer();
3489 }
3490 }
3491
3492 /**
3493 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3494 * network-specific HTTP proxy. If {@code network} is null, the
3495 * network-specific proxy returned is the proxy of the default active
3496 * network.
3497 *
3498 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3499 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3500 * or when {@code network} is {@code null},
3501 * the {@code ProxyInfo} for the default active network. Returns
3502 * {@code null} when no proxy applies or the caller doesn't have
3503 * permission to use {@code network}.
3504 * @hide
3505 */
3506 public ProxyInfo getProxyForNetwork(Network network) {
3507 try {
3508 return mService.getProxyForNetwork(network);
3509 } catch (RemoteException e) {
3510 throw e.rethrowFromSystemServer();
3511 }
3512 }
3513
3514 /**
3515 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3516 * otherwise if this process is bound to a {@link Network} using
3517 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3518 * the default network's proxy is returned.
3519 *
3520 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3521 * HTTP proxy is active.
3522 */
3523 @Nullable
3524 public ProxyInfo getDefaultProxy() {
3525 return getProxyForNetwork(getBoundNetworkForProcess());
3526 }
3527
3528 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003529 * Returns whether the hardware supports the given network type.
3530 *
3531 * This doesn't indicate there is coverage or such a network is available, just whether the
3532 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3533 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003534 *
3535 * @param networkType The network type we'd like to check
3536 * @return {@code true} if supported, else {@code false}
3537 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3538 * @hide
3539 */
3540 @Deprecated
3541 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3542 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3543 public boolean isNetworkSupported(int networkType) {
3544 try {
3545 return mService.isNetworkSupported(networkType);
3546 } catch (RemoteException e) {
3547 throw e.rethrowFromSystemServer();
3548 }
3549 }
3550
3551 /**
3552 * Returns if the currently active data network is metered. A network is
3553 * classified as metered when the user is sensitive to heavy data usage on
3554 * that connection due to monetary costs, data limitations or
3555 * battery/performance issues. You should check this before doing large
3556 * data transfers, and warn the user or delay the operation until another
3557 * network is available.
3558 *
3559 * @return {@code true} if large transfers should be avoided, otherwise
3560 * {@code false}.
3561 */
3562 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3563 public boolean isActiveNetworkMetered() {
3564 try {
3565 return mService.isActiveNetworkMetered();
3566 } catch (RemoteException e) {
3567 throw e.rethrowFromSystemServer();
3568 }
3569 }
3570
3571 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003572 * Set sign in error notification to visible or invisible
3573 *
3574 * @hide
3575 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3576 */
3577 @Deprecated
3578 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3579 String action) {
3580 try {
3581 mService.setProvisioningNotificationVisible(visible, networkType, action);
3582 } catch (RemoteException e) {
3583 throw e.rethrowFromSystemServer();
3584 }
3585 }
3586
3587 /**
3588 * Set the value for enabling/disabling airplane mode
3589 *
3590 * @param enable whether to enable airplane mode or not
3591 *
3592 * @hide
3593 */
3594 @RequiresPermission(anyOf = {
3595 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3596 android.Manifest.permission.NETWORK_SETTINGS,
3597 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3598 android.Manifest.permission.NETWORK_STACK})
3599 @SystemApi
3600 public void setAirplaneMode(boolean enable) {
3601 try {
3602 mService.setAirplaneMode(enable);
3603 } catch (RemoteException e) {
3604 throw e.rethrowFromSystemServer();
3605 }
3606 }
3607
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003608 /**
3609 * Registers the specified {@link NetworkProvider}.
3610 * Each listener must only be registered once. The listener can be unregistered with
3611 * {@link #unregisterNetworkProvider}.
3612 *
3613 * @param provider the provider to register
3614 * @return the ID of the provider. This ID must be used by the provider when registering
3615 * {@link android.net.NetworkAgent}s.
3616 * @hide
3617 */
3618 @SystemApi
3619 @RequiresPermission(anyOf = {
3620 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3621 android.Manifest.permission.NETWORK_FACTORY})
3622 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3623 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3624 throw new IllegalStateException("NetworkProviders can only be registered once");
3625 }
3626
3627 try {
3628 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3629 provider.getName());
3630 provider.setProviderId(providerId);
3631 } catch (RemoteException e) {
3632 throw e.rethrowFromSystemServer();
3633 }
3634 return provider.getProviderId();
3635 }
3636
3637 /**
3638 * Unregisters the specified NetworkProvider.
3639 *
3640 * @param provider the provider to unregister
3641 * @hide
3642 */
3643 @SystemApi
3644 @RequiresPermission(anyOf = {
3645 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3646 android.Manifest.permission.NETWORK_FACTORY})
3647 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3648 try {
3649 mService.unregisterNetworkProvider(provider.getMessenger());
3650 } catch (RemoteException e) {
3651 throw e.rethrowFromSystemServer();
3652 }
3653 provider.setProviderId(NetworkProvider.ID_NONE);
3654 }
3655
Chalard Jeand1b498b2021-01-05 08:40:09 +09003656 /**
3657 * Register or update a network offer with ConnectivityService.
3658 *
3659 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003660 * them to networking requests made by apps or the system. A callback identifies an offer
3661 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3662 * score and the capabilities of the network it might be able to bring up ; these act as
3663 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003664 * provider.
3665 *
3666 * The provider is under no obligation to be able to bring up the network it offers at any
3667 * given time. Instead, this mechanism is meant to limit requests received by providers
3668 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3669 * the quality of the network satisfying a given request to their own offer.
3670 *
3671 * An offer can be updated by calling this again with the same callback object. This is
3672 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3673 * provider with the changes caused by the changes in the offer.
3674 *
3675 * @param provider The provider making this offer.
3676 * @param score The prospective score of the network.
3677 * @param caps The prospective capabilities of the network.
3678 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003679 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003680 */
3681 @RequiresPermission(anyOf = {
3682 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3683 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003684 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003685 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3686 @NonNull final INetworkOfferCallback callback) {
3687 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003688 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003689 Objects.requireNonNull(score, "null score"),
3690 Objects.requireNonNull(caps, "null caps"),
3691 Objects.requireNonNull(callback, "null callback"));
3692 } catch (RemoteException e) {
3693 throw e.rethrowFromSystemServer();
3694 }
3695 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003696
Chalard Jeand1b498b2021-01-05 08:40:09 +09003697 /**
3698 * Withdraw a network offer made with {@link #offerNetwork}.
3699 *
3700 * @param callback The callback passed at registration time. This must be the same object
3701 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003702 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003703 */
3704 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3705 try {
3706 mService.unofferNetwork(Objects.requireNonNull(callback));
3707 } catch (RemoteException e) {
3708 throw e.rethrowFromSystemServer();
3709 }
3710 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003711 /** @hide exposed via the NetworkProvider class. */
3712 @RequiresPermission(anyOf = {
3713 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3714 android.Manifest.permission.NETWORK_FACTORY})
3715 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3716 try {
3717 mService.declareNetworkRequestUnfulfillable(request);
3718 } catch (RemoteException e) {
3719 throw e.rethrowFromSystemServer();
3720 }
3721 }
3722
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003723 /**
3724 * @hide
3725 * Register a NetworkAgent with ConnectivityService.
3726 * @return Network corresponding to NetworkAgent.
3727 */
3728 @RequiresPermission(anyOf = {
3729 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3730 android.Manifest.permission.NETWORK_FACTORY})
3731 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003732 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3733 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003734 try {
3735 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3736 } catch (RemoteException e) {
3737 throw e.rethrowFromSystemServer();
3738 }
3739 }
3740
3741 /**
3742 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3743 * changes. Should be extended by applications wanting notifications.
3744 *
3745 * A {@code NetworkCallback} is registered by calling
3746 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3747 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3748 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3749 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3750 * A {@code NetworkCallback} should be registered at most once at any time.
3751 * A {@code NetworkCallback} that has been unregistered can be registered again.
3752 */
3753 public static class NetworkCallback {
3754 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003755 * No flags associated with this callback.
3756 * @hide
3757 */
3758 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003759
Roshan Piuse08bc182020-12-22 15:10:42 -08003760 /**
lucaslinc582d502022-01-27 09:07:00 +08003761 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3762 *
3763 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3764 * Prior to Android 12, this information is always returned to apps holding the appropriate
3765 * permission, possibly noting that the app has used location.
3766 * <p>In Android 12 and above, by default the sent objects do not contain any location
3767 * information, even if the app holds the necessary permissions, and the system does not
3768 * take note of location usage by the app. Apps can request that location information is
3769 * included, in which case the system will check location permission and the location
3770 * toggle state, and take note of location usage by the app if any such information is
3771 * returned.
3772 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003773 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3774 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3775 * <p>
3776 * These include:
3777 * <li> Some transport info instances (retrieved via
3778 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3779 * contain location sensitive information.
3780 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003781 * sensitive for wifi suggestor apps (i.e using
3782 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003783 * </p>
3784 * <p>
3785 * Note:
3786 * <li> Retrieving this location sensitive information (subject to app's location
3787 * permissions) will be noted by system. </li>
3788 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003789 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003790 */
Roshan Pius189d0092021-03-11 21:16:44 -08003791 // Note: Some existing fields which are location sensitive may still be included without
3792 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003793 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3794
3795 /** @hide */
3796 @Retention(RetentionPolicy.SOURCE)
3797 @IntDef(flag = true, prefix = "FLAG_", value = {
3798 FLAG_NONE,
3799 FLAG_INCLUDE_LOCATION_INFO
3800 })
3801 public @interface Flag { }
3802
3803 /**
3804 * All the valid flags for error checking.
3805 */
3806 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3807
3808 public NetworkCallback() {
3809 this(FLAG_NONE);
3810 }
3811
3812 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003813 if ((flags & VALID_FLAGS) != flags) {
3814 throw new IllegalArgumentException("Invalid flags");
3815 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003816 mFlags = flags;
3817 }
3818
3819 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003820 * Called when the framework connects to a new network to evaluate whether it satisfies this
3821 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3822 * callback. There is no guarantee that this new network will satisfy any requests, or that
3823 * the network will stay connected for longer than the time necessary to evaluate it.
3824 * <p>
3825 * Most applications <b>should not</b> act on this callback, and should instead use
3826 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3827 * the framework in properly evaluating the network &mdash; for example, an application that
3828 * can automatically log in to a captive portal without user intervention.
3829 *
3830 * @param network The {@link Network} of the network that is being evaluated.
3831 *
3832 * @hide
3833 */
3834 public void onPreCheck(@NonNull Network network) {}
3835
3836 /**
3837 * Called when the framework connects and has declared a new network ready for use.
3838 * This callback may be called more than once if the {@link Network} that is
3839 * satisfying the request changes.
3840 *
3841 * @param network The {@link Network} of the satisfying network.
3842 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3843 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3844 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3845 * @hide
3846 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003847 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003848 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003849 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003850 // Internally only this method is called when a new network is available, and
3851 // it calls the callback in the same way and order that older versions used
3852 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003853 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3854 onBlockedStatusChanged(network, blocked);
3855 }
3856
3857 /**
3858 * Legacy variant of onAvailable that takes a boolean blocked reason.
3859 *
3860 * This method has never been public API, but it's not final, so there may be apps that
3861 * implemented it and rely on it being called. Do our best not to break them.
3862 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3863 * this method is called. There does not seem to be a way to avoid this.
3864 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3865 *
3866 * @hide
3867 */
3868 public void onAvailable(@NonNull Network network,
3869 @NonNull NetworkCapabilities networkCapabilities,
3870 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003871 onAvailable(network);
3872 if (!networkCapabilities.hasCapability(
3873 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3874 onNetworkSuspended(network);
3875 }
3876 onCapabilitiesChanged(network, networkCapabilities);
3877 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003878 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003879 }
3880
3881 /**
3882 * Called when the framework connects and has declared a new network ready for use.
3883 *
3884 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3885 * be available at the same time, and onAvailable will be called for each of these as they
3886 * appear.
3887 *
3888 * <p>For callbacks registered with {@link #requestNetwork} and
3889 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3890 * is the new best network for this request and is now tracked by this callback ; this
3891 * callback will no longer receive method calls about other networks that may have been
3892 * passed to this method previously. The previously-best network may have disconnected, or
3893 * it may still be around and the newly-best network may simply be better.
3894 *
3895 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3896 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3897 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3898 * to {@link #onBlockedStatusChanged(Network, boolean)}.
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 (there is no guarantee the objects
3903 * returned by these methods will be current). Instead, wait for a call to
3904 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3905 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3906 * to be well-ordered with respect to other callbacks.
3907 *
3908 * @param network The {@link Network} of the satisfying network.
3909 */
3910 public void onAvailable(@NonNull Network network) {}
3911
3912 /**
3913 * Called when the network is about to be lost, typically because there are no outstanding
3914 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3915 * with the new replacement network for graceful handover. This method is not guaranteed
3916 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3917 * network is suddenly disconnected.
3918 *
3919 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3920 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3921 * this callback as this is prone to race conditions ; calling these methods while in a
3922 * callback may return an outdated or even a null object.
3923 *
3924 * @param network The {@link Network} that is about to be lost.
3925 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3926 * connected for graceful handover; note that the network may still
3927 * suffer a hard loss at any time.
3928 */
3929 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3930
3931 /**
3932 * Called when a network disconnects or otherwise no longer satisfies this request or
3933 * callback.
3934 *
3935 * <p>If the callback was registered with requestNetwork() or
3936 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3937 * returned by onAvailable() when that network is lost and no other network satisfies
3938 * the criteria of the request.
3939 *
3940 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3941 * each network which no longer satisfies the criteria of the callback.
3942 *
3943 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3944 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3945 * this callback as this is prone to race conditions ; calling these methods while in a
3946 * callback may return an outdated or even a null object.
3947 *
3948 * @param network The {@link Network} lost.
3949 */
3950 public void onLost(@NonNull Network network) {}
3951
3952 /**
3953 * Called if no network is found within the timeout time specified in
3954 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3955 * requested network request cannot be fulfilled (whether or not a timeout was
3956 * specified). When this callback is invoked the associated
3957 * {@link NetworkRequest} will have already been removed and released, as if
3958 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3959 */
3960 public void onUnavailable() {}
3961
3962 /**
3963 * Called when the network corresponding to this request changes capabilities but still
3964 * satisfies the requested criteria.
3965 *
3966 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3967 * to be called immediately after {@link #onAvailable}.
3968 *
3969 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3970 * ConnectivityManager methods in this callback as this is prone to race conditions :
3971 * calling these methods while in a callback may return an outdated or even a null object.
3972 *
3973 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003974 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003975 * network.
3976 */
3977 public void onCapabilitiesChanged(@NonNull Network network,
3978 @NonNull NetworkCapabilities networkCapabilities) {}
3979
3980 /**
3981 * Called when the network corresponding to this request changes {@link LinkProperties}.
3982 *
3983 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3984 * to be called immediately after {@link #onAvailable}.
3985 *
3986 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3987 * ConnectivityManager methods in this callback as this is prone to race conditions :
3988 * calling these methods while in a callback may return an outdated or even a null object.
3989 *
3990 * @param network The {@link Network} whose link properties have changed.
3991 * @param linkProperties The new {@link LinkProperties} for this network.
3992 */
3993 public void onLinkPropertiesChanged(@NonNull Network network,
3994 @NonNull LinkProperties linkProperties) {}
3995
3996 /**
3997 * Called when the network the framework connected to for this request suspends data
3998 * transmission temporarily.
3999 *
4000 * <p>This generally means that while the TCP connections are still live temporarily
4001 * network data fails to transfer. To give a specific example, this is used on cellular
4002 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4003 * means read operations on sockets on this network will block once the buffers are
4004 * drained, and write operations will block once the buffers are full.
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 (there is no guarantee the objects
4009 * returned by these methods will be current).
4010 *
4011 * @hide
4012 */
4013 public void onNetworkSuspended(@NonNull Network network) {}
4014
4015 /**
4016 * Called when the network the framework connected to for this request
4017 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4018 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4019
4020 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4021 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4022 * this callback as this is prone to race conditions : calling these methods while in a
4023 * callback may return an outdated or even a null object.
4024 *
4025 * @hide
4026 */
4027 public void onNetworkResumed(@NonNull Network network) {}
4028
4029 /**
4030 * Called when access to the specified network is blocked or unblocked.
4031 *
4032 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4033 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4034 * this callback as this is prone to race conditions : calling these methods while in a
4035 * callback may return an outdated or even a null object.
4036 *
4037 * @param network The {@link Network} whose blocked status has changed.
4038 * @param blocked The blocked status of this {@link Network}.
4039 */
4040 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4041
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004042 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004043 * Called when access to the specified network is blocked or unblocked, or the reason for
4044 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004045 *
4046 * If a NetworkCallback object implements this method,
4047 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4048 *
4049 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4050 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4051 * this callback as this is prone to race conditions : calling these methods while in a
4052 * callback may return an outdated or even a null object.
4053 *
4054 * @param network The {@link Network} whose blocked status has changed.
4055 * @param blocked The blocked status of this {@link Network}.
4056 * @hide
4057 */
4058 @SystemApi(client = MODULE_LIBRARIES)
4059 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4060 onBlockedStatusChanged(network, blocked != 0);
4061 }
4062
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004063 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004064 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004065 }
4066
4067 /**
4068 * Constant error codes used by ConnectivityService to communicate about failures and errors
4069 * across a Binder boundary.
4070 * @hide
4071 */
4072 public interface Errors {
4073 int TOO_MANY_REQUESTS = 1;
4074 }
4075
4076 /** @hide */
4077 public static class TooManyRequestsException extends RuntimeException {}
4078
4079 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4080 switch (e.errorCode) {
4081 case Errors.TOO_MANY_REQUESTS:
4082 return new TooManyRequestsException();
4083 default:
4084 Log.w(TAG, "Unknown service error code " + e.errorCode);
4085 return new RuntimeException(e);
4086 }
4087 }
4088
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004089 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004090 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004091 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004092 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004093 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004094 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004095 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004096 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004097 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004098 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004099 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004100 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004101 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004102 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004103 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004104 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004105 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004106 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004107 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004108 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004109 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004110 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004111
4112 /** @hide */
4113 public static String getCallbackName(int whichCallback) {
4114 switch (whichCallback) {
4115 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4116 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4117 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4118 case CALLBACK_LOST: return "CALLBACK_LOST";
4119 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4120 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4121 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4122 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4123 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4124 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4125 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4126 default:
4127 return Integer.toString(whichCallback);
4128 }
4129 }
4130
zhujiatai79b0de92022-09-22 15:44:02 +08004131 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004132 private static final String TAG = "ConnectivityManager.CallbackHandler";
4133 private static final boolean DBG = false;
4134
4135 CallbackHandler(Looper looper) {
4136 super(looper);
4137 }
4138
4139 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004140 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004141 }
4142
4143 @Override
4144 public void handleMessage(Message message) {
4145 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004146 // the sInstance can't be null because to send this message a ConnectivityManager
4147 // instance must have been created prior to creating the thread on which this
4148 // Handler is running.
4149 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004150 return;
4151 }
4152
4153 final NetworkRequest request = getObject(message, NetworkRequest.class);
4154 final Network network = getObject(message, Network.class);
4155 final NetworkCallback callback;
4156 synchronized (sCallbacks) {
4157 callback = sCallbacks.get(request);
4158 if (callback == null) {
4159 Log.w(TAG,
4160 "callback not found for " + getCallbackName(message.what) + " message");
4161 return;
4162 }
4163 if (message.what == CALLBACK_UNAVAIL) {
4164 sCallbacks.remove(request);
4165 callback.networkRequest = ALREADY_UNREGISTERED;
4166 }
4167 }
4168 if (DBG) {
4169 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4170 }
4171
4172 switch (message.what) {
4173 case CALLBACK_PRECHECK: {
4174 callback.onPreCheck(network);
4175 break;
4176 }
4177 case CALLBACK_AVAILABLE: {
4178 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4179 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004180 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004181 break;
4182 }
4183 case CALLBACK_LOSING: {
4184 callback.onLosing(network, message.arg1);
4185 break;
4186 }
4187 case CALLBACK_LOST: {
4188 callback.onLost(network);
4189 break;
4190 }
4191 case CALLBACK_UNAVAIL: {
4192 callback.onUnavailable();
4193 break;
4194 }
4195 case CALLBACK_CAP_CHANGED: {
4196 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4197 callback.onCapabilitiesChanged(network, cap);
4198 break;
4199 }
4200 case CALLBACK_IP_CHANGED: {
4201 LinkProperties lp = getObject(message, LinkProperties.class);
4202 callback.onLinkPropertiesChanged(network, lp);
4203 break;
4204 }
4205 case CALLBACK_SUSPENDED: {
4206 callback.onNetworkSuspended(network);
4207 break;
4208 }
4209 case CALLBACK_RESUMED: {
4210 callback.onNetworkResumed(network);
4211 break;
4212 }
4213 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004214 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004215 }
4216 }
4217 }
4218
4219 private <T> T getObject(Message msg, Class<T> c) {
4220 return (T) msg.getData().getParcelable(c.getSimpleName());
4221 }
4222 }
4223
4224 private CallbackHandler getDefaultHandler() {
4225 synchronized (sCallbacks) {
4226 if (sCallbackHandler == null) {
4227 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4228 }
4229 return sCallbackHandler;
4230 }
4231 }
4232
4233 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4234 private static CallbackHandler sCallbackHandler;
4235
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004236 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4237 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4238 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004239 printStackTrace();
4240 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004241 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4242 throw new IllegalArgumentException("null NetworkCapabilities");
4243 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004244 final NetworkRequest request;
4245 final String callingPackageName = mContext.getOpPackageName();
4246 try {
4247 synchronized(sCallbacks) {
4248 if (callback.networkRequest != null
4249 && callback.networkRequest != ALREADY_UNREGISTERED) {
4250 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4251 // and requests (http://b/20701525).
4252 Log.e(TAG, "NetworkCallback was already registered");
4253 }
4254 Messenger messenger = new Messenger(handler);
4255 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004256 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004257 if (reqType == LISTEN) {
4258 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004259 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004260 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004261 } else {
4262 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004263 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4264 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004265 }
4266 if (request != null) {
4267 sCallbacks.put(request, callback);
4268 }
4269 callback.networkRequest = request;
4270 }
4271 } catch (RemoteException e) {
4272 throw e.rethrowFromSystemServer();
4273 } catch (ServiceSpecificException e) {
4274 throw convertServiceException(e);
4275 }
4276 return request;
4277 }
4278
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004279 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4280 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4281 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4282 legacyType, handler);
4283 }
4284
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004285 /**
4286 * Helper function to request a network with a particular legacy type.
4287 *
4288 * This API is only for use in internal system code that requests networks with legacy type and
4289 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4290 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4291 *
4292 * @param request {@link NetworkRequest} describing this request.
4293 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4294 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4295 * be a positive value (i.e. >0).
4296 * @param legacyType to specify the network type(#TYPE_*).
4297 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4298 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4299 * the callback must not be shared - it uniquely specifies this request.
4300 *
4301 * @hide
4302 */
4303 @SystemApi
4304 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4305 public void requestNetwork(@NonNull NetworkRequest request,
4306 int timeoutMs, int legacyType, @NonNull Handler handler,
4307 @NonNull NetworkCallback networkCallback) {
4308 if (legacyType == TYPE_NONE) {
4309 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4310 }
4311 CallbackHandler cbHandler = new CallbackHandler(handler);
4312 NetworkCapabilities nc = request.networkCapabilities;
4313 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4314 }
4315
4316 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004317 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004318 *
4319 * <p>This method will attempt to find the best network that matches the passed
4320 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4321 * criteria. The platform will evaluate which network is the best at its own discretion.
4322 * Throughput, latency, cost per byte, policy, user preference and other considerations
4323 * may be factored in the decision of what is considered the best network.
4324 *
4325 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4326 * matching this request, while always attempting to match the request to a better network if
4327 * possible. If a better match is found, the platform will switch this request to the now-best
4328 * network and inform the app of the newly best network by invoking
4329 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4330 * will not try to maintain any other network than the best one currently matching the request:
4331 * a network not matching any network request may be disconnected at any time.
4332 *
4333 * <p>For example, an application could use this method to obtain a connected cellular network
4334 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4335 * radio to consume additional power. Or, an application could inform the system that it wants
4336 * a network supporting sending MMSes and have the system let it know about the currently best
4337 * MMS-supporting network through the provided {@link NetworkCallback}.
4338 *
4339 * <p>The status of the request can be followed by listening to the various callbacks described
4340 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4341 * used to direct traffic to the network (although accessing some networks may be subject to
4342 * holding specific permissions). Callers will learn about the specific characteristics of the
4343 * network through
4344 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4345 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4346 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4347 * matching the request at any given time; therefore when a better network matching the request
4348 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4349 * with the new network after which no further updates are given about the previously-best
4350 * network, unless it becomes the best again at some later time. All callbacks are invoked
4351 * in order on the same thread, which by default is a thread created by the framework running
4352 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004353 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004354 * callbacks are invoked.
4355 *
4356 * <p>This{@link NetworkRequest} will live until released via
4357 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4358 * which point the system may let go of the network at any time.
4359 *
4360 * <p>A version of this method which takes a timeout is
4361 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4362 * wait for a limited amount of time for the network to become unavailable.
4363 *
4364 * <p>It is presently unsupported to request a network with mutable
4365 * {@link NetworkCapabilities} such as
4366 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4367 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4368 * as these {@code NetworkCapabilities} represent states that a particular
4369 * network may never attain, and whether a network will attain these states
4370 * is unknown prior to bringing up the network so the framework does not
4371 * know how to go about satisfying a request with these capabilities.
4372 *
4373 * <p>This method requires the caller to hold either the
4374 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4375 * or the ability to modify system settings as determined by
4376 * {@link android.provider.Settings.System#canWrite}.</p>
4377 *
4378 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4379 * number of outstanding requests to 100 per app (identified by their UID), shared with
4380 * all variants of this method, of {@link #registerNetworkCallback} as well as
4381 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4382 * Requesting a network with this method will count toward this limit. If this limit is
4383 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4384 * make sure to unregister the callbacks with
4385 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4386 *
4387 * @param request {@link NetworkRequest} describing this request.
4388 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4389 * the callback must not be shared - it uniquely specifies this request.
4390 * The callback is invoked on the default internal Handler.
4391 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4392 * @throws SecurityException if missing the appropriate permissions.
4393 * @throws RuntimeException if the app already has too many callbacks registered.
4394 */
4395 public void requestNetwork(@NonNull NetworkRequest request,
4396 @NonNull NetworkCallback networkCallback) {
4397 requestNetwork(request, networkCallback, getDefaultHandler());
4398 }
4399
4400 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004401 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004402 *
4403 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4404 * but runs all the callbacks on the passed Handler.
4405 *
4406 * <p>This method has the same permission requirements as
4407 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4408 * and throws the same exceptions in the same conditions.
4409 *
4410 * @param request {@link NetworkRequest} describing this request.
4411 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4412 * the callback must not be shared - it uniquely specifies this request.
4413 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4414 */
4415 public void requestNetwork(@NonNull NetworkRequest request,
4416 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4417 CallbackHandler cbHandler = new CallbackHandler(handler);
4418 NetworkCapabilities nc = request.networkCapabilities;
4419 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4420 }
4421
4422 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004423 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004424 * by a timeout.
4425 *
4426 * This function behaves identically to the non-timed-out version
4427 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4428 * is not found within the given time (in milliseconds) the
4429 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4430 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4431 * not have to be released if timed-out (it is automatically released). Unregistering a
4432 * request that timed out is not an error.
4433 *
4434 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4435 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4436 * for that purpose. Calling this method will attempt to bring up the requested network.
4437 *
4438 * <p>This method has the same permission requirements as
4439 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4440 * and throws the same exceptions in the same conditions.
4441 *
4442 * @param request {@link NetworkRequest} describing this request.
4443 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4444 * the callback must not be shared - it uniquely specifies this request.
4445 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4446 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4447 * be a positive value (i.e. >0).
4448 */
4449 public void requestNetwork(@NonNull NetworkRequest request,
4450 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4451 checkTimeout(timeoutMs);
4452 NetworkCapabilities nc = request.networkCapabilities;
4453 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4454 getDefaultHandler());
4455 }
4456
4457 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004458 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004459 * by a timeout.
4460 *
4461 * This method behaves identically to
4462 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4463 * on the passed Handler.
4464 *
4465 * <p>This method has the same permission requirements as
4466 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4467 * and throws the same exceptions in the same conditions.
4468 *
4469 * @param request {@link NetworkRequest} describing this request.
4470 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4471 * the callback must not be shared - it uniquely specifies this request.
4472 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4473 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4474 * before {@link NetworkCallback#onUnavailable} is called.
4475 */
4476 public void requestNetwork(@NonNull NetworkRequest request,
4477 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4478 checkTimeout(timeoutMs);
4479 CallbackHandler cbHandler = new CallbackHandler(handler);
4480 NetworkCapabilities nc = request.networkCapabilities;
4481 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4482 }
4483
4484 /**
4485 * The lookup key for a {@link Network} object included with the intent after
4486 * successfully finding a network for the applications request. Retrieve it with
4487 * {@link android.content.Intent#getParcelableExtra(String)}.
4488 * <p>
4489 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4490 * then you must get a ConnectivityManager instance before doing so.
4491 */
4492 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4493
4494 /**
4495 * The lookup key for a {@link NetworkRequest} object included with the intent after
4496 * successfully finding a network for the applications request. Retrieve it with
4497 * {@link android.content.Intent#getParcelableExtra(String)}.
4498 */
4499 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4500
4501
4502 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004503 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004504 *
4505 * This function behaves identically to the version that takes a NetworkCallback, but instead
4506 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4507 * the request may outlive the calling application and get called back when a suitable
4508 * network is found.
4509 * <p>
4510 * The operation is an Intent broadcast that goes to a broadcast receiver that
4511 * you registered with {@link Context#registerReceiver} or through the
4512 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4513 * <p>
4514 * The operation Intent is delivered with two extras, a {@link Network} typed
4515 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4516 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4517 * the original requests parameters. It is important to create a new,
4518 * {@link NetworkCallback} based request before completing the processing of the
4519 * Intent to reserve the network or it will be released shortly after the Intent
4520 * is processed.
4521 * <p>
4522 * If there is already a request for this Intent registered (with the equality of
4523 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4524 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4525 * <p>
4526 * The request may be released normally by calling
4527 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4528 * <p>It is presently unsupported to request a network with either
4529 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4530 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4531 * as these {@code NetworkCapabilities} represent states that a particular
4532 * network may never attain, and whether a network will attain these states
4533 * is unknown prior to bringing up the network so the framework does not
4534 * know how to go about satisfying a request with these capabilities.
4535 *
4536 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4537 * number of outstanding requests to 100 per app (identified by their UID), shared with
4538 * all variants of this method, of {@link #registerNetworkCallback} as well as
4539 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4540 * Requesting a network with this method will count toward this limit. If this limit is
4541 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4542 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4543 * or {@link #releaseNetworkRequest(PendingIntent)}.
4544 *
4545 * <p>This method requires the caller to hold either the
4546 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4547 * or the ability to modify system settings as determined by
4548 * {@link android.provider.Settings.System#canWrite}.</p>
4549 *
4550 * @param request {@link NetworkRequest} describing this request.
4551 * @param operation Action to perform when the network is available (corresponds
4552 * to the {@link NetworkCallback#onAvailable} call. Typically
4553 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4554 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4555 * @throws SecurityException if missing the appropriate permissions.
4556 * @throws RuntimeException if the app already has too many callbacks registered.
4557 */
4558 public void requestNetwork(@NonNull NetworkRequest request,
4559 @NonNull PendingIntent operation) {
4560 printStackTrace();
4561 checkPendingIntentNotNull(operation);
4562 try {
4563 mService.pendingRequestForNetwork(
4564 request.networkCapabilities, operation, mContext.getOpPackageName(),
4565 getAttributionTag());
4566 } catch (RemoteException e) {
4567 throw e.rethrowFromSystemServer();
4568 } catch (ServiceSpecificException e) {
4569 throw convertServiceException(e);
4570 }
4571 }
4572
4573 /**
4574 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4575 * <p>
4576 * This method has the same behavior as
4577 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4578 * releasing network resources and disconnecting.
4579 *
4580 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4581 * PendingIntent passed to
4582 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4583 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4584 */
4585 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4586 printStackTrace();
4587 checkPendingIntentNotNull(operation);
4588 try {
4589 mService.releasePendingNetworkRequest(operation);
4590 } catch (RemoteException e) {
4591 throw e.rethrowFromSystemServer();
4592 }
4593 }
4594
4595 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004596 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004597 }
4598
4599 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004600 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004601 }
4602
4603 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004604 if (timeoutMs <= 0) {
4605 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4606 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004607 }
4608
4609 /**
4610 * Registers to receive notifications about all networks which satisfy the given
4611 * {@link NetworkRequest}. The callbacks will continue to be called until
4612 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4613 * called.
4614 *
4615 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4616 * number of outstanding requests to 100 per app (identified by their UID), shared with
4617 * all variants of this method, of {@link #requestNetwork} as well as
4618 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4619 * Requesting a network with this method will count toward this limit. If this limit is
4620 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4621 * make sure to unregister the callbacks with
4622 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4623 *
4624 * @param request {@link NetworkRequest} describing this request.
4625 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4626 * networks change state.
4627 * The callback is invoked on the default internal Handler.
4628 * @throws RuntimeException if the app already has too many callbacks registered.
4629 */
4630 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4631 public void registerNetworkCallback(@NonNull NetworkRequest request,
4632 @NonNull NetworkCallback networkCallback) {
4633 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4634 }
4635
4636 /**
4637 * Registers to receive notifications about all networks which satisfy the given
4638 * {@link NetworkRequest}. The callbacks will continue to be called until
4639 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4640 * called.
4641 *
4642 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4643 * number of outstanding requests to 100 per app (identified by their UID), shared with
4644 * all variants of this method, of {@link #requestNetwork} as well as
4645 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4646 * Requesting a network with this method will count toward this limit. If this limit is
4647 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4648 * make sure to unregister the callbacks with
4649 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4650 *
4651 *
4652 * @param request {@link NetworkRequest} describing this request.
4653 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4654 * networks change state.
4655 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4656 * @throws RuntimeException if the app already has too many callbacks registered.
4657 */
4658 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4659 public void registerNetworkCallback(@NonNull NetworkRequest request,
4660 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4661 CallbackHandler cbHandler = new CallbackHandler(handler);
4662 NetworkCapabilities nc = request.networkCapabilities;
4663 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4664 }
4665
4666 /**
4667 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4668 * {@link NetworkRequest}.
4669 *
4670 * This function behaves identically to the version that takes a NetworkCallback, but instead
4671 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4672 * the request may outlive the calling application and get called back when a suitable
4673 * network is found.
4674 * <p>
4675 * The operation is an Intent broadcast that goes to a broadcast receiver that
4676 * you registered with {@link Context#registerReceiver} or through the
4677 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4678 * <p>
4679 * The operation Intent is delivered with two extras, a {@link Network} typed
4680 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4681 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4682 * the original requests parameters.
4683 * <p>
4684 * If there is already a request for this Intent registered (with the equality of
4685 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4686 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4687 * <p>
4688 * The request may be released normally by calling
4689 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4690 *
4691 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4692 * number of outstanding requests to 100 per app (identified by their UID), shared with
4693 * all variants of this method, of {@link #requestNetwork} as well as
4694 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4695 * Requesting a network with this method will count toward this limit. If this limit is
4696 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4697 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4698 * or {@link #releaseNetworkRequest(PendingIntent)}.
4699 *
4700 * @param request {@link NetworkRequest} describing this request.
4701 * @param operation Action to perform when the network is available (corresponds
4702 * to the {@link NetworkCallback#onAvailable} call. Typically
4703 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4704 * @throws RuntimeException if the app already has too many callbacks registered.
4705 */
4706 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4707 public void registerNetworkCallback(@NonNull NetworkRequest request,
4708 @NonNull PendingIntent operation) {
4709 printStackTrace();
4710 checkPendingIntentNotNull(operation);
4711 try {
4712 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004713 request.networkCapabilities, operation, mContext.getOpPackageName(),
4714 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004715 } catch (RemoteException e) {
4716 throw e.rethrowFromSystemServer();
4717 } catch (ServiceSpecificException e) {
4718 throw convertServiceException(e);
4719 }
4720 }
4721
4722 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004723 * Registers to receive notifications about changes in the application's default network. This
4724 * may be a physical network or a virtual network, such as a VPN that applies to the
4725 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004726 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4727 *
4728 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4729 * number of outstanding requests to 100 per app (identified by their UID), shared with
4730 * all variants of this method, of {@link #requestNetwork} as well as
4731 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4732 * Requesting a network with this method will count toward this limit. If this limit is
4733 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4734 * make sure to unregister the callbacks with
4735 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4736 *
4737 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004738 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004739 * The callback is invoked on the default internal Handler.
4740 * @throws RuntimeException if the app already has too many callbacks registered.
4741 */
4742 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4743 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4744 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4745 }
4746
4747 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004748 * Registers to receive notifications about changes in the application's default network. This
4749 * may be a physical network or a virtual network, such as a VPN that applies to the
4750 * application. The callbacks will continue to be called until either the application exits or
4751 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4752 *
4753 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4754 * number of outstanding requests to 100 per app (identified by their UID), shared with
4755 * all variants of this method, of {@link #requestNetwork} as well as
4756 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4757 * Requesting a network with this method will count toward this limit. If this limit is
4758 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4759 * make sure to unregister the callbacks with
4760 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4761 *
4762 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4763 * application's default network changes.
4764 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4765 * @throws RuntimeException if the app already has too many callbacks registered.
4766 */
4767 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4768 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4769 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004770 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004771 }
4772
4773 /**
4774 * Registers to receive notifications about changes in the default network for the specified
4775 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4776 * UID. The callbacks will continue to be called until either the application exits or
4777 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4778 *
4779 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4780 * number of outstanding requests to 100 per app (identified by their UID), shared with
4781 * all variants of this method, of {@link #requestNetwork} as well as
4782 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4783 * Requesting a network with this method will count toward this limit. If this limit is
4784 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4785 * make sure to unregister the callbacks with
4786 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4787 *
4788 * @param uid the UID for which to track default network changes.
4789 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4790 * UID's default network changes.
4791 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4792 * @throws RuntimeException if the app already has too many callbacks registered.
4793 * @hide
4794 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004795 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004796 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4797 @RequiresPermission(anyOf = {
4798 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4799 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004800 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004801 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004802 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004803 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004804 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4805 }
4806
4807 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004808 * Registers to receive notifications about changes in the system default network. The callbacks
4809 * will continue to be called until either the application exits or
4810 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4811 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004812 * This method should not be used to determine networking state seen by applications, because in
4813 * many cases, most or even all application traffic may not use the default network directly,
4814 * and traffic from different applications may go on different networks by default. As an
4815 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4816 * and not onto the system default network. Applications or system components desiring to do
4817 * determine network state as seen by applications should use other methods such as
4818 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4819 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004820 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4821 * number of outstanding requests to 100 per app (identified by their UID), shared with
4822 * all variants of this method, of {@link #requestNetwork} as well as
4823 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4824 * Requesting a network with this method will count toward this limit. If this limit is
4825 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4826 * make sure to unregister the callbacks with
4827 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4828 *
4829 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4830 * system default network changes.
4831 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4832 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004833 *
4834 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004835 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004836 @SystemApi(client = MODULE_LIBRARIES)
4837 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4838 @RequiresPermission(anyOf = {
4839 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004840 android.Manifest.permission.NETWORK_SETTINGS,
4841 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004842 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004843 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004844 CallbackHandler cbHandler = new CallbackHandler(handler);
4845 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004846 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004847 }
4848
4849 /**
junyulaibd123062021-03-15 11:48:48 +08004850 * Registers to receive notifications about the best matching network which satisfy the given
4851 * {@link NetworkRequest}. The callbacks will continue to be called until
4852 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4853 * called.
4854 *
4855 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4856 * number of outstanding requests to 100 per app (identified by their UID), shared with
4857 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4858 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4859 * Requesting a network with this method will count toward this limit. If this limit is
4860 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4861 * make sure to unregister the callbacks with
4862 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4863 *
4864 *
4865 * @param request {@link NetworkRequest} describing this request.
4866 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4867 * networks change state.
4868 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4869 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004870 */
junyulai5a5c99b2021-03-05 15:51:17 +08004871 @SuppressLint("ExecutorRegistration")
4872 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4873 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4874 final NetworkCapabilities nc = request.networkCapabilities;
4875 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004876 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004877 }
4878
4879 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004880 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4881 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4882 * network connection for updated bandwidth information. The caller will be notified via
4883 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4884 * method assumes that the caller has previously called
4885 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4886 * changes.
4887 *
4888 * @param network {@link Network} specifying which network you're interested.
4889 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4890 */
4891 public boolean requestBandwidthUpdate(@NonNull Network network) {
4892 try {
4893 return mService.requestBandwidthUpdate(network);
4894 } catch (RemoteException e) {
4895 throw e.rethrowFromSystemServer();
4896 }
4897 }
4898
4899 /**
4900 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4901 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4902 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09004903 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
4904 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004905 *
4906 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4907 * triggering it as soon as this call returns.
4908 *
4909 * @param networkCallback The {@link NetworkCallback} used when making the request.
4910 */
4911 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4912 printStackTrace();
4913 checkCallbackNotNull(networkCallback);
4914 final List<NetworkRequest> reqs = new ArrayList<>();
4915 // Find all requests associated to this callback and stop callback triggers immediately.
4916 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4917 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004918 if (networkCallback.networkRequest == null) {
4919 throw new IllegalArgumentException("NetworkCallback was not registered");
4920 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004921 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4922 Log.d(TAG, "NetworkCallback was already unregistered");
4923 return;
4924 }
4925 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4926 if (e.getValue() == networkCallback) {
4927 reqs.add(e.getKey());
4928 }
4929 }
4930 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4931 for (NetworkRequest r : reqs) {
4932 try {
4933 mService.releaseNetworkRequest(r);
4934 } catch (RemoteException e) {
4935 throw e.rethrowFromSystemServer();
4936 }
4937 // Only remove mapping if rpc was successful.
4938 sCallbacks.remove(r);
4939 }
4940 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4941 }
4942 }
4943
4944 /**
4945 * Unregisters a callback previously registered via
4946 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4947 *
4948 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4949 * PendingIntent passed to
4950 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4951 * Cannot be null.
4952 */
4953 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4954 releaseNetworkRequest(operation);
4955 }
4956
4957 /**
4958 * Informs the system whether it should switch to {@code network} regardless of whether it is
4959 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4960 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4961 * the system default network regardless of any other network that's currently connected. If
4962 * {@code always} is true, then the choice is remembered, so that the next time the user
4963 * connects to this network, the system will switch to it.
4964 *
4965 * @param network The network to accept.
4966 * @param accept Whether to accept the network even if unvalidated.
4967 * @param always Whether to remember this choice in the future.
4968 *
4969 * @hide
4970 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004971 @SystemApi(client = MODULE_LIBRARIES)
4972 @RequiresPermission(anyOf = {
4973 android.Manifest.permission.NETWORK_SETTINGS,
4974 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4975 android.Manifest.permission.NETWORK_STACK,
4976 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4977 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004978 try {
4979 mService.setAcceptUnvalidated(network, accept, always);
4980 } catch (RemoteException e) {
4981 throw e.rethrowFromSystemServer();
4982 }
4983 }
4984
4985 /**
4986 * Informs the system whether it should consider the network as validated even if it only has
4987 * partial connectivity. If {@code accept} is true, then the network will be considered as
4988 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4989 * is remembered, so that the next time the user connects to this network, the system will
4990 * switch to it.
4991 *
4992 * @param network The network to accept.
4993 * @param accept Whether to consider the network as validated even if it has partial
4994 * connectivity.
4995 * @param always Whether to remember this choice in the future.
4996 *
4997 * @hide
4998 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004999 @SystemApi(client = MODULE_LIBRARIES)
5000 @RequiresPermission(anyOf = {
5001 android.Manifest.permission.NETWORK_SETTINGS,
5002 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5003 android.Manifest.permission.NETWORK_STACK,
5004 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5005 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5006 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005007 try {
5008 mService.setAcceptPartialConnectivity(network, accept, always);
5009 } catch (RemoteException e) {
5010 throw e.rethrowFromSystemServer();
5011 }
5012 }
5013
5014 /**
5015 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5016 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5017 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5018 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5019 *
5020 * @param network The network to accept.
5021 *
5022 * @hide
5023 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005024 @SystemApi(client = MODULE_LIBRARIES)
5025 @RequiresPermission(anyOf = {
5026 android.Manifest.permission.NETWORK_SETTINGS,
5027 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5028 android.Manifest.permission.NETWORK_STACK,
5029 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5030 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005031 try {
5032 mService.setAvoidUnvalidated(network);
5033 } catch (RemoteException e) {
5034 throw e.rethrowFromSystemServer();
5035 }
5036 }
5037
5038 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005039 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005040 *
5041 * @param timeMs The expired current time. The value should be set within a limited time from
5042 * now.
5043 *
5044 * @hide
5045 */
5046 public void setTestAllowBadWifiUntil(long timeMs) {
5047 try {
5048 mService.setTestAllowBadWifiUntil(timeMs);
5049 } catch (RemoteException e) {
5050 throw e.rethrowFromSystemServer();
5051 }
5052 }
5053
5054 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005055 * Requests that the system open the captive portal app on the specified network.
5056 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005057 * <p>This is to be used on networks where a captive portal was detected, as per
5058 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5059 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005060 * @param network The network to log into.
5061 *
5062 * @hide
5063 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005064 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5065 @RequiresPermission(anyOf = {
5066 android.Manifest.permission.NETWORK_SETTINGS,
5067 android.Manifest.permission.NETWORK_STACK,
5068 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5069 })
5070 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005071 try {
5072 mService.startCaptivePortalApp(network);
5073 } catch (RemoteException e) {
5074 throw e.rethrowFromSystemServer();
5075 }
5076 }
5077
5078 /**
5079 * Requests that the system open the captive portal app with the specified extras.
5080 *
5081 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5082 * corresponding permission.
5083 * @param network Network on which the captive portal was detected.
5084 * @param appExtras Extras to include in the app start intent.
5085 * @hide
5086 */
5087 @SystemApi
5088 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5089 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5090 try {
5091 mService.startCaptivePortalAppInternal(network, appExtras);
5092 } catch (RemoteException e) {
5093 throw e.rethrowFromSystemServer();
5094 }
5095 }
5096
5097 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005098 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005099 * @hide
5100 */
5101 @SystemApi
5102 @RequiresPermission(anyOf = {
5103 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5104 android.Manifest.permission.NETWORK_STACK})
5105 public boolean shouldAvoidBadWifi() {
5106 try {
5107 return mService.shouldAvoidBadWifi();
5108 } catch (RemoteException e) {
5109 throw e.rethrowFromSystemServer();
5110 }
5111 }
5112
5113 /**
5114 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5115 * time-sensitive user-facing operations when the system default network is temporarily
5116 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5117 * this method), and the operation should be infrequent to ensure that data usage is limited.
5118 *
5119 * An example of such an operation might be a time-sensitive foreground activity, such as a
5120 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5121 */
5122 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5123
5124 /**
5125 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5126 * a backup channel for traffic that is primarily going over another network.
5127 *
5128 * An example might be maintaining backup connections to peers or servers for the purpose of
5129 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5130 * on backup paths should be negligible compared to the traffic on the main path.
5131 */
5132 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5133
5134 /**
5135 * It is acceptable to use metered data to improve network latency and performance.
5136 */
5137 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5138
5139 /**
5140 * Return value to use for unmetered networks. On such networks we currently set all the flags
5141 * to true.
5142 * @hide
5143 */
5144 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5145 MULTIPATH_PREFERENCE_HANDOVER |
5146 MULTIPATH_PREFERENCE_RELIABILITY |
5147 MULTIPATH_PREFERENCE_PERFORMANCE;
5148
Aaron Huangcff22942021-05-27 16:31:26 +08005149 /** @hide */
5150 @Retention(RetentionPolicy.SOURCE)
5151 @IntDef(flag = true, value = {
5152 MULTIPATH_PREFERENCE_HANDOVER,
5153 MULTIPATH_PREFERENCE_RELIABILITY,
5154 MULTIPATH_PREFERENCE_PERFORMANCE,
5155 })
5156 public @interface MultipathPreference {
5157 }
5158
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005159 /**
5160 * Provides a hint to the calling application on whether it is desirable to use the
5161 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5162 * for multipath data transfer on this network when it is not the system default network.
5163 * Applications desiring to use multipath network protocols should call this method before
5164 * each such operation.
5165 *
5166 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005167 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005168 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005169 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005170 */
5171 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5172 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5173 try {
5174 return mService.getMultipathPreference(network);
5175 } catch (RemoteException e) {
5176 throw e.rethrowFromSystemServer();
5177 }
5178 }
5179
5180 /**
5181 * Resets all connectivity manager settings back to factory defaults.
5182 * @hide
5183 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005184 @SystemApi(client = MODULE_LIBRARIES)
5185 @RequiresPermission(anyOf = {
5186 android.Manifest.permission.NETWORK_SETTINGS,
5187 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005188 public void factoryReset() {
5189 try {
5190 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005191 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005192 } catch (RemoteException e) {
5193 throw e.rethrowFromSystemServer();
5194 }
5195 }
5196
5197 /**
5198 * Binds the current process to {@code network}. All Sockets created in the future
5199 * (and not explicitly bound via a bound SocketFactory from
5200 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5201 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5202 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5203 * work and all host name resolutions will fail. This is by design so an application doesn't
5204 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5205 * To clear binding pass {@code null} for {@code network}. Using individually bound
5206 * Sockets created by Network.getSocketFactory().createSocket() and
5207 * performing network-specific host name resolutions via
5208 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5209 * {@code bindProcessToNetwork}.
5210 *
5211 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5212 * the current binding.
5213 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5214 */
5215 public boolean bindProcessToNetwork(@Nullable Network network) {
5216 // Forcing callers to call through non-static function ensures ConnectivityManager
5217 // instantiated.
5218 return setProcessDefaultNetwork(network);
5219 }
5220
5221 /**
5222 * Binds the current process to {@code network}. All Sockets created in the future
5223 * (and not explicitly bound via a bound SocketFactory from
5224 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5225 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5226 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5227 * work and all host name resolutions will fail. This is by design so an application doesn't
5228 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5229 * To clear binding pass {@code null} for {@code network}. Using individually bound
5230 * Sockets created by Network.getSocketFactory().createSocket() and
5231 * performing network-specific host name resolutions via
5232 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5233 * {@code setProcessDefaultNetwork}.
5234 *
5235 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5236 * the current binding.
5237 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5238 * @deprecated This function can throw {@link IllegalStateException}. Use
5239 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5240 * is a direct replacement.
5241 */
5242 @Deprecated
5243 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5244 int netId = (network == null) ? NETID_UNSET : network.netId;
5245 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5246
5247 if (netId != NETID_UNSET) {
5248 netId = network.getNetIdForResolv();
5249 }
5250
5251 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5252 return false;
5253 }
5254
5255 if (!isSameNetId) {
5256 // Set HTTP proxy system properties to match network.
5257 // TODO: Deprecate this static method and replace it with a non-static version.
5258 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005259 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005260 } catch (SecurityException e) {
5261 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5262 Log.e(TAG, "Can't set proxy properties", e);
5263 }
5264 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005265 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005266 // Must flush socket pool as idle sockets will be bound to previous network and may
5267 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005268 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005269 }
5270
5271 return true;
5272 }
5273
5274 /**
5275 * Returns the {@link Network} currently bound to this process via
5276 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5277 *
5278 * @return {@code Network} to which this process is bound, or {@code null}.
5279 */
5280 @Nullable
5281 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005282 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005283 // instantiated.
5284 return getProcessDefaultNetwork();
5285 }
5286
5287 /**
5288 * Returns the {@link Network} currently bound to this process via
5289 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5290 *
5291 * @return {@code Network} to which this process is bound, or {@code null}.
5292 * @deprecated Using this function can lead to other functions throwing
5293 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5294 * {@code getBoundNetworkForProcess} is a direct replacement.
5295 */
5296 @Deprecated
5297 @Nullable
5298 public static Network getProcessDefaultNetwork() {
5299 int netId = NetworkUtils.getBoundNetworkForProcess();
5300 if (netId == NETID_UNSET) return null;
5301 return new Network(netId);
5302 }
5303
5304 private void unsupportedStartingFrom(int version) {
5305 if (Process.myUid() == Process.SYSTEM_UID) {
5306 // The getApplicationInfo() call we make below is not supported in system context. Let
5307 // the call through here, and rely on the fact that ConnectivityService will refuse to
5308 // allow the system to use these APIs anyway.
5309 return;
5310 }
5311
5312 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5313 throw new UnsupportedOperationException(
5314 "This method is not supported in target SDK version " + version + " and above");
5315 }
5316 }
5317
5318 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5319 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5320 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5321 // remove these exemptions. Note that this check is not secure, and apps can still access these
5322 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5323 // so is unsupported and may break in the future. http://b/22728205
5324 private void checkLegacyRoutingApiAccess() {
5325 unsupportedStartingFrom(VERSION_CODES.M);
5326 }
5327
5328 /**
5329 * Binds host resolutions performed by this process to {@code network}.
5330 * {@link #bindProcessToNetwork} takes precedence over this setting.
5331 *
5332 * @param network The {@link Network} to bind host resolutions from the current process to, or
5333 * {@code null} to clear the current binding.
5334 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5335 * @hide
5336 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5337 */
5338 @Deprecated
5339 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5340 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5341 return NetworkUtils.bindProcessToNetworkForHostResolution(
5342 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5343 }
5344
5345 /**
5346 * Device is not restricting metered network activity while application is running on
5347 * background.
5348 */
5349 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5350
5351 /**
5352 * Device is restricting metered network activity while application is running on background,
5353 * but application is allowed to bypass it.
5354 * <p>
5355 * In this state, application should take action to mitigate metered network access.
5356 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5357 */
5358 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5359
5360 /**
5361 * Device is restricting metered network activity while application is running on background.
5362 * <p>
5363 * In this state, application should not try to use the network while running on background,
5364 * because it would be denied.
5365 */
5366 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5367
5368 /**
5369 * A change in the background metered network activity restriction has occurred.
5370 * <p>
5371 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5372 * applies to them.
5373 * <p>
5374 * This is only sent to registered receivers, not manifest receivers.
5375 */
5376 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5377 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5378 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5379
Aaron Huangcff22942021-05-27 16:31:26 +08005380 /** @hide */
5381 @Retention(RetentionPolicy.SOURCE)
5382 @IntDef(flag = false, value = {
5383 RESTRICT_BACKGROUND_STATUS_DISABLED,
5384 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5385 RESTRICT_BACKGROUND_STATUS_ENABLED,
5386 })
5387 public @interface RestrictBackgroundStatus {
5388 }
5389
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005390 /**
5391 * Determines if the calling application is subject to metered network restrictions while
5392 * running on background.
5393 *
5394 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5395 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5396 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5397 */
5398 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5399 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005400 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005401 } catch (RemoteException e) {
5402 throw e.rethrowFromSystemServer();
5403 }
5404 }
5405
5406 /**
5407 * The network watchlist is a list of domains and IP addresses that are associated with
5408 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5409 * currently used by the system for validation purposes.
5410 *
5411 * @return Hash of network watchlist config file. Null if config does not exist.
5412 */
5413 @Nullable
5414 public byte[] getNetworkWatchlistConfigHash() {
5415 try {
5416 return mService.getNetworkWatchlistConfigHash();
5417 } catch (RemoteException e) {
5418 Log.e(TAG, "Unable to get watchlist config hash");
5419 throw e.rethrowFromSystemServer();
5420 }
5421 }
5422
5423 /**
5424 * Returns the {@code uid} of the owner of a network connection.
5425 *
5426 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5427 * IPPROTO_UDP} currently supported.
5428 * @param local The local {@link InetSocketAddress} of a connection.
5429 * @param remote The remote {@link InetSocketAddress} of a connection.
5430 * @return {@code uid} if the connection is found and the app has permission to observe it
5431 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5432 * android.os.Process#INVALID_UID} if the connection is not found.
5433 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5434 * user.
5435 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5436 */
5437 public int getConnectionOwnerUid(
5438 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5439 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5440 try {
5441 return mService.getConnectionOwnerUid(connectionInfo);
5442 } catch (RemoteException e) {
5443 throw e.rethrowFromSystemServer();
5444 }
5445 }
5446
5447 private void printStackTrace() {
5448 if (DEBUG) {
5449 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5450 final StringBuffer sb = new StringBuffer();
5451 for (int i = 3; i < callStack.length; i++) {
5452 final String stackTrace = callStack[i].toString();
5453 if (stackTrace == null || stackTrace.contains("android.os")) {
5454 break;
5455 }
5456 sb.append(" [").append(stackTrace).append("]");
5457 }
5458 Log.d(TAG, "StackLog:" + sb.toString());
5459 }
5460 }
5461
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005462 /** @hide */
5463 public TestNetworkManager startOrGetTestNetworkManager() {
5464 final IBinder tnBinder;
5465 try {
5466 tnBinder = mService.startOrGetTestNetworkService();
5467 } catch (RemoteException e) {
5468 throw e.rethrowFromSystemServer();
5469 }
5470
5471 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5472 }
5473
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005474 /** @hide */
5475 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5476 return new ConnectivityDiagnosticsManager(mContext, mService);
5477 }
5478
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005479 /**
5480 * Simulates a Data Stall for the specified Network.
5481 *
5482 * <p>This method should only be used for tests.
5483 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005484 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5485 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005486 *
5487 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005488 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5489 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5490 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005491 * @param network The Network for which a Data Stall is being simluated.
5492 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5493 * @throws SecurityException if the caller is not the owner of the given network.
5494 * @hide
5495 */
5496 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5497 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5498 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005499 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005500 @NonNull Network network, @NonNull PersistableBundle extras) {
5501 try {
5502 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5503 } catch (RemoteException e) {
5504 e.rethrowFromSystemServer();
5505 }
5506 }
5507
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005508 @NonNull
5509 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5510
5511 /**
5512 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5513 * receive available QoS events related to the {@link Network} and local ip + port
5514 * specified within socketInfo.
5515 * <p/>
5516 * The same {@link QosCallback} must be unregistered before being registered a second time,
5517 * otherwise {@link QosCallbackRegistrationException} is thrown.
5518 * <p/>
5519 * This API does not, in itself, require any permission if called with a network that is not
5520 * restricted. However, the underlying implementation currently only supports the IMS network,
5521 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5522 * useful, because they'd never be called back on networks that they would have access to.
5523 *
5524 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5525 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5526 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5527 * @throws RuntimeException if the app already has too many callbacks registered.
5528 *
5529 * Exceptions after the time of registration is passed through
5530 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5531 *
5532 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005533 * @param executor The executor on which the callback will be invoked. The provided
5534 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005535 * callbacks cannot be guaranteed.onQosCallbackRegistered
5536 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005537 *
5538 * @hide
5539 */
5540 @SystemApi
5541 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005542 @CallbackExecutor @NonNull final Executor executor,
5543 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005544 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005545 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005546 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005547
5548 try {
5549 synchronized (mQosCallbackConnections) {
5550 if (getQosCallbackConnection(callback) == null) {
5551 final QosCallbackConnection connection =
5552 new QosCallbackConnection(this, callback, executor);
5553 mQosCallbackConnections.add(connection);
5554 mService.registerQosSocketCallback(socketInfo, connection);
5555 } else {
5556 Log.e(TAG, "registerQosCallback: Callback already registered");
5557 throw new QosCallbackRegistrationException();
5558 }
5559 }
5560 } catch (final RemoteException e) {
5561 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5562
5563 // The same unregister method method is called for consistency even though nothing
5564 // will be sent to the ConnectivityService since the callback was never successfully
5565 // registered.
5566 unregisterQosCallback(callback);
5567 e.rethrowFromSystemServer();
5568 } catch (final ServiceSpecificException e) {
5569 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5570 unregisterQosCallback(callback);
5571 throw convertServiceException(e);
5572 }
5573 }
5574
5575 /**
5576 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5577 * events once unregistered and can be registered a second time.
5578 * <p/>
5579 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5580 *
5581 * @param callback the callback being unregistered
5582 *
5583 * @hide
5584 */
5585 @SystemApi
5586 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5587 Objects.requireNonNull(callback, "The callback must be non-null");
5588 try {
5589 synchronized (mQosCallbackConnections) {
5590 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5591 if (connection != null) {
5592 connection.stopReceivingMessages();
5593 mService.unregisterQosCallback(connection);
5594 mQosCallbackConnections.remove(connection);
5595 } else {
5596 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5597 }
5598 }
5599 } catch (final RemoteException e) {
5600 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5601 e.rethrowFromSystemServer();
5602 }
5603 }
5604
5605 /**
5606 * Gets the connection related to the callback.
5607 *
5608 * @param callback the callback to look up
5609 * @return the related connection
5610 */
5611 @Nullable
5612 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5613 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5614 // Checking by reference here is intentional
5615 if (connection.getCallback() == callback) {
5616 return connection;
5617 }
5618 }
5619 return null;
5620 }
5621
5622 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005623 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005624 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5625 * be used to request that the system provide a network without causing the network to be
5626 * in the foreground.
5627 *
5628 * <p>This method will attempt to find the best network that matches the passed
5629 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5630 * criteria. The platform will evaluate which network is the best at its own discretion.
5631 * Throughput, latency, cost per byte, policy, user preference and other considerations
5632 * may be factored in the decision of what is considered the best network.
5633 *
5634 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5635 * matching this request, while always attempting to match the request to a better network if
5636 * possible. If a better match is found, the platform will switch this request to the now-best
5637 * network and inform the app of the newly best network by invoking
5638 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5639 * will not try to maintain any other network than the best one currently matching the request:
5640 * a network not matching any network request may be disconnected at any time.
5641 *
5642 * <p>For example, an application could use this method to obtain a connected cellular network
5643 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5644 * radio to consume additional power. Or, an application could inform the system that it wants
5645 * a network supporting sending MMSes and have the system let it know about the currently best
5646 * MMS-supporting network through the provided {@link NetworkCallback}.
5647 *
5648 * <p>The status of the request can be followed by listening to the various callbacks described
5649 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5650 * used to direct traffic to the network (although accessing some networks may be subject to
5651 * holding specific permissions). Callers will learn about the specific characteristics of the
5652 * network through
5653 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5654 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5655 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5656 * matching the request at any given time; therefore when a better network matching the request
5657 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5658 * with the new network after which no further updates are given about the previously-best
5659 * network, unless it becomes the best again at some later time. All callbacks are invoked
5660 * in order on the same thread, which by default is a thread created by the framework running
5661 * in the app.
5662 *
5663 * <p>This{@link NetworkRequest} will live until released via
5664 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5665 * which point the system may let go of the network at any time.
5666 *
5667 * <p>It is presently unsupported to request a network with mutable
5668 * {@link NetworkCapabilities} such as
5669 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5670 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5671 * as these {@code NetworkCapabilities} represent states that a particular
5672 * network may never attain, and whether a network will attain these states
5673 * is unknown prior to bringing up the network so the framework does not
5674 * know how to go about satisfying a request with these capabilities.
5675 *
5676 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5677 * number of outstanding requests to 100 per app (identified by their UID), shared with
5678 * all variants of this method, of {@link #registerNetworkCallback} as well as
5679 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5680 * Requesting a network with this method will count toward this limit. If this limit is
5681 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5682 * make sure to unregister the callbacks with
5683 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5684 *
5685 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005686 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5687 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005688 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5689 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005690 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5691 * @throws SecurityException if missing the appropriate permissions.
5692 * @throws RuntimeException if the app already has too many callbacks registered.
5693 *
5694 * @hide
5695 */
5696 @SystemApi(client = MODULE_LIBRARIES)
5697 @SuppressLint("ExecutorRegistration")
5698 @RequiresPermission(anyOf = {
5699 android.Manifest.permission.NETWORK_SETTINGS,
5700 android.Manifest.permission.NETWORK_STACK,
5701 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5702 })
5703 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005704 @NonNull NetworkCallback networkCallback,
5705 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005706 final NetworkCapabilities nc = request.networkCapabilities;
5707 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005708 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005709 }
James Mattis12aeab82021-01-10 14:24:24 -08005710
5711 /**
James Mattis12aeab82021-01-10 14:24:24 -08005712 * Used by automotive devices to set the network preferences used to direct traffic at an
5713 * application level as per the given OemNetworkPreferences. An example use-case would be an
5714 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5715 * vehicle via a particular network.
5716 *
5717 * Calling this will overwrite the existing preference.
5718 *
5719 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5720 * @param executor the executor on which listener will be invoked.
5721 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5722 * communicate completion of setOemNetworkPreference(). This will only be
5723 * called once upon successful completion of setOemNetworkPreference().
5724 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5725 * @throws SecurityException if missing the appropriate permissions.
5726 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005727 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005728 */
James Mattis6e2d7022021-01-26 16:23:52 -08005729 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005730 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005731 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005732 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005733 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005734 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5735 if (null != listener) {
5736 Objects.requireNonNull(executor, "Executor must be non-null");
5737 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005738 final IOnCompleteListener listenerInternal = listener == null ? null :
5739 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005740 @Override
5741 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005742 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005743 }
5744 };
5745
5746 try {
5747 mService.setOemNetworkPreference(preference, listenerInternal);
5748 } catch (RemoteException e) {
5749 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5750 throw e.rethrowFromSystemServer();
5751 }
5752 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005753
Chalard Jeanad565e22021-02-25 17:23:40 +09005754 /**
5755 * Request that a user profile is put by default on a network matching a given preference.
5756 *
5757 * See the documentation for the individual preferences for a description of the supported
5758 * behaviors.
5759 *
5760 * @param profile the profile concerned.
5761 * @param preference the preference for this 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.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005766 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5767 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005768 * @hide
5769 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005770 // This function is for establishing per-profile default networking and can only be called by
5771 // the device policy manager, running as the system server. It would make no sense to call it
5772 // on a context for a user because it does not establish a setting on behalf of a user, rather
5773 // it establishes a setting for a user on behalf of the DPM.
5774 @SuppressLint({"UserHandle"})
5775 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005776 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005777 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005778 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005779 @ProfileNetworkPreferencePolicy final int preference,
5780 @Nullable @CallbackExecutor final Executor executor,
5781 @Nullable final Runnable listener) {
5782
5783 ProfileNetworkPreference.Builder preferenceBuilder =
5784 new ProfileNetworkPreference.Builder();
5785 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005786 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5787 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5788 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005789 setProfileNetworkPreferences(profile,
5790 List.of(preferenceBuilder.build()), executor, listener);
5791 }
5792
5793 /**
5794 * Set a list of default network selection policies for a user profile.
5795 *
5796 * Calling this API with a user handle defines the entire policy for that user handle.
5797 * It will overwrite any setting previously set for the same user profile,
5798 * and not affect previously set settings for other handles.
5799 *
5800 * Call this API with an empty list to remove settings for this user profile.
5801 *
5802 * See {@link ProfileNetworkPreference} for more details on each preference
5803 * parameter.
5804 *
5805 * @param profile the user profile for which the preference is being set.
5806 * @param profileNetworkPreferences the list of profile network preferences for the
5807 * provided profile.
5808 * @param executor an executor to execute the listener on. Optional if listener is null.
5809 * @param listener an optional listener to listen for completion of the operation.
5810 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5811 * @throws SecurityException if missing the appropriate permissions.
5812 * @hide
5813 */
5814 @SystemApi(client = MODULE_LIBRARIES)
5815 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5816 public void setProfileNetworkPreferences(
5817 @NonNull final UserHandle profile,
5818 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005819 @Nullable @CallbackExecutor final Executor executor,
5820 @Nullable final Runnable listener) {
5821 if (null != listener) {
5822 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5823 }
5824 final IOnCompleteListener proxy;
5825 if (null == listener) {
5826 proxy = null;
5827 } else {
5828 proxy = new IOnCompleteListener.Stub() {
5829 @Override
5830 public void onComplete() {
5831 executor.execute(listener::run);
5832 }
5833 };
5834 }
5835 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005836 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005837 } catch (RemoteException e) {
5838 throw e.rethrowFromSystemServer();
5839 }
5840 }
5841
lucaslin5cdbcfb2021-03-12 00:46:33 +08005842 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005843 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005844 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005845 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005846
5847 /**
5848 * Get the network ID range reserved for IPSec tunnel interfaces.
5849 *
5850 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5851 * @hide
5852 */
5853 @SystemApi(client = MODULE_LIBRARIES)
5854 @NonNull
5855 public static Range<Integer> getIpSecNetIdRange() {
5856 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5857 }
markchien738ad912021-12-09 18:15:45 +08005858
5859 /**
markchiene46042b2022-03-02 18:07:35 +08005860 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5861 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005862 *
5863 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005864 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005865 * @hide
5866 */
5867 @SystemApi(client = MODULE_LIBRARIES)
5868 @RequiresPermission(anyOf = {
5869 android.Manifest.permission.NETWORK_SETTINGS,
5870 android.Manifest.permission.NETWORK_STACK,
5871 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5872 })
markchiene46042b2022-03-02 18:07:35 +08005873 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005874 try {
markchiene46042b2022-03-02 18:07:35 +08005875 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08005876 } catch (RemoteException e) {
5877 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005878 }
5879 }
5880
5881 /**
markchiene46042b2022-03-02 18:07:35 +08005882 * Removes the specified UID from the list of UIDs that are allowed to use background data on
5883 * metered networks when background data is restricted. The deny list takes precedence over
5884 * the allow list.
5885 *
5886 * @param uid uid of target app
5887 * @throws IllegalStateException if updating allow list failed.
5888 * @hide
5889 */
5890 @SystemApi(client = MODULE_LIBRARIES)
5891 @RequiresPermission(anyOf = {
5892 android.Manifest.permission.NETWORK_SETTINGS,
5893 android.Manifest.permission.NETWORK_STACK,
5894 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5895 })
5896 public void removeUidFromMeteredNetworkAllowList(final int uid) {
5897 try {
5898 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
5899 } catch (RemoteException e) {
5900 throw e.rethrowFromSystemServer();
5901 }
5902 }
5903
5904 /**
5905 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
5906 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08005907 *
5908 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005909 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08005910 * @hide
5911 */
5912 @SystemApi(client = MODULE_LIBRARIES)
5913 @RequiresPermission(anyOf = {
5914 android.Manifest.permission.NETWORK_SETTINGS,
5915 android.Manifest.permission.NETWORK_STACK,
5916 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5917 })
markchiene46042b2022-03-02 18:07:35 +08005918 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005919 try {
markchiene46042b2022-03-02 18:07:35 +08005920 mService.updateMeteredNetworkDenyList(uid, true /* add */);
5921 } catch (RemoteException e) {
5922 throw e.rethrowFromSystemServer();
5923 }
5924 }
5925
5926 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005927 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08005928 * networks if background data is not restricted. The deny list takes precedence over the
5929 * allow list.
5930 *
5931 * @param uid uid of target app
5932 * @throws IllegalStateException if updating deny list failed.
5933 * @hide
5934 */
5935 @SystemApi(client = MODULE_LIBRARIES)
5936 @RequiresPermission(anyOf = {
5937 android.Manifest.permission.NETWORK_SETTINGS,
5938 android.Manifest.permission.NETWORK_STACK,
5939 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5940 })
5941 public void removeUidFromMeteredNetworkDenyList(final int uid) {
5942 try {
5943 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08005944 } catch (RemoteException e) {
5945 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08005946 }
5947 }
5948
5949 /**
5950 * Sets a firewall rule for the specified UID on the specified chain.
5951 *
5952 * @param chain target chain.
5953 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08005954 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08005955 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08005956 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08005957 * @hide
5958 */
5959 @SystemApi(client = MODULE_LIBRARIES)
5960 @RequiresPermission(anyOf = {
5961 android.Manifest.permission.NETWORK_SETTINGS,
5962 android.Manifest.permission.NETWORK_STACK,
5963 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5964 })
markchien3c04e662022-03-22 16:29:56 +08005965 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
5966 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08005967 try {
markchien3c04e662022-03-22 16:29:56 +08005968 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08005969 } catch (RemoteException e) {
5970 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005971 }
5972 }
markchien98a6f952022-01-13 23:43:53 +08005973
5974 /**
5975 * Enables or disables the specified firewall chain.
5976 *
5977 * @param chain target chain.
5978 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00005979 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08005980 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08005981 * @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 setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
5990 try {
5991 mService.setFirewallChainEnabled(chain, enable);
5992 } catch (RemoteException e) {
5993 throw e.rethrowFromSystemServer();
5994 }
5995 }
markchien00a0bed2022-01-13 23:46:13 +08005996
5997 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00005998 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00005999 *
6000 * @param chain target chain.
6001 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6002 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006003 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6004 * cause of the failure.
6005 * @hide
6006 */
6007 @RequiresPermission(anyOf = {
6008 android.Manifest.permission.NETWORK_SETTINGS,
6009 android.Manifest.permission.NETWORK_STACK,
6010 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6011 })
6012 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6013 try {
6014 return mService.getFirewallChainEnabled(chain);
6015 } catch (RemoteException e) {
6016 throw e.rethrowFromSystemServer();
6017 }
6018 }
6019
6020 /**
markchien00a0bed2022-01-13 23:46:13 +08006021 * Replaces the contents of the specified UID-based firewall chain.
6022 *
6023 * @param chain target chain to replace.
6024 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006025 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006026 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6027 * @hide
6028 */
6029 @SystemApi(client = MODULE_LIBRARIES)
6030 @RequiresPermission(anyOf = {
6031 android.Manifest.permission.NETWORK_SETTINGS,
6032 android.Manifest.permission.NETWORK_STACK,
6033 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6034 })
6035 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6036 Objects.requireNonNull(uids);
6037 try {
6038 mService.replaceFirewallChain(chain, uids);
6039 } catch (RemoteException e) {
6040 throw e.rethrowFromSystemServer();
6041 }
6042 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006043
6044 /** @hide */
6045 public IBinder getCompanionDeviceManagerProxyService() {
6046 try {
6047 return mService.getCompanionDeviceManagerProxyService();
6048 } catch (RemoteException e) {
6049 throw e.rethrowFromSystemServer();
6050 }
6051 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006052}