blob: 915ec52e7774d665f95a7d0afb9723915b283f43 [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;
Junyu Laidf210362023-10-24 02:47:50 +000029import android.annotation.FlaggedApi;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090030import android.annotation.IntDef;
31import android.annotation.NonNull;
32import android.annotation.Nullable;
Chalard Jean2fb66f12023-08-25 12:50:37 +090033import android.annotation.RequiresApi;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090034import android.annotation.RequiresPermission;
35import android.annotation.SdkConstant;
36import android.annotation.SdkConstant.SdkConstantType;
37import android.annotation.SuppressLint;
38import android.annotation.SystemApi;
39import android.annotation.SystemService;
40import android.app.PendingIntent;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090041import android.app.admin.DevicePolicyManager;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090042import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090043import android.content.ComponentName;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090044import android.content.Context;
45import android.content.Intent;
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +090046import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090047import android.net.IpSecManager.UdpEncapsulationSocket;
48import android.net.SocketKeepalive.Callback;
49import android.net.TetheringManager.StartTetheringCallback;
50import android.net.TetheringManager.TetheringEventCallback;
51import android.net.TetheringManager.TetheringRequest;
52import android.os.Binder;
53import android.os.Build;
54import android.os.Build.VERSION_CODES;
55import android.os.Bundle;
56import android.os.Handler;
57import android.os.IBinder;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090058import android.os.Looper;
59import android.os.Message;
60import android.os.Messenger;
61import android.os.ParcelFileDescriptor;
62import android.os.PersistableBundle;
63import android.os.Process;
64import android.os.RemoteException;
65import android.os.ResultReceiver;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090066import android.os.ServiceSpecificException;
Chalard Jeanad565e22021-02-25 17:23:40 +090067import android.os.UserHandle;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090068import android.provider.Settings;
69import android.telephony.SubscriptionManager;
70import android.telephony.TelephonyManager;
71import android.util.ArrayMap;
72import android.util.Log;
73import android.util.Range;
74import android.util.SparseIntArray;
75
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090076import com.android.internal.annotations.GuardedBy;
Junyu Lai934d4832024-02-22 11:21:47 +080077import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090078
79import libcore.net.event.NetworkEventDispatcher;
80
81import java.io.IOException;
82import java.io.UncheckedIOException;
83import java.lang.annotation.Retention;
84import java.lang.annotation.RetentionPolicy;
85import java.net.DatagramSocket;
86import java.net.InetAddress;
87import java.net.InetSocketAddress;
88import java.net.Socket;
89import java.util.ArrayList;
90import java.util.Collection;
91import java.util.HashMap;
92import java.util.List;
93import java.util.Map;
94import java.util.Objects;
95import java.util.concurrent.Executor;
96import java.util.concurrent.ExecutorService;
97import java.util.concurrent.Executors;
98import java.util.concurrent.RejectedExecutionException;
99
100/**
101 * Class that answers queries about the state of network connectivity. It also
102 * notifies applications when network connectivity changes.
103 * <p>
104 * The primary responsibilities of this class are to:
105 * <ol>
106 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
107 * <li>Send broadcast intents when network connectivity changes</li>
108 * <li>Attempt to "fail over" to another network when connectivity to a network
109 * is lost</li>
110 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
111 * state of the available networks</li>
112 * <li>Provide an API that allows applications to request and select networks for their data
113 * traffic</li>
114 * </ol>
115 */
116@SystemService(Context.CONNECTIVITY_SERVICE)
117public class ConnectivityManager {
118 private static final String TAG = "ConnectivityManager";
119 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
120
Junyu Laidf210362023-10-24 02:47:50 +0000121 // TODO : remove this class when udc-mainline-prod is abandoned and android.net.flags.Flags is
122 // available here
123 /** @hide */
124 public static class Flags {
125 static final String SET_DATA_SAVER_VIA_CM =
126 "com.android.net.flags.set_data_saver_via_cm";
Junyu Laibb594802023-09-04 11:37:03 +0800127 static final String SUPPORT_IS_UID_NETWORKING_BLOCKED =
128 "com.android.net.flags.support_is_uid_networking_blocked";
Suprabh Shukla2d893b62023-11-06 08:47:40 -0800129 static final String BASIC_BACKGROUND_RESTRICTIONS_ENABLED =
130 "com.android.net.flags.basic_background_restrictions_enabled";
Junyu Laidf210362023-10-24 02:47:50 +0000131 }
132
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900133 /**
134 * A change in network connectivity has occurred. A default connection has either
135 * been established or lost. The NetworkInfo for the affected network is
136 * sent as an extra; it should be consulted to see what kind of
137 * connectivity event occurred.
138 * <p/>
139 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
140 * broadcast if they declare the broadcast receiver in their manifest. Apps
141 * will still receive broadcasts if they register their
142 * {@link android.content.BroadcastReceiver} with
143 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
144 * and that context is still valid.
145 * <p/>
146 * If this is a connection that was the result of failing over from a
147 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
148 * set to true.
149 * <p/>
150 * For a loss of connectivity, if the connectivity manager is attempting
151 * to connect (or has already connected) to another network, the
152 * NetworkInfo for the new network is also passed as an extra. This lets
153 * any receivers of the broadcast know that they should not necessarily
154 * tell the user that no data traffic will be possible. Instead, the
155 * receiver should expect another broadcast soon, indicating either that
156 * the failover attempt succeeded (and so there is still overall data
157 * connectivity), or that the failover attempt failed, meaning that all
158 * connectivity has been lost.
159 * <p/>
160 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
161 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900162 * <p />
163 * Note that this broadcast is deprecated and generally tries to implement backwards
164 * compatibility with older versions of Android. As such, it may not reflect new
165 * capabilities of the system, like multiple networks being connected at the same
166 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900167 *
168 * @deprecated apps should use the more versatile {@link #requestNetwork},
169 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
170 * functions instead for faster and more detailed updates about the network
171 * changes they care about.
172 */
173 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
174 @Deprecated
175 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
176
177 /**
178 * The device has connected to a network that has presented a captive
179 * portal, which is blocking Internet connectivity. The user was presented
180 * with a notification that network sign in is required,
181 * and the user invoked the notification's action indicating they
182 * desire to sign in to the network. Apps handling this activity should
183 * facilitate signing in to the network. This action includes a
184 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
185 * the network presenting the captive portal; all communication with the
186 * captive portal must be done using this {@code Network} object.
187 * <p/>
188 * This activity includes a {@link CaptivePortal} extra named
189 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
190 * outcomes of the captive portal sign in to the system:
191 * <ul>
192 * <li> When the app handling this action believes the user has signed in to
193 * the network and the captive portal has been dismissed, the app should
194 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
195 * reevaluate the network. If reevaluation finds the network no longer
196 * subject to a captive portal, the network may become the default active
197 * data network.</li>
198 * <li> When the app handling this action believes the user explicitly wants
199 * to ignore the captive portal and the network, the app should call
200 * {@link CaptivePortal#ignoreNetwork}. </li>
201 * </ul>
202 */
203 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
204 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
205
206 /**
207 * The lookup key for a {@link NetworkInfo} object. Retrieve with
208 * {@link android.content.Intent#getParcelableExtra(String)}.
209 *
210 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
211 * can't accurately represent modern network characteristics.
212 * Please obtain information about networks from the {@link NetworkCapabilities}
213 * or {@link LinkProperties} objects instead.
214 */
215 @Deprecated
216 public static final String EXTRA_NETWORK_INFO = "networkInfo";
217
218 /**
219 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
220 *
221 * @see android.content.Intent#getIntExtra(String, int)
222 * @deprecated The network type is not rich enough to represent the characteristics
223 * of modern networks. Please use {@link NetworkCapabilities} instead,
224 * in particular the transports.
225 */
226 @Deprecated
227 public static final String EXTRA_NETWORK_TYPE = "networkType";
228
229 /**
230 * The lookup key for a boolean that indicates whether a connect event
231 * is for a network to which the connectivity manager was failing over
232 * following a disconnect on another network.
233 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
234 *
235 * @deprecated See {@link NetworkInfo}.
236 */
237 @Deprecated
238 public static final String EXTRA_IS_FAILOVER = "isFailover";
239 /**
240 * The lookup key for a {@link NetworkInfo} object. This is supplied when
241 * there is another network that it may be possible to connect to. Retrieve with
242 * {@link android.content.Intent#getParcelableExtra(String)}.
243 *
244 * @deprecated See {@link NetworkInfo}.
245 */
246 @Deprecated
247 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
248 /**
249 * The lookup key for a boolean that indicates whether there is a
250 * complete lack of connectivity, i.e., no network is available.
251 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
252 */
253 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
254 /**
255 * The lookup key for a string that indicates why an attempt to connect
256 * to a network failed. The string has no particular structure. It is
257 * intended to be used in notifications presented to users. Retrieve
258 * it with {@link android.content.Intent#getStringExtra(String)}.
259 */
260 public static final String EXTRA_REASON = "reason";
261 /**
262 * The lookup key for a string that provides optionally supplied
263 * extra information about the network state. The information
264 * may be passed up from the lower networking layers, and its
265 * meaning may be specific to a particular network type. Retrieve
266 * it with {@link android.content.Intent#getStringExtra(String)}.
267 *
268 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
269 */
270 @Deprecated
271 public static final String EXTRA_EXTRA_INFO = "extraInfo";
272 /**
273 * The lookup key for an int that provides information about
274 * our connection to the internet at large. 0 indicates no connection,
275 * 100 indicates a great connection. Retrieve it with
276 * {@link android.content.Intent#getIntExtra(String, int)}.
277 * {@hide}
278 */
279 public static final String EXTRA_INET_CONDITION = "inetCondition";
280 /**
281 * The lookup key for a {@link CaptivePortal} object included with the
282 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
283 * object can be used to either indicate to the system that the captive
284 * portal has been dismissed or that the user does not want to pursue
285 * signing in to captive portal. Retrieve it with
286 * {@link android.content.Intent#getParcelableExtra(String)}.
287 */
288 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
289
290 /**
291 * Key for passing a URL to the captive portal login activity.
292 */
293 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
294
295 /**
296 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
297 * portal login activity.
298 * {@hide}
299 */
300 @SystemApi
301 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
302 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
303
304 /**
305 * Key for passing a user agent string to the captive portal login activity.
306 * {@hide}
307 */
308 @SystemApi
309 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
310 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
311
312 /**
313 * Broadcast action to indicate the change of data activity status
314 * (idle or active) on a network in a recent period.
315 * The network becomes active when data transmission is started, or
316 * idle if there is no data transmission for a period of time.
317 * {@hide}
318 */
319 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
320 public static final String ACTION_DATA_ACTIVITY_CHANGE =
321 "android.net.conn.DATA_ACTIVITY_CHANGE";
322 /**
323 * The lookup key for an enum that indicates the network device type on which this data activity
324 * change happens.
325 * {@hide}
326 */
327 public static final String EXTRA_DEVICE_TYPE = "deviceType";
328 /**
329 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
330 * it is actively sending or receiving data and {@code false} means it is idle.
331 * {@hide}
332 */
333 public static final String EXTRA_IS_ACTIVE = "isActive";
334 /**
335 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
336 * {@hide}
337 */
338 public static final String EXTRA_REALTIME_NS = "tsNanos";
339
340 /**
341 * Broadcast Action: The setting for background data usage has changed
342 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
343 * <p>
344 * If an application uses the network in the background, it should listen
345 * for this broadcast and stop using the background data if the value is
346 * {@code false}.
347 * <p>
348 *
349 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
350 * of background data depends on several combined factors, and
351 * this broadcast is no longer sent. Instead, when background
352 * data is unavailable, {@link #getActiveNetworkInfo()} will now
353 * appear disconnected. During first boot after a platform
354 * upgrade, this broadcast will be sent once if
355 * {@link #getBackgroundDataSetting()} was {@code false} before
356 * the upgrade.
357 */
358 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
359 @Deprecated
360 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
361 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
362
363 /**
364 * Broadcast Action: The network connection may not be good
365 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
366 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
367 * the network and it's condition.
368 * @hide
369 */
370 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
371 @UnsupportedAppUsage
372 public static final String INET_CONDITION_ACTION =
373 "android.net.conn.INET_CONDITION_ACTION";
374
375 /**
376 * Broadcast Action: A tetherable connection has come or gone.
377 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
378 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
379 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
380 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
381 * the current state of tethering. Each include a list of
382 * interface names in that state (may be empty).
383 * @hide
384 */
385 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
386 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
387 public static final String ACTION_TETHER_STATE_CHANGED =
388 TetheringManager.ACTION_TETHER_STATE_CHANGED;
389
390 /**
391 * @hide
392 * gives a String[] listing all the interfaces configured for
393 * tethering and currently available for tethering.
394 */
395 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
396 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
397
398 /**
399 * @hide
400 * gives a String[] listing all the interfaces currently in local-only
401 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
402 */
403 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
404
405 /**
406 * @hide
407 * gives a String[] listing all the interfaces currently tethered
408 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
409 */
410 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
411 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
412
413 /**
414 * @hide
415 * gives a String[] listing all the interfaces we tried to tether and
416 * failed. Use {@link #getLastTetherError} to find the error code
417 * for any interfaces listed here.
418 */
419 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
420 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
421
422 /**
423 * Broadcast Action: The captive portal tracker has finished its test.
424 * Sent only while running Setup Wizard, in lieu of showing a user
425 * notification.
426 * @hide
427 */
428 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
429 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
430 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
431 /**
432 * The lookup key for a boolean that indicates whether a captive portal was detected.
433 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
434 * @hide
435 */
436 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
437
438 /**
439 * Action used to display a dialog that asks the user whether to connect to a network that is
440 * not validated. This intent is used to start the dialog in settings via startActivity.
441 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800442 * This action includes a {@link Network} typed extra which is called
443 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
444 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900445 * @hide
446 */
lucaslincf6d4502021-03-04 17:09:51 +0800447 @SystemApi(client = MODULE_LIBRARIES)
448 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900449
450 /**
451 * Action used to display a dialog that asks the user whether to avoid a network that is no
452 * longer validated. This intent is used to start the dialog in settings via 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 is no longer
456 * validated.
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_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800462 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900463
464 /**
465 * Action used to display a dialog that asks the user whether to stay connected to a network
466 * that has not validated. This intent is used to start the dialog in settings via
467 * startActivity.
468 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800469 * This action includes a {@link Network} typed extra which is called
470 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
471 * connectivity.
472 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900473 * @hide
474 */
lucaslincf6d4502021-03-04 17:09:51 +0800475 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900476 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800477 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900478
479 /**
paulhub49c8422021-04-07 16:18:13 +0800480 * Clear DNS Cache Action: This is broadcast when networks have changed and old
481 * DNS entries should be cleared.
482 * @hide
483 */
484 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
485 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
486 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
487
488 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900489 * Invalid tethering type.
490 * @see #startTethering(int, boolean, OnStartTetheringCallback)
491 * @hide
492 */
493 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
494
495 /**
496 * Wifi tethering type.
497 * @see #startTethering(int, boolean, OnStartTetheringCallback)
498 * @hide
499 */
500 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900501 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900502
503 /**
504 * USB tethering type.
505 * @see #startTethering(int, boolean, OnStartTetheringCallback)
506 * @hide
507 */
508 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900509 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900510
511 /**
512 * Bluetooth tethering type.
513 * @see #startTethering(int, boolean, OnStartTetheringCallback)
514 * @hide
515 */
516 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900517 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900518
519 /**
520 * Wifi P2p tethering type.
521 * Wifi P2p tethering is set through events automatically, and don't
522 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
523 * @hide
524 */
525 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
526
527 /**
528 * Extra used for communicating with the TetherService. Includes the type of tethering to
529 * enable if any.
530 * @hide
531 */
532 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
533
534 /**
535 * Extra used for communicating with the TetherService. Includes the type of tethering for
536 * which to cancel provisioning.
537 * @hide
538 */
539 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
540
541 /**
542 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
543 * provisioning.
544 * @hide
545 */
546 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
547
548 /**
549 * Tells the TetherService to run a provision check now.
550 * @hide
551 */
552 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
553
554 /**
555 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
556 * which will receive provisioning results. Can be left empty.
557 * @hide
558 */
559 public static final String EXTRA_PROVISION_CALLBACK =
560 TetheringConstants.EXTRA_PROVISION_CALLBACK;
561
562 /**
563 * The absence of a connection type.
564 * @hide
565 */
566 @SystemApi
567 public static final int TYPE_NONE = -1;
568
569 /**
570 * A Mobile data connection. Devices may support more than one.
571 *
572 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
573 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000574 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900575 */
576 @Deprecated
577 public static final int TYPE_MOBILE = 0;
578
579 /**
580 * A WIFI data connection. Devices may support more than one.
581 *
582 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
583 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000584 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900585 */
586 @Deprecated
587 public static final int TYPE_WIFI = 1;
588
589 /**
590 * An MMS-specific Mobile data connection. This network type may use the
591 * same network interface as {@link #TYPE_MOBILE} or it may use a different
592 * one. This is used by applications needing to talk to the carrier's
593 * Multimedia Messaging Service servers.
594 *
595 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
596 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
597 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
598 */
599 @Deprecated
600 public static final int TYPE_MOBILE_MMS = 2;
601
602 /**
603 * A SUPL-specific Mobile data connection. This network type may use the
604 * same network interface as {@link #TYPE_MOBILE} or it may use a different
605 * one. This is used by applications needing to talk to the carrier's
606 * Secure User Plane Location servers for help locating the device.
607 *
608 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
609 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
610 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
611 */
612 @Deprecated
613 public static final int TYPE_MOBILE_SUPL = 3;
614
615 /**
616 * A DUN-specific Mobile data connection. This network type may use the
617 * same network interface as {@link #TYPE_MOBILE} or it may use a different
618 * one. This is sometimes by the system when setting up an upstream connection
619 * for tethering so that the carrier is aware of DUN traffic.
620 *
621 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
622 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
623 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
624 */
625 @Deprecated
626 public static final int TYPE_MOBILE_DUN = 4;
627
628 /**
629 * A High Priority Mobile data connection. This network type uses the
630 * same network interface as {@link #TYPE_MOBILE} but the routing setup
631 * is different.
632 *
633 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
634 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000635 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900636 */
637 @Deprecated
638 public static final int TYPE_MOBILE_HIPRI = 5;
639
640 /**
641 * A WiMAX data connection.
642 *
643 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
644 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000645 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900646 */
647 @Deprecated
648 public static final int TYPE_WIMAX = 6;
649
650 /**
651 * A Bluetooth data connection.
652 *
653 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
654 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000655 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900656 */
657 @Deprecated
658 public static final int TYPE_BLUETOOTH = 7;
659
660 /**
661 * Fake data connection. This should not be used on shipping devices.
662 * @deprecated This is not used any more.
663 */
664 @Deprecated
665 public static final int TYPE_DUMMY = 8;
666
667 /**
668 * An Ethernet data connection.
669 *
670 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
671 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000672 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900673 */
674 @Deprecated
675 public static final int TYPE_ETHERNET = 9;
676
677 /**
678 * Over the air Administration.
679 * @deprecated Use {@link NetworkCapabilities} instead.
680 * {@hide}
681 */
682 @Deprecated
683 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
684 public static final int TYPE_MOBILE_FOTA = 10;
685
686 /**
687 * IP Multimedia Subsystem.
688 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
689 * {@hide}
690 */
691 @Deprecated
692 @UnsupportedAppUsage
693 public static final int TYPE_MOBILE_IMS = 11;
694
695 /**
696 * Carrier Branded Services.
697 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
698 * {@hide}
699 */
700 @Deprecated
701 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
702 public static final int TYPE_MOBILE_CBS = 12;
703
704 /**
705 * A Wi-Fi p2p connection. Only requesting processes will have access to
706 * the peers connected.
707 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
708 * {@hide}
709 */
710 @Deprecated
711 @SystemApi
712 public static final int TYPE_WIFI_P2P = 13;
713
714 /**
715 * The network to use for initially attaching to the network
716 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
717 * {@hide}
718 */
719 @Deprecated
720 @UnsupportedAppUsage
721 public static final int TYPE_MOBILE_IA = 14;
722
723 /**
724 * Emergency PDN connection for emergency services. This
725 * may include IMS and MMS in emergency situations.
726 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
727 * {@hide}
728 */
729 @Deprecated
730 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
731 public static final int TYPE_MOBILE_EMERGENCY = 15;
732
733 /**
734 * The network that uses proxy to achieve connectivity.
735 * @deprecated Use {@link NetworkCapabilities} instead.
736 * {@hide}
737 */
738 @Deprecated
739 @SystemApi
740 public static final int TYPE_PROXY = 16;
741
742 /**
743 * A virtual network using one or more native bearers.
744 * It may or may not be providing security services.
745 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
746 */
747 @Deprecated
748 public static final int TYPE_VPN = 17;
749
750 /**
751 * A network that is exclusively meant to be used for testing
752 *
753 * @deprecated Use {@link NetworkCapabilities} instead.
754 * @hide
755 */
756 @Deprecated
757 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
758
759 /**
760 * @deprecated Use {@link NetworkCapabilities} instead.
761 * @hide
762 */
763 @Deprecated
764 @Retention(RetentionPolicy.SOURCE)
765 @IntDef(prefix = { "TYPE_" }, value = {
766 TYPE_NONE,
767 TYPE_MOBILE,
768 TYPE_WIFI,
769 TYPE_MOBILE_MMS,
770 TYPE_MOBILE_SUPL,
771 TYPE_MOBILE_DUN,
772 TYPE_MOBILE_HIPRI,
773 TYPE_WIMAX,
774 TYPE_BLUETOOTH,
775 TYPE_DUMMY,
776 TYPE_ETHERNET,
777 TYPE_MOBILE_FOTA,
778 TYPE_MOBILE_IMS,
779 TYPE_MOBILE_CBS,
780 TYPE_WIFI_P2P,
781 TYPE_MOBILE_IA,
782 TYPE_MOBILE_EMERGENCY,
783 TYPE_PROXY,
784 TYPE_VPN,
785 TYPE_TEST
786 })
787 public @interface LegacyNetworkType {}
788
789 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
790 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
791 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
792 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
793 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
794
795 /** {@hide} */
796 public static final int MAX_RADIO_TYPE = TYPE_TEST;
797
798 /** {@hide} */
799 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
800
801 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
802
803 /**
804 * If you want to set the default network preference,you can directly
805 * change the networkAttributes array in framework's config.xml.
806 *
807 * @deprecated Since we support so many more networks now, the single
808 * network default network preference can't really express
809 * the hierarchy. Instead, the default is defined by the
810 * networkAttributes in config.xml. You can determine
811 * the current value by calling {@link #getNetworkPreference()}
812 * from an App.
813 */
814 @Deprecated
815 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
816
817 /**
818 * @hide
819 */
820 public static final int REQUEST_ID_UNSET = 0;
821
822 /**
823 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
824 * This allows to distinguish when unregistering NetworkCallbacks those that were never
825 * registered from those that were already unregistered.
826 * @hide
827 */
828 private static final NetworkRequest ALREADY_UNREGISTERED =
829 new NetworkRequest.Builder().clearCapabilities().build();
830
831 /**
832 * A NetID indicating no Network is selected.
833 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
834 * @hide
835 */
836 public static final int NETID_UNSET = 0;
837
838 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000839 * Flag to indicate that an app is not subject to any restrictions that could result in its
840 * network access blocked.
841 *
842 * @hide
843 */
844 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
845 public static final int BLOCKED_REASON_NONE = 0;
846
847 /**
848 * Flag to indicate that an app is subject to Battery saver restrictions that would
849 * result in its network access being blocked.
850 *
851 * @hide
852 */
853 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
854 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
855
856 /**
857 * Flag to indicate that an app is subject to Doze restrictions that would
858 * result in its network access being blocked.
859 *
860 * @hide
861 */
862 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
863 public static final int BLOCKED_REASON_DOZE = 1 << 1;
864
865 /**
866 * Flag to indicate that an app is subject to App Standby restrictions that would
867 * result in its network access being blocked.
868 *
869 * @hide
870 */
871 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
872 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
873
874 /**
875 * Flag to indicate that an app is subject to Restricted mode restrictions that would
876 * result in its network access being blocked.
877 *
878 * @hide
879 */
880 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
881 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
882
883 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900884 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
885 * is not currently connected.
886 *
887 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
888 *
889 * @hide
890 */
891 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
892 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
893
894 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100895 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
896 * result in its network access being blocked.
897 *
898 * @hide
899 */
900 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
901 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
902
903 /**
Suprabh Shukla2d893b62023-11-06 08:47:40 -0800904 * Flag to indicate that an app is subject to default background restrictions that would
905 * result in its network access being blocked.
906 *
907 * @hide
908 */
909 @FlaggedApi(Flags.BASIC_BACKGROUND_RESTRICTIONS_ENABLED)
910 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
911 public static final int BLOCKED_REASON_APP_BACKGROUND = 1 << 6;
912
913 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000914 * Flag to indicate that an app is subject to Data saver restrictions that would
915 * result in its metered network access being blocked.
916 *
917 * @hide
918 */
919 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
920 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
921
922 /**
923 * Flag to indicate that an app is subject to user restrictions that would
924 * result in its metered network access being blocked.
925 *
926 * @hide
927 */
928 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
929 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
930
931 /**
932 * Flag to indicate that an app is subject to Device admin restrictions that would
933 * result in its metered network access being blocked.
934 *
935 * @hide
936 */
937 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
938 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
939
940 /**
941 * @hide
942 */
943 @Retention(RetentionPolicy.SOURCE)
944 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
945 BLOCKED_REASON_NONE,
946 BLOCKED_REASON_BATTERY_SAVER,
947 BLOCKED_REASON_DOZE,
948 BLOCKED_REASON_APP_STANDBY,
949 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900950 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100951 BLOCKED_REASON_LOW_POWER_STANDBY,
Suprabh Shukla2d893b62023-11-06 08:47:40 -0800952 BLOCKED_REASON_APP_BACKGROUND,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000953 BLOCKED_METERED_REASON_DATA_SAVER,
954 BLOCKED_METERED_REASON_USER_RESTRICTED,
955 BLOCKED_METERED_REASON_ADMIN_DISABLED,
956 })
957 public @interface BlockedReason {}
958
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900959 /**
960 * Set of blocked reasons that are only applicable on metered networks.
961 *
962 * @hide
963 */
964 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
965 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
966
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900967 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
968 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900969
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900970 /**
markchiene1561fa2021-12-09 22:00:56 +0800971 * Firewall chain for device idle (doze mode).
972 * Allowlist of apps that have network access in device idle.
973 * @hide
974 */
975 @SystemApi(client = MODULE_LIBRARIES)
976 public static final int FIREWALL_CHAIN_DOZABLE = 1;
977
978 /**
979 * Firewall chain used for app standby.
980 * Denylist of apps that do not have network access.
981 * @hide
982 */
983 @SystemApi(client = MODULE_LIBRARIES)
984 public static final int FIREWALL_CHAIN_STANDBY = 2;
985
986 /**
987 * Firewall chain used for battery saver.
988 * Allowlist of apps that have network access when battery saver is on.
989 * @hide
990 */
991 @SystemApi(client = MODULE_LIBRARIES)
992 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
993
994 /**
995 * Firewall chain used for restricted networking mode.
996 * Allowlist of apps that have access in restricted networking mode.
997 * @hide
998 */
999 @SystemApi(client = MODULE_LIBRARIES)
1000 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
1001
Robert Horvath34cba142022-01-27 19:52:43 +01001002 /**
1003 * Firewall chain used for low power standby.
1004 * Allowlist of apps that have access in low power standby.
1005 * @hide
1006 */
1007 @SystemApi(client = MODULE_LIBRARIES)
1008 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
1009
Motomu Utsumib08654c2022-05-11 05:56:26 +00001010 /**
Suprabh Shukla2d893b62023-11-06 08:47:40 -08001011 * Firewall chain used for always-on default background restrictions.
1012 * Allowlist of apps that have access because either they are in the foreground or they are
1013 * exempted for specific situations while in the background.
1014 * @hide
1015 */
1016 @FlaggedApi(Flags.BASIC_BACKGROUND_RESTRICTIONS_ENABLED)
1017 @SystemApi(client = MODULE_LIBRARIES)
1018 public static final int FIREWALL_CHAIN_BACKGROUND = 6;
1019
1020 /**
Motomu Utsumid9801492022-06-01 13:57:27 +00001021 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001022 *
1023 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1024 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1025 *
1026 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1027 * independent of the others. The chains can be enabled and disabled independently, and apps can
1028 * be added and removed from each chain independently.
1029 *
1030 * @see #FIREWALL_CHAIN_OEM_DENY_2
1031 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001032 * @hide
1033 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001034 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001035 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1036
1037 /**
1038 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001039 *
1040 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1041 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1042 *
1043 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1044 * independent of the others. The chains can be enabled and disabled independently, and apps can
1045 * be added and removed from each chain independently.
1046 *
1047 * @see #FIREWALL_CHAIN_OEM_DENY_1
1048 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001049 * @hide
1050 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001051 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001052 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1053
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001054 /**
1055 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001056 *
1057 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1058 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1059 *
1060 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1061 * independent of the others. The chains can be enabled and disabled independently, and apps can
1062 * be added and removed from each chain independently.
1063 *
1064 * @see #FIREWALL_CHAIN_OEM_DENY_1
1065 * @see #FIREWALL_CHAIN_OEM_DENY_2
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001066 * @hide
1067 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001068 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001069 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1070
markchiene1561fa2021-12-09 22:00:56 +08001071 /** @hide */
1072 @Retention(RetentionPolicy.SOURCE)
1073 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1074 FIREWALL_CHAIN_DOZABLE,
1075 FIREWALL_CHAIN_STANDBY,
1076 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001077 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001078 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Suprabh Shukla2d893b62023-11-06 08:47:40 -08001079 FIREWALL_CHAIN_BACKGROUND,
Motomu Utsumid9801492022-06-01 13:57:27 +00001080 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001081 FIREWALL_CHAIN_OEM_DENY_2,
1082 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001083 })
1084 public @interface FirewallChain {}
1085
1086 /**
markchien011a7f52022-03-29 01:07:22 +08001087 * A firewall rule which allows or drops packets depending on existing policy.
1088 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1089 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001090 * @hide
1091 */
1092 @SystemApi(client = MODULE_LIBRARIES)
1093 public static final int FIREWALL_RULE_DEFAULT = 0;
1094
1095 /**
markchien011a7f52022-03-29 01:07:22 +08001096 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1097 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001098 * @hide
1099 */
1100 @SystemApi(client = MODULE_LIBRARIES)
1101 public static final int FIREWALL_RULE_ALLOW = 1;
1102
1103 /**
markchien011a7f52022-03-29 01:07:22 +08001104 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1105 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001106 * @hide
1107 */
1108 @SystemApi(client = MODULE_LIBRARIES)
1109 public static final int FIREWALL_RULE_DENY = 2;
1110
1111 /** @hide */
1112 @Retention(RetentionPolicy.SOURCE)
1113 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1114 FIREWALL_RULE_DEFAULT,
1115 FIREWALL_RULE_ALLOW,
1116 FIREWALL_RULE_DENY
1117 })
1118 public @interface FirewallRule {}
1119
1120 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001121 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1122 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1123 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1124 * methods that take a Context argument.
1125 */
1126 private static ConnectivityManager sInstance;
1127
1128 private final Context mContext;
1129
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001130 @GuardedBy("mTetheringEventCallbacks")
1131 private TetheringManager mTetheringManager;
1132
1133 private TetheringManager getTetheringManager() {
1134 synchronized (mTetheringEventCallbacks) {
1135 if (mTetheringManager == null) {
1136 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1137 }
1138 return mTetheringManager;
1139 }
1140 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001141
1142 /**
1143 * Tests if a given integer represents a valid network type.
1144 * @param networkType the type to be tested
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001145 * @return {@code true} if the type is valid, else {@code false}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001146 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1147 * validate a network type.
1148 */
1149 @Deprecated
1150 public static boolean isNetworkTypeValid(int networkType) {
1151 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1152 }
1153
1154 /**
1155 * Returns a non-localized string representing a given network type.
1156 * ONLY used for debugging output.
1157 * @param type the type needing naming
1158 * @return a String for the given type, or a string version of the type ("87")
1159 * if no name is known.
1160 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1161 * {@hide}
1162 */
1163 @Deprecated
1164 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1165 public static String getNetworkTypeName(int type) {
1166 switch (type) {
1167 case TYPE_NONE:
1168 return "NONE";
1169 case TYPE_MOBILE:
1170 return "MOBILE";
1171 case TYPE_WIFI:
1172 return "WIFI";
1173 case TYPE_MOBILE_MMS:
1174 return "MOBILE_MMS";
1175 case TYPE_MOBILE_SUPL:
1176 return "MOBILE_SUPL";
1177 case TYPE_MOBILE_DUN:
1178 return "MOBILE_DUN";
1179 case TYPE_MOBILE_HIPRI:
1180 return "MOBILE_HIPRI";
1181 case TYPE_WIMAX:
1182 return "WIMAX";
1183 case TYPE_BLUETOOTH:
1184 return "BLUETOOTH";
1185 case TYPE_DUMMY:
1186 return "DUMMY";
1187 case TYPE_ETHERNET:
1188 return "ETHERNET";
1189 case TYPE_MOBILE_FOTA:
1190 return "MOBILE_FOTA";
1191 case TYPE_MOBILE_IMS:
1192 return "MOBILE_IMS";
1193 case TYPE_MOBILE_CBS:
1194 return "MOBILE_CBS";
1195 case TYPE_WIFI_P2P:
1196 return "WIFI_P2P";
1197 case TYPE_MOBILE_IA:
1198 return "MOBILE_IA";
1199 case TYPE_MOBILE_EMERGENCY:
1200 return "MOBILE_EMERGENCY";
1201 case TYPE_PROXY:
1202 return "PROXY";
1203 case TYPE_VPN:
1204 return "VPN";
Junyu Laic9f1ca62022-07-25 16:31:59 +08001205 case TYPE_TEST:
1206 return "TEST";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001207 default:
1208 return Integer.toString(type);
1209 }
1210 }
1211
1212 /**
1213 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001214 */
lucaslin10774b72021-03-17 14:16:01 +08001215 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001216 public void systemReady() {
1217 try {
1218 mService.systemReady();
1219 } catch (RemoteException e) {
1220 throw e.rethrowFromSystemServer();
1221 }
1222 }
1223
1224 /**
1225 * Checks if a given type uses the cellular data connection.
1226 * This should be replaced in the future by a network property.
1227 * @param networkType the type to check
1228 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1229 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1230 * {@hide}
1231 */
1232 @Deprecated
1233 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1234 public static boolean isNetworkTypeMobile(int networkType) {
1235 switch (networkType) {
1236 case TYPE_MOBILE:
1237 case TYPE_MOBILE_MMS:
1238 case TYPE_MOBILE_SUPL:
1239 case TYPE_MOBILE_DUN:
1240 case TYPE_MOBILE_HIPRI:
1241 case TYPE_MOBILE_FOTA:
1242 case TYPE_MOBILE_IMS:
1243 case TYPE_MOBILE_CBS:
1244 case TYPE_MOBILE_IA:
1245 case TYPE_MOBILE_EMERGENCY:
1246 return true;
1247 default:
1248 return false;
1249 }
1250 }
1251
1252 /**
1253 * Checks if the given network type is backed by a Wi-Fi radio.
1254 *
1255 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1256 * @hide
1257 */
1258 @Deprecated
1259 public static boolean isNetworkTypeWifi(int networkType) {
1260 switch (networkType) {
1261 case TYPE_WIFI:
1262 case TYPE_WIFI_P2P:
1263 return true;
1264 default:
1265 return false;
1266 }
1267 }
1268
1269 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001270 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001271 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Junyu Lai35665cc2022-12-19 17:37:48 +08001272 * Specify that the traffic for this user should by follow the default rules:
1273 * applications in the profile designated by the UserHandle behave like any
1274 * other application and use the system default network as their default
1275 * network. Compare other PROFILE_NETWORK_PREFERENCE_* settings.
Chalard Jeanad565e22021-02-25 17:23:40 +09001276 * @hide
1277 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001278 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001279 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1280
1281 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001282 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001283 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001284 * Specify that the traffic for this user should by default go on a network with
1285 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1286 * if no such network is available.
1287 * @hide
1288 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001289 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001290 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1291
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001292 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001293 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001294 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001295 * Specify that the traffic for this user should by default go on a network with
1296 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
Junyu Lai35665cc2022-12-19 17:37:48 +08001297 * should not have a default network at all (that is, network accesses that
1298 * do not specify a network explicitly terminate with an error), even if there
1299 * is a system default network available to apps outside this preference.
1300 * The apps can still use a non-enterprise network if they request it explicitly
1301 * provided that specific network doesn't require any specific permission they
1302 * do not hold.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001303 * @hide
1304 */
1305 @SystemApi(client = MODULE_LIBRARIES)
1306 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1307
Junyu Lai35665cc2022-12-19 17:37:48 +08001308 /**
1309 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
1310 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1311 * Specify that the traffic for this user should by default go on a network with
1312 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}.
1313 * If there is no such network, the apps will have no default
1314 * network at all, even if there are available non-enterprise networks on the
1315 * device (that is, network accesses that do not specify a network explicitly
1316 * terminate with an error). Additionally, the designated apps should be
1317 * blocked from using any non-enterprise network even if they specify it
1318 * explicitly, unless they hold specific privilege overriding this (see
1319 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS}).
1320 * @hide
1321 */
1322 @SystemApi(client = MODULE_LIBRARIES)
1323 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING = 3;
1324
Chalard Jeanad565e22021-02-25 17:23:40 +09001325 /** @hide */
1326 @Retention(RetentionPolicy.SOURCE)
1327 @IntDef(value = {
1328 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001329 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1330 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001331 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001332 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001333 }
1334
1335 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001336 * Specifies the preferred network type. When the device has more
1337 * than one type available the preferred network type will be used.
1338 *
1339 * @param preference the network type to prefer over all others. It is
1340 * unspecified what happens to the old preferred network in the
1341 * overall ordering.
1342 * @deprecated Functionality has been removed as it no longer makes sense,
1343 * with many more than two networks - we'd need an array to express
1344 * preference. Instead we use dynamic network properties of
1345 * the networks to describe their precedence.
1346 */
1347 @Deprecated
1348 public void setNetworkPreference(int preference) {
1349 }
1350
1351 /**
1352 * Retrieves the current preferred network type.
1353 *
1354 * @return an integer representing the preferred network type
1355 *
1356 * @deprecated Functionality has been removed as it no longer makes sense,
1357 * with many more than two networks - we'd need an array to express
1358 * preference. Instead we use dynamic network properties of
1359 * the networks to describe their precedence.
1360 */
1361 @Deprecated
1362 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1363 public int getNetworkPreference() {
1364 return TYPE_NONE;
1365 }
1366
1367 /**
1368 * Returns details about the currently active default data network. When
1369 * connected, this network is the default route for outgoing connections.
1370 * You should always check {@link NetworkInfo#isConnected()} before initiating
1371 * network traffic. This may return {@code null} when there is no default
1372 * network.
1373 * Note that if the default network is a VPN, this method will return the
1374 * NetworkInfo for one of its underlying networks instead, or null if the
1375 * VPN agent did not specify any. Apps interested in learning about VPNs
1376 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1377 *
1378 * @return a {@link NetworkInfo} object for the current default network
1379 * or {@code null} if no default network is currently active
1380 * @deprecated See {@link NetworkInfo}.
1381 */
1382 @Deprecated
1383 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1384 @Nullable
1385 public NetworkInfo getActiveNetworkInfo() {
1386 try {
1387 return mService.getActiveNetworkInfo();
1388 } catch (RemoteException e) {
1389 throw e.rethrowFromSystemServer();
1390 }
1391 }
1392
1393 /**
1394 * Returns a {@link Network} object corresponding to the currently active
1395 * default data network. In the event that the current active default data
1396 * network disconnects, the returned {@code Network} object will no longer
1397 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001398 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001399 *
1400 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001401 * {@code null} if no default network is currently active or if
1402 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001403 */
1404 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1405 @Nullable
1406 public Network getActiveNetwork() {
1407 try {
1408 return mService.getActiveNetwork();
1409 } catch (RemoteException e) {
1410 throw e.rethrowFromSystemServer();
1411 }
1412 }
1413
1414 /**
1415 * Returns a {@link Network} object corresponding to the currently active
1416 * default data network for a specific UID. In the event that the default data
1417 * network disconnects, the returned {@code Network} object will no longer
1418 * be usable. This will return {@code null} when there is no default
1419 * network for the UID.
1420 *
1421 * @return a {@link Network} object for the current default network for the
1422 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001423 *
1424 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001425 */
1426 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1427 @Nullable
1428 public Network getActiveNetworkForUid(int uid) {
1429 return getActiveNetworkForUid(uid, false);
1430 }
1431
1432 /** {@hide} */
1433 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1434 try {
1435 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1436 } catch (RemoteException e) {
1437 throw e.rethrowFromSystemServer();
1438 }
1439 }
1440
lucaslin3ba7cc22022-12-19 02:35:33 +00001441 private static UidRange[] getUidRangeArray(@NonNull Collection<Range<Integer>> ranges) {
1442 Objects.requireNonNull(ranges);
1443 final UidRange[] rangesArray = new UidRange[ranges.size()];
1444 int index = 0;
1445 for (Range<Integer> range : ranges) {
1446 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1447 }
1448
1449 return rangesArray;
1450 }
1451
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001452 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001453 * Adds or removes a requirement for given UID ranges to use the VPN.
1454 *
1455 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1456 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1457 * otherwise have permission to bypass the VPN (e.g., because they have the
1458 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1459 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1460 * set to {@code false}, a previously-added restriction is removed.
1461 * <p>
1462 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1463 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1464 * remove a previously-added range, the exact range must be removed as is.
1465 * <p>
1466 * The changes are applied asynchronously and may not have been applied by the time the method
1467 * returns. Apps will be notified about any changes that apply to them via
1468 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1469 * effect.
1470 * <p>
lucaslin3ba7cc22022-12-19 02:35:33 +00001471 * This method will block the specified UIDs from accessing non-VPN networks, but does not
1472 * affect what the UIDs get as their default network.
1473 * Compare {@link #setVpnDefaultForUids(String, Collection)}, which declares that the UIDs
1474 * should only have a VPN as their default network, but does not block them from accessing other
1475 * networks if they request them explicitly with the {@link Network} API.
1476 * <p>
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001477 * This method should be called only by the VPN code.
1478 *
1479 * @param ranges the UID ranges to restrict
1480 * @param requireVpn whether the specified UID ranges must use a VPN
1481 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001482 * @hide
1483 */
1484 @RequiresPermission(anyOf = {
1485 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001486 android.Manifest.permission.NETWORK_STACK,
1487 android.Manifest.permission.NETWORK_SETTINGS})
1488 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001489 public void setRequireVpnForUids(boolean requireVpn,
1490 @NonNull Collection<Range<Integer>> ranges) {
1491 Objects.requireNonNull(ranges);
1492 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1493 // This method is not necessarily expected to be used outside the system server, so
1494 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1495 // stack process, or by tests.
lucaslin3ba7cc22022-12-19 02:35:33 +00001496 final UidRange[] rangesArray = getUidRangeArray(ranges);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001497 try {
1498 mService.setRequireVpnForUids(requireVpn, rangesArray);
1499 } catch (RemoteException e) {
1500 throw e.rethrowFromSystemServer();
1501 }
1502 }
1503
1504 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001505 * Inform the system that this VPN session should manage the passed UIDs.
1506 *
1507 * A VPN with the specified session ID may call this method to inform the system that the UIDs
1508 * in the specified range are subject to a VPN.
1509 * When this is called, the system will only choose a VPN for the default network of the UIDs in
1510 * the specified ranges.
1511 *
1512 * This method declares that the UIDs in the range will only have a VPN for their default
1513 * network, but does not block the UIDs from accessing other networks (permissions allowing) by
1514 * explicitly requesting it with the {@link Network} API.
1515 * Compare {@link #setRequireVpnForUids(boolean, Collection)}, which does not affect what
1516 * network the UIDs get as default, but will block them from accessing non-VPN networks.
1517 *
1518 * @param session The VPN session which manages the passed UIDs.
1519 * @param ranges The uid ranges which will treat VPN as their only default network.
1520 *
1521 * @hide
1522 */
1523 @RequiresPermission(anyOf = {
1524 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1525 android.Manifest.permission.NETWORK_STACK,
1526 android.Manifest.permission.NETWORK_SETTINGS})
1527 @SystemApi(client = MODULE_LIBRARIES)
1528 public void setVpnDefaultForUids(@NonNull String session,
1529 @NonNull Collection<Range<Integer>> ranges) {
1530 Objects.requireNonNull(ranges);
1531 final UidRange[] rangesArray = getUidRangeArray(ranges);
1532 try {
1533 mService.setVpnNetworkPreference(session, rangesArray);
1534 } catch (RemoteException e) {
1535 throw e.rethrowFromSystemServer();
1536 }
1537 }
1538
1539 /**
chiachangwange0192a72023-02-06 13:25:01 +00001540 * Temporarily set automaticOnOff keeplaive TCP polling alarm timer to 1 second.
1541 *
1542 * TODO: Remove this when the TCP polling design is replaced with callback.
Jean Chalard17cbf062023-02-13 05:07:48 +00001543 * @param timeMs The time of expiry, with System.currentTimeMillis() base. The value should be
1544 * set no more than 5 minutes in the future.
chiachangwange0192a72023-02-06 13:25:01 +00001545 * @hide
1546 */
1547 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
1548 try {
1549 mService.setTestLowTcpPollingTimerForKeepalive(timeMs);
1550 } catch (RemoteException e) {
1551 throw e.rethrowFromSystemServer();
1552 }
1553 }
1554
1555 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001556 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1557 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1558 * but is still supported for backwards compatibility.
1559 * <p>
1560 * This type of VPN is assumed always to use the system default network, and must always declare
1561 * exactly one underlying network, which is the network that was the default when the VPN
1562 * connected.
1563 * <p>
1564 * Calling this method with {@code true} enables legacy behaviour, specifically:
1565 * <ul>
1566 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1567 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1568 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1569 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1570 * underlying the VPN.</li>
1571 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1572 * similarly replaced by the VPN network state.</li>
1573 * <li>Information on current network interfaces passed to NetworkStatsService will not
1574 * include any VPN interfaces.</li>
1575 * </ul>
1576 *
1577 * @param enabled whether legacy lockdown VPN is enabled or disabled
1578 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001579 * @hide
1580 */
1581 @RequiresPermission(anyOf = {
1582 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001583 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001584 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001585 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001586 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1587 try {
1588 mService.setLegacyLockdownVpnEnabled(enabled);
1589 } catch (RemoteException e) {
1590 throw e.rethrowFromSystemServer();
1591 }
1592 }
1593
1594 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001595 * Returns details about the currently active default data network for a given uid.
1596 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001597 *
1598 * @return a {@link NetworkInfo} object for the current default network
1599 * for the given uid or {@code null} if no default network is
1600 * available for the specified uid.
1601 *
1602 * {@hide}
1603 */
1604 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1605 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1606 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1607 return getActiveNetworkInfoForUid(uid, false);
1608 }
1609
1610 /** {@hide} */
1611 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1612 try {
1613 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1614 } catch (RemoteException e) {
1615 throw e.rethrowFromSystemServer();
1616 }
1617 }
1618
1619 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001620 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001621 *
1622 * @param networkType integer specifying which networkType in
1623 * which you're interested.
1624 * @return a {@link NetworkInfo} object for the requested
1625 * network type or {@code null} if the type is not
1626 * supported by the device. If {@code networkType} is
1627 * TYPE_VPN and a VPN is active for the calling app,
1628 * then this method will try to return one of the
1629 * underlying networks for the VPN or null if the
1630 * VPN agent didn't specify any.
1631 *
1632 * @deprecated This method does not support multiple connected networks
1633 * of the same type. Use {@link #getAllNetworks} and
1634 * {@link #getNetworkInfo(android.net.Network)} instead.
1635 */
1636 @Deprecated
1637 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1638 @Nullable
1639 public NetworkInfo getNetworkInfo(int networkType) {
1640 try {
1641 return mService.getNetworkInfo(networkType);
1642 } catch (RemoteException e) {
1643 throw e.rethrowFromSystemServer();
1644 }
1645 }
1646
1647 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001648 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001649 *
1650 * @param network {@link Network} specifying which network
1651 * in which you're interested.
1652 * @return a {@link NetworkInfo} object for the requested
1653 * network or {@code null} if the {@code Network}
1654 * is not valid.
1655 * @deprecated See {@link NetworkInfo}.
1656 */
1657 @Deprecated
1658 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1659 @Nullable
1660 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1661 return getNetworkInfoForUid(network, Process.myUid(), false);
1662 }
1663
1664 /** {@hide} */
1665 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1666 try {
1667 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1668 } catch (RemoteException e) {
1669 throw e.rethrowFromSystemServer();
1670 }
1671 }
1672
1673 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001674 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001675 *
1676 * @return an array of {@link NetworkInfo} objects. Check each
1677 * {@link NetworkInfo#getType} for which type each applies.
1678 *
1679 * @deprecated This method does not support multiple connected networks
1680 * of the same type. Use {@link #getAllNetworks} and
1681 * {@link #getNetworkInfo(android.net.Network)} instead.
1682 */
1683 @Deprecated
1684 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1685 @NonNull
1686 public NetworkInfo[] getAllNetworkInfo() {
1687 try {
1688 return mService.getAllNetworkInfo();
1689 } catch (RemoteException e) {
1690 throw e.rethrowFromSystemServer();
1691 }
1692 }
1693
1694 /**
junyulaib1211372021-03-03 12:09:05 +08001695 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1696 * connected.
1697 * @hide
1698 */
1699 @SystemApi(client = MODULE_LIBRARIES)
1700 @RequiresPermission(anyOf = {
1701 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1702 android.Manifest.permission.NETWORK_STACK,
1703 android.Manifest.permission.NETWORK_SETTINGS})
1704 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001705 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001706 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001707 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001708 } catch (RemoteException e) {
1709 throw e.rethrowFromSystemServer();
1710 }
1711 }
1712
1713 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001714 * Returns the {@link Network} object currently serving a given type, or
1715 * null if the given type is not connected.
1716 *
1717 * @hide
1718 * @deprecated This method does not support multiple connected networks
1719 * of the same type. Use {@link #getAllNetworks} and
1720 * {@link #getNetworkInfo(android.net.Network)} instead.
1721 */
1722 @Deprecated
1723 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1724 @UnsupportedAppUsage
1725 public Network getNetworkForType(int networkType) {
1726 try {
1727 return mService.getNetworkForType(networkType);
1728 } catch (RemoteException e) {
1729 throw e.rethrowFromSystemServer();
1730 }
1731 }
1732
1733 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001734 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001735 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001736 * @deprecated This method does not provide any notification of network state changes, forcing
1737 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1738 * Apps should use methods such as
1739 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1740 * Apps that desire to obtain information about networks that do not apply to them
1741 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1742 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001743 * @return an array of {@link Network} objects.
1744 */
1745 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1746 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001747 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001748 public Network[] getAllNetworks() {
1749 try {
1750 return mService.getAllNetworks();
1751 } catch (RemoteException e) {
1752 throw e.rethrowFromSystemServer();
1753 }
1754 }
1755
1756 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001757 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001758 * the Networks that applications run by the given user will use by default.
1759 * @hide
1760 */
1761 @UnsupportedAppUsage
1762 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1763 try {
1764 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001765 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001766 } catch (RemoteException e) {
1767 throw e.rethrowFromSystemServer();
1768 }
1769 }
1770
1771 /**
1772 * Returns the IP information for the current default network.
1773 *
1774 * @return a {@link LinkProperties} object describing the IP info
1775 * for the current default network, or {@code null} if there
1776 * is no current default network.
1777 *
1778 * {@hide}
1779 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1780 * value of {@link #getActiveNetwork()} instead. In particular,
1781 * this method will return non-null LinkProperties even if the
1782 * app is blocked by policy from using this network.
1783 */
1784 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1785 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1786 public LinkProperties getActiveLinkProperties() {
1787 try {
1788 return mService.getActiveLinkProperties();
1789 } catch (RemoteException e) {
1790 throw e.rethrowFromSystemServer();
1791 }
1792 }
1793
1794 /**
1795 * Returns the IP information for a given network type.
1796 *
1797 * @param networkType the network type of interest.
1798 * @return a {@link LinkProperties} object describing the IP info
1799 * for the given networkType, or {@code null} if there is
1800 * no current default network.
1801 *
1802 * {@hide}
1803 * @deprecated This method does not support multiple connected networks
1804 * of the same type. Use {@link #getAllNetworks},
1805 * {@link #getNetworkInfo(android.net.Network)}, and
1806 * {@link #getLinkProperties(android.net.Network)} instead.
1807 */
1808 @Deprecated
1809 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1810 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1811 public LinkProperties getLinkProperties(int networkType) {
1812 try {
1813 return mService.getLinkPropertiesForType(networkType);
1814 } catch (RemoteException e) {
1815 throw e.rethrowFromSystemServer();
1816 }
1817 }
1818
1819 /**
1820 * Get the {@link LinkProperties} for the given {@link Network}. This
1821 * will return {@code null} if the network is unknown.
1822 *
1823 * @param network The {@link Network} object identifying the network in question.
1824 * @return The {@link LinkProperties} for the network, or {@code null}.
1825 */
1826 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1827 @Nullable
1828 public LinkProperties getLinkProperties(@Nullable Network network) {
1829 try {
1830 return mService.getLinkProperties(network);
1831 } catch (RemoteException e) {
1832 throw e.rethrowFromSystemServer();
1833 }
1834 }
1835
1836 /**
lucaslinc582d502022-01-27 09:07:00 +08001837 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001838 *
lucaslinc582d502022-01-27 09:07:00 +08001839 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1840 * given package, considering its permissions.
1841 *
1842 * @param lp A {@link LinkProperties} which will be redacted.
1843 * @param uid The target uid.
1844 * @param packageName The name of the package, for appops logging.
1845 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1846 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1847 * @hide
1848 */
1849 @RequiresPermission(anyOf = {
1850 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1851 android.Manifest.permission.NETWORK_STACK,
1852 android.Manifest.permission.NETWORK_SETTINGS})
1853 @SystemApi(client = MODULE_LIBRARIES)
1854 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001855 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001856 @NonNull String packageName) {
1857 try {
lucaslind2b06132022-03-02 10:56:57 +08001858 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001859 lp, uid, packageName, getAttributionTag());
1860 } catch (RemoteException e) {
1861 throw e.rethrowFromSystemServer();
1862 }
1863 }
1864
1865 /**
1866 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1867 *
1868 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1869 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1870 * sensitive information. To retrieve this location sensitive information (subject to
1871 * the caller's location permissions), use a {@link NetworkCallback} with the
1872 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1873 *
1874 * This method returns {@code null} if the network is unknown or if the |network| argument
1875 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001876 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001877 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001878 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001879 */
1880 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1881 @Nullable
1882 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1883 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001884 return mService.getNetworkCapabilities(
1885 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001886 } catch (RemoteException e) {
1887 throw e.rethrowFromSystemServer();
1888 }
1889 }
1890
1891 /**
lucaslinc582d502022-01-27 09:07:00 +08001892 * Redact {@link NetworkCapabilities} for a given package.
1893 *
1894 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001895 * to the given package, considering its permissions. If the passed capabilities contain
1896 * location-sensitive information, they will be redacted to the correct degree for the location
1897 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1898 * that level of location. If the UID holds no location permission, the returned object will
1899 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001900 *
1901 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1902 * @param uid The target uid.
1903 * @param packageName The name of the package, for appops logging.
1904 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1905 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1906 * @hide
1907 */
1908 @RequiresPermission(anyOf = {
1909 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1910 android.Manifest.permission.NETWORK_STACK,
1911 android.Manifest.permission.NETWORK_SETTINGS})
1912 @SystemApi(client = MODULE_LIBRARIES)
1913 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001914 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001915 @NonNull NetworkCapabilities nc,
1916 int uid, @NonNull String packageName) {
1917 try {
lucaslind2b06132022-03-02 10:56:57 +08001918 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001919 getAttributionTag());
1920 } catch (RemoteException e) {
1921 throw e.rethrowFromSystemServer();
1922 }
1923 }
1924
1925 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001926 * Gets a URL that can be used for resolving whether a captive portal is present.
1927 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1928 * portal is present.
1929 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1930 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1931 *
1932 * The system network validation may be using different strategies to detect captive portals,
1933 * so this method does not necessarily return a URL used by the system. It only returns a URL
1934 * that may be relevant for other components trying to detect captive portals.
1935 *
1936 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001937 * @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 +09001938 * system.
1939 */
1940 @Deprecated
1941 @SystemApi
1942 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1943 public String getCaptivePortalServerUrl() {
1944 try {
1945 return mService.getCaptivePortalServerUrl();
1946 } catch (RemoteException e) {
1947 throw e.rethrowFromSystemServer();
1948 }
1949 }
1950
1951 /**
1952 * Tells the underlying networking system that the caller wants to
1953 * begin using the named feature. The interpretation of {@code feature}
1954 * is completely up to each networking implementation.
1955 *
1956 * <p>This method requires the caller to hold either the
1957 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1958 * or the ability to modify system settings as determined by
1959 * {@link android.provider.Settings.System#canWrite}.</p>
1960 *
1961 * @param networkType specifies which network the request pertains to
1962 * @param feature the name of the feature to be used
1963 * @return an integer value representing the outcome of the request.
1964 * The interpretation of this value is specific to each networking
1965 * implementation+feature combination, except that the value {@code -1}
1966 * always indicates failure.
1967 *
1968 * @deprecated Deprecated in favor of the cleaner
1969 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1970 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1971 * throw {@code UnsupportedOperationException} if called.
1972 * @removed
1973 */
1974 @Deprecated
1975 public int startUsingNetworkFeature(int networkType, String feature) {
1976 checkLegacyRoutingApiAccess();
1977 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1978 if (netCap == null) {
1979 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1980 feature);
1981 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1982 }
1983
1984 NetworkRequest request = null;
1985 synchronized (sLegacyRequests) {
1986 LegacyRequest l = sLegacyRequests.get(netCap);
1987 if (l != null) {
1988 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1989 renewRequestLocked(l);
1990 if (l.currentNetwork != null) {
1991 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1992 } else {
1993 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1994 }
1995 }
1996
1997 request = requestNetworkForFeatureLocked(netCap);
1998 }
1999 if (request != null) {
2000 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
2001 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
2002 } else {
2003 Log.d(TAG, " request Failed");
2004 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
2005 }
2006 }
2007
2008 /**
2009 * Tells the underlying networking system that the caller is finished
2010 * using the named feature. The interpretation of {@code feature}
2011 * is completely up to each networking implementation.
2012 *
2013 * <p>This method requires the caller to hold either the
2014 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2015 * or the ability to modify system settings as determined by
2016 * {@link android.provider.Settings.System#canWrite}.</p>
2017 *
2018 * @param networkType specifies which network the request pertains to
2019 * @param feature the name of the feature that is no longer needed
2020 * @return an integer value representing the outcome of the request.
2021 * The interpretation of this value is specific to each networking
2022 * implementation+feature combination, except that the value {@code -1}
2023 * always indicates failure.
2024 *
2025 * @deprecated Deprecated in favor of the cleaner
2026 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
2027 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2028 * throw {@code UnsupportedOperationException} if called.
2029 * @removed
2030 */
2031 @Deprecated
2032 public int stopUsingNetworkFeature(int networkType, String feature) {
2033 checkLegacyRoutingApiAccess();
2034 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
2035 if (netCap == null) {
2036 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
2037 feature);
2038 return -1;
2039 }
2040
2041 if (removeRequestForFeature(netCap)) {
2042 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
2043 }
2044 return 1;
2045 }
2046
2047 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2048 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
2049 if (networkType == TYPE_MOBILE) {
2050 switch (feature) {
2051 case "enableCBS":
2052 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
2053 case "enableDUN":
2054 case "enableDUNAlways":
2055 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
2056 case "enableFOTA":
2057 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
2058 case "enableHIPRI":
2059 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
2060 case "enableIMS":
2061 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
2062 case "enableMMS":
2063 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
2064 case "enableSUPL":
2065 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
2066 default:
2067 return null;
2068 }
2069 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
2070 return networkCapabilitiesForType(TYPE_WIFI_P2P);
2071 }
2072 return null;
2073 }
2074
2075 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
2076 if (netCap == null) return TYPE_NONE;
2077 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
2078 return TYPE_MOBILE_CBS;
2079 }
2080 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2081 return TYPE_MOBILE_IMS;
2082 }
2083 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
2084 return TYPE_MOBILE_FOTA;
2085 }
2086 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
2087 return TYPE_MOBILE_DUN;
2088 }
2089 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
2090 return TYPE_MOBILE_SUPL;
2091 }
2092 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2093 return TYPE_MOBILE_MMS;
2094 }
2095 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
2096 return TYPE_MOBILE_HIPRI;
2097 }
2098 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
2099 return TYPE_WIFI_P2P;
2100 }
2101 return TYPE_NONE;
2102 }
2103
2104 private static class LegacyRequest {
2105 NetworkCapabilities networkCapabilities;
2106 NetworkRequest networkRequest;
2107 int expireSequenceNumber;
2108 Network currentNetwork;
2109 int delay = -1;
2110
2111 private void clearDnsBinding() {
2112 if (currentNetwork != null) {
2113 currentNetwork = null;
2114 setProcessDefaultNetworkForHostResolution(null);
2115 }
2116 }
2117
2118 NetworkCallback networkCallback = new NetworkCallback() {
2119 @Override
2120 public void onAvailable(Network network) {
2121 currentNetwork = network;
2122 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
2123 setProcessDefaultNetworkForHostResolution(network);
2124 }
2125 @Override
2126 public void onLost(Network network) {
2127 if (network.equals(currentNetwork)) clearDnsBinding();
2128 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2129 }
2130 };
2131 }
2132
2133 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2134 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2135 new HashMap<>();
2136
2137 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2138 synchronized (sLegacyRequests) {
2139 LegacyRequest l = sLegacyRequests.get(netCap);
2140 if (l != null) return l.networkRequest;
2141 }
2142 return null;
2143 }
2144
2145 private void renewRequestLocked(LegacyRequest l) {
2146 l.expireSequenceNumber++;
2147 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2148 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2149 }
2150
2151 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2152 int ourSeqNum = -1;
2153 synchronized (sLegacyRequests) {
2154 LegacyRequest l = sLegacyRequests.get(netCap);
2155 if (l == null) return;
2156 ourSeqNum = l.expireSequenceNumber;
2157 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2158 }
2159 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2160 }
2161
2162 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2163 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2164 int delay = -1;
2165 int type = legacyTypeForNetworkCapabilities(netCap);
2166 try {
2167 delay = mService.getRestoreDefaultNetworkDelay(type);
2168 } catch (RemoteException e) {
2169 throw e.rethrowFromSystemServer();
2170 }
2171 LegacyRequest l = new LegacyRequest();
2172 l.networkCapabilities = netCap;
2173 l.delay = delay;
2174 l.expireSequenceNumber = 0;
2175 l.networkRequest = sendRequestForNetwork(
2176 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2177 if (l.networkRequest == null) return null;
2178 sLegacyRequests.put(netCap, l);
2179 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2180 return l.networkRequest;
2181 }
2182
2183 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2184 if (delay >= 0) {
2185 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2186 CallbackHandler handler = getDefaultHandler();
2187 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2188 handler.sendMessageDelayed(msg, delay);
2189 }
2190 }
2191
2192 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2193 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2194 final LegacyRequest l;
2195 synchronized (sLegacyRequests) {
2196 l = sLegacyRequests.remove(netCap);
2197 }
2198 if (l == null) return false;
2199 unregisterNetworkCallback(l.networkCallback);
2200 l.clearDnsBinding();
2201 return true;
2202 }
2203
2204 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2205 static {
2206 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2207 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2208 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2209 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2210 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2211 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2212 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2213 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2214 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2215 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2216 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2217 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2218 }
2219
2220 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2221 static {
2222 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2223 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2224 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2225 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2226 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2227 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2228 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2229 }
2230
2231 /**
2232 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2233 * instance suitable for registering a request or callback. Throws an
2234 * IllegalArgumentException if no mapping from the legacy type to
2235 * NetworkCapabilities is known.
2236 *
2237 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2238 * to find the network instead.
2239 * @hide
2240 */
2241 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2242 final NetworkCapabilities nc = new NetworkCapabilities();
2243
2244 // Map from type to transports.
2245 final int NOT_FOUND = -1;
2246 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002247 if (transport == NOT_FOUND) {
2248 throw new IllegalArgumentException("unknown legacy type: " + type);
2249 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002250 nc.addTransportType(transport);
2251
2252 // Map from type to capabilities.
2253 nc.addCapability(sLegacyTypeToCapability.get(
2254 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2255 nc.maybeMarkCapabilitiesRestricted();
2256 return nc;
2257 }
2258
2259 /** @hide */
2260 public static class PacketKeepaliveCallback {
2261 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2262 public PacketKeepaliveCallback() {
2263 }
2264 /** The requested keepalive was successfully started. */
2265 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2266 public void onStarted() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002267 /** The keepalive was resumed after being paused by the system. */
2268 public void onResumed() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002269 /** The keepalive was successfully stopped. */
2270 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2271 public void onStopped() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002272 /** The keepalive was paused automatically by the system. */
2273 public void onPaused() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002274 /** An error occurred. */
2275 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2276 public void onError(int error) {}
2277 }
2278
2279 /**
2280 * Allows applications to request that the system periodically send specific packets on their
2281 * behalf, using hardware offload to save battery power.
2282 *
2283 * To request that the system send keepalives, call one of the methods that return a
2284 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2285 * passing in a non-null callback. If the callback is successfully started, the callback's
2286 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2287 * specifying one of the {@code ERROR_*} constants in this class.
2288 *
2289 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2290 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2291 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2292 *
2293 * @deprecated Use {@link SocketKeepalive} instead.
2294 *
2295 * @hide
2296 */
2297 public class PacketKeepalive {
2298
2299 private static final String TAG = "PacketKeepalive";
2300
2301 /** @hide */
2302 public static final int SUCCESS = 0;
2303
2304 /** @hide */
2305 public static final int NO_KEEPALIVE = -1;
2306
2307 /** @hide */
2308 public static final int BINDER_DIED = -10;
2309
2310 /** The specified {@code Network} is not connected. */
2311 public static final int ERROR_INVALID_NETWORK = -20;
2312 /** The specified IP addresses are invalid. For example, the specified source IP address is
2313 * not configured on the specified {@code Network}. */
2314 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2315 /** The requested port is invalid. */
2316 public static final int ERROR_INVALID_PORT = -22;
2317 /** The packet length is invalid (e.g., too long). */
2318 public static final int ERROR_INVALID_LENGTH = -23;
2319 /** The packet transmission interval is invalid (e.g., too short). */
2320 public static final int ERROR_INVALID_INTERVAL = -24;
2321
2322 /** The hardware does not support this request. */
2323 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2324 /** The hardware returned an error. */
2325 public static final int ERROR_HARDWARE_ERROR = -31;
2326
2327 /** The NAT-T destination port for IPsec */
2328 public static final int NATT_PORT = 4500;
2329
2330 /** The minimum interval in seconds between keepalive packet transmissions */
2331 public static final int MIN_INTERVAL = 10;
2332
2333 private final Network mNetwork;
2334 private final ISocketKeepaliveCallback mCallback;
2335 private final ExecutorService mExecutor;
2336
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002337 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2338 public void stop() {
2339 try {
2340 mExecutor.execute(() -> {
2341 try {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002342 mService.stopKeepalive(mCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002343 } catch (RemoteException e) {
2344 Log.e(TAG, "Error stopping packet keepalive: ", e);
2345 throw e.rethrowFromSystemServer();
2346 }
2347 });
2348 } catch (RejectedExecutionException e) {
2349 // The internal executor has already stopped due to previous event.
2350 }
2351 }
2352
2353 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002354 Objects.requireNonNull(network, "network cannot be null");
2355 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002356 mNetwork = network;
2357 mExecutor = Executors.newSingleThreadExecutor();
2358 mCallback = new ISocketKeepaliveCallback.Stub() {
2359 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002360 public void onStarted() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002361 final long token = Binder.clearCallingIdentity();
2362 try {
2363 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002364 callback.onStarted();
2365 });
2366 } finally {
2367 Binder.restoreCallingIdentity(token);
2368 }
2369 }
2370
2371 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002372 public void onResumed() {
2373 final long token = Binder.clearCallingIdentity();
2374 try {
2375 mExecutor.execute(() -> {
2376 callback.onResumed();
2377 });
2378 } finally {
2379 Binder.restoreCallingIdentity(token);
2380 }
2381 }
2382
2383 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002384 public void onStopped() {
2385 final long token = Binder.clearCallingIdentity();
2386 try {
2387 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002388 callback.onStopped();
2389 });
2390 } finally {
2391 Binder.restoreCallingIdentity(token);
2392 }
2393 mExecutor.shutdown();
2394 }
2395
2396 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002397 public void onPaused() {
2398 final long token = Binder.clearCallingIdentity();
2399 try {
2400 mExecutor.execute(() -> {
2401 callback.onPaused();
2402 });
2403 } finally {
2404 Binder.restoreCallingIdentity(token);
2405 }
2406 mExecutor.shutdown();
2407 }
2408
2409 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002410 public void onError(int error) {
2411 final long token = Binder.clearCallingIdentity();
2412 try {
2413 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002414 callback.onError(error);
2415 });
2416 } finally {
2417 Binder.restoreCallingIdentity(token);
2418 }
2419 mExecutor.shutdown();
2420 }
2421
2422 @Override
2423 public void onDataReceived() {
2424 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2425 // this callback when data is received.
2426 }
2427 };
2428 }
2429 }
2430
2431 /**
2432 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2433 *
2434 * @deprecated Use {@link #createSocketKeepalive} instead.
2435 *
2436 * @hide
2437 */
2438 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2439 public PacketKeepalive startNattKeepalive(
2440 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2441 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2442 final PacketKeepalive k = new PacketKeepalive(network, callback);
2443 try {
2444 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2445 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2446 } catch (RemoteException e) {
2447 Log.e(TAG, "Error starting packet keepalive: ", e);
2448 throw e.rethrowFromSystemServer();
2449 }
2450 return k;
2451 }
2452
2453 // Construct an invalid fd.
2454 private ParcelFileDescriptor createInvalidFd() {
2455 final int invalidFd = -1;
2456 return ParcelFileDescriptor.adoptFd(invalidFd);
2457 }
2458
2459 /**
2460 * Request that keepalives be started on a IPsec NAT-T socket.
2461 *
2462 * @param network The {@link Network} the socket is on.
2463 * @param socket The socket that needs to be kept alive.
2464 * @param source The source address of the {@link UdpEncapsulationSocket}.
2465 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2466 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2467 * must run callback sequentially, otherwise the order of callbacks cannot be
2468 * guaranteed.
2469 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2470 * changes. Must be extended by applications that use this API.
2471 *
2472 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2473 * given socket.
2474 **/
2475 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2476 @NonNull UdpEncapsulationSocket socket,
2477 @NonNull InetAddress source,
2478 @NonNull InetAddress destination,
2479 @NonNull @CallbackExecutor Executor executor,
2480 @NonNull Callback callback) {
2481 ParcelFileDescriptor dup;
2482 try {
2483 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2484 // which cannot be obtained by the app process.
2485 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2486 } catch (IOException ignored) {
2487 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2488 // ERROR_INVALID_SOCKET.
2489 dup = createInvalidFd();
2490 }
2491 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2492 destination, executor, callback);
2493 }
2494
2495 /**
2496 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2497 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2498 *
2499 * @param network The {@link Network} the socket is on.
2500 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2501 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2502 * from that port.
2503 * @param source The source address of the {@link UdpEncapsulationSocket}.
2504 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2505 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2506 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2507 * must run callback sequentially, otherwise the order of callbacks cannot be
2508 * guaranteed.
2509 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2510 * changes. Must be extended by applications that use this API.
2511 *
2512 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2513 * given socket.
2514 * @hide
2515 */
2516 @SystemApi
2517 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2518 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2519 @NonNull ParcelFileDescriptor pfd,
2520 @NonNull InetAddress source,
2521 @NonNull InetAddress destination,
2522 @NonNull @CallbackExecutor Executor executor,
2523 @NonNull Callback callback) {
2524 ParcelFileDescriptor dup;
2525 try {
2526 // TODO: Consider remove unnecessary dup.
2527 dup = pfd.dup();
2528 } catch (IOException ignored) {
2529 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2530 // ERROR_INVALID_SOCKET.
2531 dup = createInvalidFd();
2532 }
2533 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002534 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002535 }
2536
2537 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002538 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002539 *
2540 * @param network The {@link Network} the socket is on.
2541 * @param socket The socket that needs to be kept alive.
2542 * @param executor The executor on which callback will be invoked. This implementation assumes
2543 * the provided {@link Executor} runs the callbacks in sequence with no
2544 * concurrency. Failing this, no guarantee of correctness can be made. It is
2545 * the responsibility of the caller to ensure the executor provides this
2546 * guarantee. A simple way of creating such an executor is with the standard
2547 * tool {@code Executors.newSingleThreadExecutor}.
2548 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2549 * changes. Must be extended by applications that use this API.
2550 *
2551 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2552 * given socket.
2553 * @hide
2554 */
2555 @SystemApi
2556 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2557 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2558 @NonNull Socket socket,
Sherri Lin443b7182023-02-08 04:49:29 +01002559 @NonNull @CallbackExecutor Executor executor,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002560 @NonNull Callback callback) {
2561 ParcelFileDescriptor dup;
2562 try {
2563 dup = ParcelFileDescriptor.fromSocket(socket);
2564 } catch (UncheckedIOException ignored) {
2565 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2566 // ERROR_INVALID_SOCKET.
2567 dup = createInvalidFd();
2568 }
2569 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2570 }
2571
2572 /**
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +09002573 * Get the supported keepalive count for each transport configured in resource overlays.
2574 *
2575 * @return An array of supported keepalive count for each transport type.
2576 * @hide
2577 */
2578 @RequiresPermission(anyOf = { android.Manifest.permission.NETWORK_SETTINGS,
2579 // CTS 13 used QUERY_ALL_PACKAGES to get the resource value, which was implemented
2580 // as below in KeepaliveUtils. Also allow that permission so that KeepaliveUtils can
2581 // use this method and avoid breaking released CTS. Apps that have this permission
2582 // can query the resource themselves anyway.
2583 android.Manifest.permission.QUERY_ALL_PACKAGES })
2584 public int[] getSupportedKeepalives() {
2585 try {
2586 return mService.getSupportedKeepalives();
2587 } catch (RemoteException e) {
2588 throw e.rethrowFromSystemServer();
2589 }
2590 }
2591
2592 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002593 * Ensure that a network route exists to deliver traffic to the specified
2594 * host via the specified network interface. An attempt to add a route that
2595 * already exists is ignored, but treated as successful.
2596 *
2597 * <p>This method requires the caller to hold either the
2598 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2599 * or the ability to modify system settings as determined by
2600 * {@link android.provider.Settings.System#canWrite}.</p>
2601 *
2602 * @param networkType the type of the network over which traffic to the specified
2603 * host is to be routed
2604 * @param hostAddress the IP address of the host to which the route is desired
2605 * @return {@code true} on success, {@code false} on failure
2606 *
2607 * @deprecated Deprecated in favor of the
2608 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2609 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2610 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2611 * throw {@code UnsupportedOperationException} if called.
2612 * @removed
2613 */
2614 @Deprecated
2615 public boolean requestRouteToHost(int networkType, int hostAddress) {
2616 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2617 }
2618
2619 /**
2620 * Ensure that a network route exists to deliver traffic to the specified
2621 * host via the specified network interface. An attempt to add a route that
2622 * already exists is ignored, but treated as successful.
2623 *
2624 * <p>This method requires the caller to hold either the
2625 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2626 * or the ability to modify system settings as determined by
2627 * {@link android.provider.Settings.System#canWrite}.</p>
2628 *
2629 * @param networkType the type of the network over which traffic to the specified
2630 * host is to be routed
2631 * @param hostAddress the IP address of the host to which the route is desired
2632 * @return {@code true} on success, {@code false} on failure
2633 * @hide
2634 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2635 * {@link #bindProcessToNetwork} API.
2636 */
2637 @Deprecated
2638 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002639 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002640 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2641 checkLegacyRoutingApiAccess();
2642 try {
2643 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2644 mContext.getOpPackageName(), getAttributionTag());
2645 } catch (RemoteException e) {
2646 throw e.rethrowFromSystemServer();
2647 }
2648 }
2649
2650 /**
2651 * @return the context's attribution tag
2652 */
2653 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2654 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002655 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002656 }
2657
2658 /**
2659 * Returns the value of the setting for background data usage. If false,
2660 * applications should not use the network if the application is not in the
2661 * foreground. Developers should respect this setting, and check the value
2662 * of this before performing any background data operations.
2663 * <p>
2664 * All applications that have background services that use the network
2665 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2666 * <p>
2667 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2668 * background data depends on several combined factors, and this method will
2669 * always return {@code true}. Instead, when background data is unavailable,
2670 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2671 *
2672 * @return Whether background data usage is allowed.
2673 */
2674 @Deprecated
2675 public boolean getBackgroundDataSetting() {
2676 // assume that background data is allowed; final authority is
2677 // NetworkInfo which may be blocked.
2678 return true;
2679 }
2680
2681 /**
2682 * Sets the value of the setting for background data usage.
2683 *
2684 * @param allowBackgroundData Whether an application should use data while
2685 * it is in the background.
2686 *
2687 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2688 * @see #getBackgroundDataSetting()
2689 * @hide
2690 */
2691 @Deprecated
2692 @UnsupportedAppUsage
2693 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2694 // ignored
2695 }
2696
2697 /**
2698 * @hide
2699 * @deprecated Talk to TelephonyManager directly
2700 */
2701 @Deprecated
2702 @UnsupportedAppUsage
2703 public boolean getMobileDataEnabled() {
2704 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2705 if (tm != null) {
2706 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2707 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2708 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2709 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2710 + " retVal=" + retVal);
2711 return retVal;
2712 }
2713 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2714 return false;
2715 }
2716
2717 /**
2718 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2719 * to find out when the system default network has gone in to a high power state.
2720 */
2721 public interface OnNetworkActiveListener {
2722 /**
2723 * Called on the main thread of the process to report that the current data network
2724 * has become active, and it is now a good time to perform any pending network
2725 * operations. Note that this listener only tells you when the network becomes
2726 * active; if at any other time you want to know whether it is active (and thus okay
2727 * to initiate network traffic), you can retrieve its instantaneous state with
2728 * {@link ConnectivityManager#isDefaultNetworkActive}.
2729 */
2730 void onNetworkActive();
2731 }
2732
Chiachang Wang2de41682021-09-23 10:46:03 +08002733 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002734 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2735 mNetworkActivityListeners = new ArrayMap<>();
2736
2737 /**
2738 * Start listening to reports when the system's default data network is active, meaning it is
2739 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2740 * to determine the current state of the system's default network after registering the
2741 * listener.
2742 * <p>
2743 * If the process default network has been set with
2744 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2745 * reflect the process's default, but the system default.
2746 *
2747 * @param l The listener to be told when the network is active.
2748 */
2749 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002750 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002751 @Override
2752 public void onNetworkActive() throws RemoteException {
2753 l.onNetworkActive();
2754 }
2755 };
2756
Chiachang Wang2de41682021-09-23 10:46:03 +08002757 synchronized (mNetworkActivityListeners) {
2758 try {
2759 mService.registerNetworkActivityListener(rl);
2760 mNetworkActivityListeners.put(l, rl);
2761 } catch (RemoteException e) {
2762 throw e.rethrowFromSystemServer();
2763 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002764 }
2765 }
2766
2767 /**
2768 * Remove network active listener previously registered with
2769 * {@link #addDefaultNetworkActiveListener}.
2770 *
2771 * @param l Previously registered listener.
2772 */
2773 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002774 synchronized (mNetworkActivityListeners) {
2775 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2776 if (rl == null) {
2777 throw new IllegalArgumentException("Listener was not registered.");
2778 }
2779 try {
2780 mService.unregisterNetworkActivityListener(rl);
2781 mNetworkActivityListeners.remove(l);
2782 } catch (RemoteException e) {
2783 throw e.rethrowFromSystemServer();
2784 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002785 }
2786 }
2787
2788 /**
2789 * Return whether the data network is currently active. An active network means that
2790 * it is currently in a high power state for performing data transmission. On some
2791 * types of networks, it may be expensive to move and stay in such a state, so it is
2792 * more power efficient to batch network traffic together when the radio is already in
2793 * this state. This method tells you whether right now is currently a good time to
2794 * initiate network traffic, as the network is already active.
2795 */
2796 public boolean isDefaultNetworkActive() {
2797 try {
lucaslin709eb842021-01-21 02:04:15 +08002798 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002799 } catch (RemoteException e) {
2800 throw e.rethrowFromSystemServer();
2801 }
2802 }
2803
2804 /**
2805 * {@hide}
2806 */
2807 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002808 this(context, service, true /* newStatic */);
2809 }
2810
2811 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002812 mContext = Objects.requireNonNull(context, "missing context");
2813 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002814 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2815 // different ConnectivityManager, but that's still OK considering its usage.
2816 if (sInstance == null && newStatic) {
2817 final Context appContext = mContext.getApplicationContext();
2818 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2819 // If the application context is null, we're either in the system process or
2820 // it's the application context very early in app initialization. In both these
2821 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2822 // service. http://b/27532714 .
2823 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2824 false /* newStatic */);
2825 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002826 }
2827
2828 /** {@hide} */
2829 @UnsupportedAppUsage
2830 public static ConnectivityManager from(Context context) {
2831 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2832 }
2833
2834 /** @hide */
2835 public NetworkRequest getDefaultRequest() {
2836 try {
2837 // This is not racy as the default request is final in ConnectivityService.
2838 return mService.getDefaultRequest();
2839 } catch (RemoteException e) {
2840 throw e.rethrowFromSystemServer();
2841 }
2842 }
2843
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002844 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002845 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002846 * happened.
2847 *
2848 * @return {@code true} iff the package is allowed to write settings.
2849 */
2850 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2851 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2852 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2853 boolean throwException) {
2854 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002855 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002856 }
2857
2858 /**
2859 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2860 * situations where a Context pointer is unavailable.
2861 * @hide
2862 */
2863 @Deprecated
2864 static ConnectivityManager getInstanceOrNull() {
2865 return sInstance;
2866 }
2867
2868 /**
2869 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2870 * situations where a Context pointer is unavailable.
2871 * @hide
2872 */
2873 @Deprecated
2874 @UnsupportedAppUsage
2875 private static ConnectivityManager getInstance() {
2876 if (getInstanceOrNull() == null) {
2877 throw new IllegalStateException("No ConnectivityManager yet constructed");
2878 }
2879 return getInstanceOrNull();
2880 }
2881
2882 /**
2883 * Get the set of tetherable, available interfaces. This list is limited by
2884 * device configuration and current interface existence.
2885 *
2886 * @return an array of 0 or more Strings of tetherable interface names.
2887 *
2888 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2889 * {@hide}
2890 */
2891 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2892 @UnsupportedAppUsage
2893 @Deprecated
2894 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002895 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002896 }
2897
2898 /**
2899 * Get the set of tethered interfaces.
2900 *
2901 * @return an array of 0 or more String of currently tethered interface names.
2902 *
2903 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2904 * {@hide}
2905 */
2906 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2907 @UnsupportedAppUsage
2908 @Deprecated
2909 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002910 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002911 }
2912
2913 /**
2914 * Get the set of interface names which attempted to tether but
2915 * failed. Re-attempting to tether may cause them to reset to the Tethered
2916 * state. Alternatively, causing the interface to be destroyed and recreated
2917 * may cause them to reset to the available state.
2918 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2919 * information on the cause of the errors.
2920 *
2921 * @return an array of 0 or more String indicating the interface names
2922 * which failed to tether.
2923 *
2924 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2925 * {@hide}
2926 */
2927 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2928 @UnsupportedAppUsage
2929 @Deprecated
2930 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002931 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002932 }
2933
2934 /**
2935 * Get the set of tethered dhcp ranges.
2936 *
2937 * @deprecated This method is not supported.
2938 * TODO: remove this function when all of clients are removed.
2939 * {@hide}
2940 */
2941 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2942 @Deprecated
2943 public String[] getTetheredDhcpRanges() {
2944 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2945 }
2946
2947 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002948 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002949 * on the interface, forward and NAT IP packets and forward DNS requests
2950 * to the best active upstream network interface. Note that if no upstream
2951 * IP network interface is available, dhcp will still run and traffic will be
2952 * allowed between the tethered devices and this device, though upstream net
2953 * access will of course fail until an upstream network interface becomes
2954 * active.
2955 *
2956 * <p>This method requires the caller to hold either the
2957 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2958 * or the ability to modify system settings as determined by
2959 * {@link android.provider.Settings.System#canWrite}.</p>
2960 *
2961 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2962 * and WifiStateMachine which need direct access. All other clients should use
2963 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2964 * logic.</p>
2965 *
2966 * @param iface the interface name to tether.
2967 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2968 * @deprecated Use {@link TetheringManager#startTethering} instead
2969 *
2970 * {@hide}
2971 */
2972 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2973 @Deprecated
2974 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002975 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002976 }
2977
2978 /**
2979 * Stop tethering the named interface.
2980 *
2981 * <p>This method requires the caller to hold either the
2982 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2983 * or the ability to modify system settings as determined by
2984 * {@link android.provider.Settings.System#canWrite}.</p>
2985 *
2986 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2987 * and WifiStateMachine which need direct access. All other clients should use
2988 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2989 * logic.</p>
2990 *
2991 * @param iface the interface name to untether.
2992 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2993 *
2994 * {@hide}
2995 */
2996 @UnsupportedAppUsage
2997 @Deprecated
2998 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002999 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003000 }
3001
3002 /**
3003 * Check if the device allows for tethering. It may be disabled via
3004 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
3005 * due to device configuration.
3006 *
3007 * <p>If this app does not have permission to use this API, it will always
3008 * return false rather than throw an exception.</p>
3009 *
3010 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
3011 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
3012 *
3013 * <p>Otherwise, this method requires the caller to hold the ability to modify system
3014 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
3015 *
3016 * @return a boolean - {@code true} indicating Tethering is supported.
3017 *
3018 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
3019 * {@hide}
3020 */
3021 @SystemApi
3022 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
3023 android.Manifest.permission.WRITE_SETTINGS})
3024 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003025 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003026 }
3027
3028 /**
3029 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
3030 *
3031 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
3032 * @hide
3033 */
3034 @SystemApi
3035 @Deprecated
3036 public static abstract class OnStartTetheringCallback {
3037 /**
3038 * Called when tethering has been successfully started.
3039 */
3040 public void onTetheringStarted() {}
3041
3042 /**
3043 * Called when starting tethering failed.
3044 */
3045 public void onTetheringFailed() {}
3046 }
3047
3048 /**
3049 * Convenient overload for
3050 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
3051 * handler to run on the current thread's {@link Looper}.
3052 *
3053 * @deprecated Use {@link TetheringManager#startTethering} instead.
3054 * @hide
3055 */
3056 @SystemApi
3057 @Deprecated
3058 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3059 public void startTethering(int type, boolean showProvisioningUi,
3060 final OnStartTetheringCallback callback) {
3061 startTethering(type, showProvisioningUi, callback, null);
3062 }
3063
3064 /**
3065 * Runs tether provisioning for the given type if needed and then starts tethering if
3066 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
3067 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
3068 * schedules tether provisioning re-checks if appropriate.
3069 *
3070 * @param type The type of tethering to start. Must be one of
3071 * {@link ConnectivityManager.TETHERING_WIFI},
3072 * {@link ConnectivityManager.TETHERING_USB}, or
3073 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3074 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
3075 * is one. This should be true the first time this function is called and also any time
3076 * the user can see this UI. It gives users information from their carrier about the
3077 * check failing and how they can sign up for tethering if possible.
3078 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
3079 * of the result of trying to tether.
3080 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3081 *
3082 * @deprecated Use {@link TetheringManager#startTethering} instead.
3083 * @hide
3084 */
3085 @SystemApi
3086 @Deprecated
3087 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3088 public void startTethering(int type, boolean showProvisioningUi,
3089 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003090 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003091
3092 final Executor executor = new Executor() {
3093 @Override
3094 public void execute(Runnable command) {
3095 if (handler == null) {
3096 command.run();
3097 } else {
3098 handler.post(command);
3099 }
3100 }
3101 };
3102
3103 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
3104 @Override
3105 public void onTetheringStarted() {
3106 callback.onTetheringStarted();
3107 }
3108
3109 @Override
3110 public void onTetheringFailed(final int error) {
3111 callback.onTetheringFailed();
3112 }
3113 };
3114
3115 final TetheringRequest request = new TetheringRequest.Builder(type)
3116 .setShouldShowEntitlementUi(showProvisioningUi).build();
3117
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003118 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003119 }
3120
3121 /**
3122 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
3123 * applicable.
3124 *
3125 * @param type The type of tethering to stop. Must be one of
3126 * {@link ConnectivityManager.TETHERING_WIFI},
3127 * {@link ConnectivityManager.TETHERING_USB}, or
3128 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3129 *
3130 * @deprecated Use {@link TetheringManager#stopTethering} instead.
3131 * @hide
3132 */
3133 @SystemApi
3134 @Deprecated
3135 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3136 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003137 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003138 }
3139
3140 /**
3141 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
3142 * upstream status.
3143 *
3144 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
3145 * @hide
3146 */
3147 @SystemApi
3148 @Deprecated
3149 public abstract static class OnTetheringEventCallback {
3150
3151 /**
3152 * Called when tethering upstream changed. This can be called multiple times and can be
3153 * called any time.
3154 *
3155 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
3156 * have any upstream.
3157 */
3158 public void onUpstreamChanged(@Nullable Network network) {}
3159 }
3160
3161 @GuardedBy("mTetheringEventCallbacks")
3162 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
3163 mTetheringEventCallbacks = new ArrayMap<>();
3164
3165 /**
3166 * Start listening to tethering change events. Any new added callback will receive the last
3167 * tethering status right away. If callback is registered when tethering has no upstream or
3168 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3169 * with a null argument. The same callback object cannot be registered twice.
3170 *
3171 * @param executor the executor on which callback will be invoked.
3172 * @param callback the callback to be called when tethering has change events.
3173 *
3174 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3175 * @hide
3176 */
3177 @SystemApi
3178 @Deprecated
3179 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3180 public void registerTetheringEventCallback(
3181 @NonNull @CallbackExecutor Executor executor,
3182 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003183 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003184
3185 final TetheringEventCallback tetherCallback =
3186 new TetheringEventCallback() {
3187 @Override
3188 public void onUpstreamChanged(@Nullable Network network) {
3189 callback.onUpstreamChanged(network);
3190 }
3191 };
3192
3193 synchronized (mTetheringEventCallbacks) {
3194 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003195 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003196 }
3197 }
3198
3199 /**
3200 * Remove tethering event callback previously registered with
3201 * {@link #registerTetheringEventCallback}.
3202 *
3203 * @param callback previously registered callback.
3204 *
3205 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3206 * @hide
3207 */
3208 @SystemApi
3209 @Deprecated
3210 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3211 public void unregisterTetheringEventCallback(
3212 @NonNull final OnTetheringEventCallback callback) {
3213 Objects.requireNonNull(callback, "The callback must be non-null");
3214 synchronized (mTetheringEventCallbacks) {
3215 final TetheringEventCallback tetherCallback =
3216 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003217 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003218 }
3219 }
3220
3221
3222 /**
3223 * Get the list of regular expressions that define any tetherable
3224 * USB network interfaces. If USB tethering is not supported by the
3225 * device, this list should be empty.
3226 *
3227 * @return an array of 0 or more regular expression Strings defining
3228 * what interfaces are considered tetherable usb interfaces.
3229 *
3230 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3231 * {@hide}
3232 */
3233 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3234 @UnsupportedAppUsage
3235 @Deprecated
3236 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003237 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003238 }
3239
3240 /**
3241 * Get the list of regular expressions that define any tetherable
3242 * Wifi network interfaces. If Wifi tethering is not supported by the
3243 * device, this list should be empty.
3244 *
3245 * @return an array of 0 or more regular expression Strings defining
3246 * what interfaces are considered tetherable wifi interfaces.
3247 *
3248 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3249 * {@hide}
3250 */
3251 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3252 @UnsupportedAppUsage
3253 @Deprecated
3254 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003255 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003256 }
3257
3258 /**
3259 * Get the list of regular expressions that define any tetherable
3260 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3261 * device, this list should be empty.
3262 *
3263 * @return an array of 0 or more regular expression Strings defining
3264 * what interfaces are considered tetherable bluetooth interfaces.
3265 *
3266 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3267 *TetheringManager.TetheringInterfaceRegexps)} instead.
3268 * {@hide}
3269 */
3270 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3271 @UnsupportedAppUsage
3272 @Deprecated
3273 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003274 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003275 }
3276
3277 /**
3278 * Attempt to both alter the mode of USB and Tethering of USB. A
3279 * utility method to deal with some of the complexity of USB - will
3280 * attempt to switch to Rndis and subsequently tether the resulting
3281 * interface on {@code true} or turn off tethering and switch off
3282 * Rndis on {@code false}.
3283 *
3284 * <p>This method requires the caller to hold either the
3285 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3286 * or the ability to modify system settings as determined by
3287 * {@link android.provider.Settings.System#canWrite}.</p>
3288 *
3289 * @param enable a boolean - {@code true} to enable tethering
3290 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3291 * @deprecated Use {@link TetheringManager#startTethering} instead
3292 *
3293 * {@hide}
3294 */
3295 @UnsupportedAppUsage
3296 @Deprecated
3297 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003298 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003299 }
3300
3301 /**
3302 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3303 * {@hide}
3304 */
3305 @SystemApi
3306 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003307 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003308 /**
3309 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3310 * {@hide}
3311 */
3312 @Deprecated
3313 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3314 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3315 /**
3316 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3317 * {@hide}
3318 */
3319 @Deprecated
3320 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3321 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3322 /**
3323 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3324 * {@hide}
3325 */
3326 @Deprecated
3327 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3328 /**
3329 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3330 * {@hide}
3331 */
3332 @Deprecated
3333 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3334 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3335 /**
3336 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3337 * {@hide}
3338 */
3339 @Deprecated
3340 public static final int TETHER_ERROR_MASTER_ERROR =
3341 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3342 /**
3343 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3344 * {@hide}
3345 */
3346 @Deprecated
3347 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3348 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3349 /**
3350 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3351 * {@hide}
3352 */
3353 @Deprecated
3354 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3355 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3356 /**
3357 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3358 * {@hide}
3359 */
3360 @Deprecated
3361 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3362 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3363 /**
3364 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3365 * {@hide}
3366 */
3367 @Deprecated
3368 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3369 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3370 /**
3371 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3372 * {@hide}
3373 */
3374 @Deprecated
3375 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3376 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3377 /**
3378 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3379 * {@hide}
3380 */
3381 @SystemApi
3382 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003383 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003384 /**
3385 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3386 * {@hide}
3387 */
3388 @Deprecated
3389 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3390 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3391 /**
3392 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3393 * {@hide}
3394 */
3395 @SystemApi
3396 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003397 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003398
3399 /**
3400 * Get a more detailed error code after a Tethering or Untethering
3401 * request asynchronously failed.
3402 *
3403 * @param iface The name of the interface of interest
3404 * @return error The error code of the last error tethering or untethering the named
3405 * interface
3406 *
3407 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3408 * {@hide}
3409 */
3410 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3411 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3412 @Deprecated
3413 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003414 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003415 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3416 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3417 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3418 // instead.
3419 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3420 }
3421 return error;
3422 }
3423
3424 /** @hide */
3425 @Retention(RetentionPolicy.SOURCE)
3426 @IntDef(value = {
3427 TETHER_ERROR_NO_ERROR,
3428 TETHER_ERROR_PROVISION_FAILED,
3429 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3430 })
3431 public @interface EntitlementResultCode {
3432 }
3433
3434 /**
3435 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3436 * entitlement succeeded.
3437 *
3438 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3439 * @hide
3440 */
3441 @SystemApi
3442 @Deprecated
3443 public interface OnTetheringEntitlementResultListener {
3444 /**
3445 * Called to notify entitlement result.
3446 *
3447 * @param resultCode an int value of entitlement result. It may be one of
3448 * {@link #TETHER_ERROR_NO_ERROR},
3449 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3450 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3451 */
3452 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3453 }
3454
3455 /**
3456 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003457 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3458 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003459 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003460 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003461 * any reason will update the cached value.
3462 *
3463 * @param type the downstream type of tethering. Must be one of
3464 * {@link #TETHERING_WIFI},
3465 * {@link #TETHERING_USB}, or
3466 * {@link #TETHERING_BLUETOOTH}.
3467 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3468 * @param executor the executor on which callback will be invoked.
3469 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3470 * notify the caller of the result of entitlement check. The listener may be called zero
3471 * or one time.
3472 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3473 * {@hide}
3474 */
3475 @SystemApi
3476 @Deprecated
3477 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3478 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3479 @NonNull @CallbackExecutor Executor executor,
3480 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003481 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003482 ResultReceiver wrappedListener = new ResultReceiver(null) {
3483 @Override
3484 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003485 final long token = Binder.clearCallingIdentity();
3486 try {
3487 executor.execute(() -> {
3488 listener.onTetheringEntitlementResult(resultCode);
3489 });
3490 } finally {
3491 Binder.restoreCallingIdentity(token);
3492 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003493 }
3494 };
3495
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003496 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003497 showEntitlementUi);
3498 }
3499
3500 /**
3501 * Report network connectivity status. This is currently used only
3502 * to alter status bar UI.
3503 * <p>This method requires the caller to hold the permission
3504 * {@link android.Manifest.permission#STATUS_BAR}.
3505 *
3506 * @param networkType The type of network you want to report on
3507 * @param percentage The quality of the connection 0 is bad, 100 is good
3508 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3509 * {@hide}
3510 */
3511 public void reportInetCondition(int networkType, int percentage) {
3512 printStackTrace();
3513 try {
3514 mService.reportInetCondition(networkType, percentage);
3515 } catch (RemoteException e) {
3516 throw e.rethrowFromSystemServer();
3517 }
3518 }
3519
3520 /**
3521 * Report a problem network to the framework. This provides a hint to the system
3522 * that there might be connectivity problems on this network and may cause
3523 * the framework to re-evaluate network connectivity and/or switch to another
3524 * network.
3525 *
3526 * @param network The {@link Network} the application was attempting to use
3527 * or {@code null} to indicate the current default network.
3528 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3529 * working and non-working connectivity.
3530 */
3531 @Deprecated
3532 public void reportBadNetwork(@Nullable Network network) {
3533 printStackTrace();
3534 try {
3535 // One of these will be ignored because it matches system's current state.
3536 // The other will trigger the necessary reevaluation.
3537 mService.reportNetworkConnectivity(network, true);
3538 mService.reportNetworkConnectivity(network, false);
3539 } catch (RemoteException e) {
3540 throw e.rethrowFromSystemServer();
3541 }
3542 }
3543
3544 /**
3545 * Report to the framework whether a network has working connectivity.
3546 * This provides a hint to the system that a particular network is providing
3547 * working connectivity or not. In response the framework may re-evaluate
3548 * the network's connectivity and might take further action thereafter.
3549 *
3550 * @param network The {@link Network} the application was attempting to use
3551 * or {@code null} to indicate the current default network.
3552 * @param hasConnectivity {@code true} if the application was able to successfully access the
3553 * Internet using {@code network} or {@code false} if not.
3554 */
3555 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3556 printStackTrace();
3557 try {
3558 mService.reportNetworkConnectivity(network, hasConnectivity);
3559 } catch (RemoteException e) {
3560 throw e.rethrowFromSystemServer();
3561 }
3562 }
3563
3564 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003565 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003566 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003567 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3568 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3569 * accessing any network, regardless of what the settings for that network are.
3570 *
3571 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3572 * proxy is likely to break networking on multiple networks. This method is only meant
3573 * for device policy clients looking to do general internal filtering or similar use cases.
3574 *
chiachangwang9473c592022-07-15 02:25:52 +00003575 * @see #getGlobalProxy
3576 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003577 *
3578 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3579 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003580 * @hide
3581 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003582 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003583 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003584 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003585 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003586 try {
3587 mService.setGlobalProxy(p);
3588 } catch (RemoteException e) {
3589 throw e.rethrowFromSystemServer();
3590 }
3591 }
3592
3593 /**
3594 * Retrieve any network-independent global HTTP proxy.
3595 *
3596 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3597 * if no global HTTP proxy is set.
3598 * @hide
3599 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003600 @SystemApi(client = MODULE_LIBRARIES)
3601 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003602 public ProxyInfo getGlobalProxy() {
3603 try {
3604 return mService.getGlobalProxy();
3605 } catch (RemoteException e) {
3606 throw e.rethrowFromSystemServer();
3607 }
3608 }
3609
3610 /**
3611 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3612 * network-specific HTTP proxy. If {@code network} is null, the
3613 * network-specific proxy returned is the proxy of the default active
3614 * network.
3615 *
3616 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3617 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3618 * or when {@code network} is {@code null},
3619 * the {@code ProxyInfo} for the default active network. Returns
3620 * {@code null} when no proxy applies or the caller doesn't have
3621 * permission to use {@code network}.
3622 * @hide
3623 */
3624 public ProxyInfo getProxyForNetwork(Network network) {
3625 try {
3626 return mService.getProxyForNetwork(network);
3627 } catch (RemoteException e) {
3628 throw e.rethrowFromSystemServer();
3629 }
3630 }
3631
3632 /**
3633 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3634 * otherwise if this process is bound to a {@link Network} using
3635 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3636 * the default network's proxy is returned.
3637 *
3638 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3639 * HTTP proxy is active.
3640 */
3641 @Nullable
3642 public ProxyInfo getDefaultProxy() {
3643 return getProxyForNetwork(getBoundNetworkForProcess());
3644 }
3645
3646 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003647 * Returns whether the hardware supports the given network type.
3648 *
3649 * This doesn't indicate there is coverage or such a network is available, just whether the
3650 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3651 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003652 *
3653 * @param networkType The network type we'd like to check
3654 * @return {@code true} if supported, else {@code false}
3655 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3656 * @hide
3657 */
3658 @Deprecated
3659 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3660 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3661 public boolean isNetworkSupported(int networkType) {
3662 try {
3663 return mService.isNetworkSupported(networkType);
3664 } catch (RemoteException e) {
3665 throw e.rethrowFromSystemServer();
3666 }
3667 }
3668
3669 /**
3670 * Returns if the currently active data network is metered. A network is
3671 * classified as metered when the user is sensitive to heavy data usage on
3672 * that connection due to monetary costs, data limitations or
3673 * battery/performance issues. You should check this before doing large
3674 * data transfers, and warn the user or delay the operation until another
3675 * network is available.
3676 *
3677 * @return {@code true} if large transfers should be avoided, otherwise
3678 * {@code false}.
3679 */
3680 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3681 public boolean isActiveNetworkMetered() {
3682 try {
3683 return mService.isActiveNetworkMetered();
3684 } catch (RemoteException e) {
3685 throw e.rethrowFromSystemServer();
3686 }
3687 }
3688
3689 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003690 * Set sign in error notification to visible or invisible
3691 *
3692 * @hide
3693 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3694 */
3695 @Deprecated
3696 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3697 String action) {
3698 try {
3699 mService.setProvisioningNotificationVisible(visible, networkType, action);
3700 } catch (RemoteException e) {
3701 throw e.rethrowFromSystemServer();
3702 }
3703 }
3704
3705 /**
3706 * Set the value for enabling/disabling airplane mode
3707 *
3708 * @param enable whether to enable airplane mode or not
3709 *
3710 * @hide
3711 */
3712 @RequiresPermission(anyOf = {
3713 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3714 android.Manifest.permission.NETWORK_SETTINGS,
3715 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3716 android.Manifest.permission.NETWORK_STACK})
3717 @SystemApi
3718 public void setAirplaneMode(boolean enable) {
3719 try {
3720 mService.setAirplaneMode(enable);
3721 } catch (RemoteException e) {
3722 throw e.rethrowFromSystemServer();
3723 }
3724 }
3725
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003726 /**
3727 * Registers the specified {@link NetworkProvider}.
3728 * Each listener must only be registered once. The listener can be unregistered with
3729 * {@link #unregisterNetworkProvider}.
3730 *
3731 * @param provider the provider to register
3732 * @return the ID of the provider. This ID must be used by the provider when registering
3733 * {@link android.net.NetworkAgent}s.
3734 * @hide
3735 */
3736 @SystemApi
3737 @RequiresPermission(anyOf = {
3738 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3739 android.Manifest.permission.NETWORK_FACTORY})
3740 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3741 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3742 throw new IllegalStateException("NetworkProviders can only be registered once");
3743 }
3744
3745 try {
3746 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3747 provider.getName());
3748 provider.setProviderId(providerId);
3749 } catch (RemoteException e) {
3750 throw e.rethrowFromSystemServer();
3751 }
3752 return provider.getProviderId();
3753 }
3754
3755 /**
3756 * Unregisters the specified NetworkProvider.
3757 *
3758 * @param provider the provider to unregister
3759 * @hide
3760 */
3761 @SystemApi
3762 @RequiresPermission(anyOf = {
3763 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3764 android.Manifest.permission.NETWORK_FACTORY})
3765 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3766 try {
3767 mService.unregisterNetworkProvider(provider.getMessenger());
3768 } catch (RemoteException e) {
3769 throw e.rethrowFromSystemServer();
3770 }
3771 provider.setProviderId(NetworkProvider.ID_NONE);
3772 }
3773
Chalard Jeand1b498b2021-01-05 08:40:09 +09003774 /**
3775 * Register or update a network offer with ConnectivityService.
3776 *
3777 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003778 * them to networking requests made by apps or the system. A callback identifies an offer
3779 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3780 * score and the capabilities of the network it might be able to bring up ; these act as
3781 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003782 * provider.
3783 *
3784 * The provider is under no obligation to be able to bring up the network it offers at any
3785 * given time. Instead, this mechanism is meant to limit requests received by providers
3786 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3787 * the quality of the network satisfying a given request to their own offer.
3788 *
3789 * An offer can be updated by calling this again with the same callback object. This is
3790 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3791 * provider with the changes caused by the changes in the offer.
3792 *
3793 * @param provider The provider making this offer.
3794 * @param score The prospective score of the network.
3795 * @param caps The prospective capabilities of the network.
3796 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003797 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003798 */
3799 @RequiresPermission(anyOf = {
3800 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3801 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003802 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003803 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3804 @NonNull final INetworkOfferCallback callback) {
3805 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003806 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003807 Objects.requireNonNull(score, "null score"),
3808 Objects.requireNonNull(caps, "null caps"),
3809 Objects.requireNonNull(callback, "null callback"));
3810 } catch (RemoteException e) {
3811 throw e.rethrowFromSystemServer();
3812 }
3813 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003814
Chalard Jeand1b498b2021-01-05 08:40:09 +09003815 /**
3816 * Withdraw a network offer made with {@link #offerNetwork}.
3817 *
3818 * @param callback The callback passed at registration time. This must be the same object
3819 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003820 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003821 */
3822 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3823 try {
3824 mService.unofferNetwork(Objects.requireNonNull(callback));
3825 } catch (RemoteException e) {
3826 throw e.rethrowFromSystemServer();
3827 }
3828 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003829 /** @hide exposed via the NetworkProvider class. */
3830 @RequiresPermission(anyOf = {
3831 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3832 android.Manifest.permission.NETWORK_FACTORY})
3833 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3834 try {
3835 mService.declareNetworkRequestUnfulfillable(request);
3836 } catch (RemoteException e) {
3837 throw e.rethrowFromSystemServer();
3838 }
3839 }
3840
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003841 /**
3842 * @hide
3843 * Register a NetworkAgent with ConnectivityService.
3844 * @return Network corresponding to NetworkAgent.
3845 */
3846 @RequiresPermission(anyOf = {
3847 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3848 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003849 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3850 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3851 @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId) {
3852 return registerNetworkAgent(na, ni, lp, nc, null /* localNetworkConfig */, score, config,
3853 providerId);
3854 }
3855
3856 /**
3857 * @hide
3858 * Register a NetworkAgent with ConnectivityService.
3859 * @return Network corresponding to NetworkAgent.
3860 */
3861 @RequiresPermission(anyOf = {
3862 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3863 android.Manifest.permission.NETWORK_FACTORY})
3864 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3865 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3866 @Nullable LocalNetworkConfig localNetworkConfig, @NonNull NetworkScore score,
3867 @NonNull NetworkAgentConfig config, int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003868 try {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003869 return mService.registerNetworkAgent(na, ni, lp, nc, score, localNetworkConfig, config,
3870 providerId);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003871 } catch (RemoteException e) {
3872 throw e.rethrowFromSystemServer();
3873 }
3874 }
3875
3876 /**
3877 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3878 * changes. Should be extended by applications wanting notifications.
3879 *
3880 * A {@code NetworkCallback} is registered by calling
3881 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3882 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3883 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3884 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3885 * A {@code NetworkCallback} should be registered at most once at any time.
3886 * A {@code NetworkCallback} that has been unregistered can be registered again.
3887 */
3888 public static class NetworkCallback {
3889 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003890 * No flags associated with this callback.
3891 * @hide
3892 */
3893 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003894
Roshan Piuse08bc182020-12-22 15:10:42 -08003895 /**
lucaslinc582d502022-01-27 09:07:00 +08003896 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3897 *
3898 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3899 * Prior to Android 12, this information is always returned to apps holding the appropriate
3900 * permission, possibly noting that the app has used location.
3901 * <p>In Android 12 and above, by default the sent objects do not contain any location
3902 * information, even if the app holds the necessary permissions, and the system does not
3903 * take note of location usage by the app. Apps can request that location information is
3904 * included, in which case the system will check location permission and the location
3905 * toggle state, and take note of location usage by the app if any such information is
3906 * returned.
3907 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003908 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3909 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3910 * <p>
3911 * These include:
3912 * <li> Some transport info instances (retrieved via
3913 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3914 * contain location sensitive information.
3915 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003916 * sensitive for wifi suggestor apps (i.e using
3917 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003918 * </p>
3919 * <p>
3920 * Note:
3921 * <li> Retrieving this location sensitive information (subject to app's location
3922 * permissions) will be noted by system. </li>
3923 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003924 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003925 */
Roshan Pius189d0092021-03-11 21:16:44 -08003926 // Note: Some existing fields which are location sensitive may still be included without
3927 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003928 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3929
3930 /** @hide */
3931 @Retention(RetentionPolicy.SOURCE)
3932 @IntDef(flag = true, prefix = "FLAG_", value = {
3933 FLAG_NONE,
3934 FLAG_INCLUDE_LOCATION_INFO
3935 })
3936 public @interface Flag { }
3937
3938 /**
3939 * All the valid flags for error checking.
3940 */
3941 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3942
3943 public NetworkCallback() {
3944 this(FLAG_NONE);
3945 }
3946
3947 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003948 if ((flags & VALID_FLAGS) != flags) {
3949 throw new IllegalArgumentException("Invalid flags");
3950 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003951 mFlags = flags;
3952 }
3953
3954 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003955 * Called when the framework connects to a new network to evaluate whether it satisfies this
3956 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3957 * callback. There is no guarantee that this new network will satisfy any requests, or that
3958 * the network will stay connected for longer than the time necessary to evaluate it.
3959 * <p>
3960 * Most applications <b>should not</b> act on this callback, and should instead use
3961 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3962 * the framework in properly evaluating the network &mdash; for example, an application that
3963 * can automatically log in to a captive portal without user intervention.
3964 *
3965 * @param network The {@link Network} of the network that is being evaluated.
3966 *
3967 * @hide
3968 */
3969 public void onPreCheck(@NonNull Network network) {}
3970
3971 /**
3972 * Called when the framework connects and has declared a new network ready for use.
3973 * This callback may be called more than once if the {@link Network} that is
3974 * satisfying the request changes.
3975 *
3976 * @param network The {@link Network} of the satisfying network.
3977 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3978 * @param linkProperties The {@link LinkProperties} of the satisfying network.
Chalard Jean22350c92023-10-07 19:21:45 +09003979 * @param localInfo The {@link LocalNetworkInfo} of the satisfying network, or null
3980 * if this network is not a local network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003981 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3982 * @hide
3983 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003984 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003985 @NonNull NetworkCapabilities networkCapabilities,
Chalard Jean22350c92023-10-07 19:21:45 +09003986 @NonNull LinkProperties linkProperties,
3987 @Nullable LocalNetworkInfo localInfo,
3988 @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003989 // Internally only this method is called when a new network is available, and
3990 // it calls the callback in the same way and order that older versions used
3991 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003992 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
Chalard Jean22350c92023-10-07 19:21:45 +09003993 if (null != localInfo) onLocalNetworkInfoChanged(network, localInfo);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003994 onBlockedStatusChanged(network, blocked);
3995 }
3996
3997 /**
3998 * Legacy variant of onAvailable that takes a boolean blocked reason.
3999 *
4000 * This method has never been public API, but it's not final, so there may be apps that
4001 * implemented it and rely on it being called. Do our best not to break them.
4002 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
4003 * this method is called. There does not seem to be a way to avoid this.
4004 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
4005 *
4006 * @hide
4007 */
4008 public void onAvailable(@NonNull Network network,
4009 @NonNull NetworkCapabilities networkCapabilities,
Chalard Jean22350c92023-10-07 19:21:45 +09004010 @NonNull LinkProperties linkProperties,
4011 boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004012 onAvailable(network);
4013 if (!networkCapabilities.hasCapability(
4014 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
4015 onNetworkSuspended(network);
4016 }
4017 onCapabilitiesChanged(network, networkCapabilities);
4018 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004019 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004020 }
4021
4022 /**
4023 * Called when the framework connects and has declared a new network ready for use.
4024 *
4025 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
4026 * be available at the same time, and onAvailable will be called for each of these as they
4027 * appear.
4028 *
4029 * <p>For callbacks registered with {@link #requestNetwork} and
4030 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
4031 * is the new best network for this request and is now tracked by this callback ; this
4032 * callback will no longer receive method calls about other networks that may have been
4033 * passed to this method previously. The previously-best network may have disconnected, or
4034 * it may still be around and the newly-best network may simply be better.
4035 *
4036 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
4037 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
4038 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
4039 * to {@link #onBlockedStatusChanged(Network, boolean)}.
4040 *
4041 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4042 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4043 * this callback as this is prone to race conditions (there is no guarantee the objects
4044 * returned by these methods will be current). Instead, wait for a call to
4045 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
4046 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
4047 * to be well-ordered with respect to other callbacks.
4048 *
4049 * @param network The {@link Network} of the satisfying network.
4050 */
4051 public void onAvailable(@NonNull Network network) {}
4052
4053 /**
4054 * Called when the network is about to be lost, typically because there are no outstanding
4055 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
4056 * with the new replacement network for graceful handover. This method is not guaranteed
4057 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
4058 * network is suddenly disconnected.
4059 *
4060 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4061 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4062 * this callback as this is prone to race conditions ; calling these methods while in a
4063 * callback may return an outdated or even a null object.
4064 *
4065 * @param network The {@link Network} that is about to be lost.
4066 * @param maxMsToLive The time in milliseconds the system intends to keep the network
4067 * connected for graceful handover; note that the network may still
4068 * suffer a hard loss at any time.
4069 */
4070 public void onLosing(@NonNull Network network, int maxMsToLive) {}
4071
4072 /**
4073 * Called when a network disconnects or otherwise no longer satisfies this request or
4074 * callback.
4075 *
4076 * <p>If the callback was registered with requestNetwork() or
4077 * registerDefaultNetworkCallback(), it will only be invoked against the last network
4078 * returned by onAvailable() when that network is lost and no other network satisfies
4079 * the criteria of the request.
4080 *
4081 * <p>If the callback was registered with registerNetworkCallback() it will be called for
4082 * each network which no longer satisfies the criteria of the callback.
4083 *
4084 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4085 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4086 * this callback as this is prone to race conditions ; calling these methods while in a
4087 * callback may return an outdated or even a null object.
4088 *
4089 * @param network The {@link Network} lost.
4090 */
4091 public void onLost(@NonNull Network network) {}
4092
4093 /**
4094 * Called if no network is found within the timeout time specified in
4095 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
4096 * requested network request cannot be fulfilled (whether or not a timeout was
4097 * specified). When this callback is invoked the associated
4098 * {@link NetworkRequest} will have already been removed and released, as if
4099 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
4100 */
4101 public void onUnavailable() {}
4102
4103 /**
4104 * Called when the network corresponding to this request changes capabilities but still
4105 * satisfies the requested criteria.
4106 *
4107 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4108 * to be called immediately after {@link #onAvailable}.
4109 *
4110 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
4111 * ConnectivityManager methods in this callback as this is prone to race conditions :
4112 * calling these methods while in a callback may return an outdated or even a null object.
4113 *
4114 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08004115 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004116 * network.
4117 */
4118 public void onCapabilitiesChanged(@NonNull Network network,
4119 @NonNull NetworkCapabilities networkCapabilities) {}
4120
4121 /**
4122 * Called when the network corresponding to this request changes {@link LinkProperties}.
4123 *
4124 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4125 * to be called immediately after {@link #onAvailable}.
4126 *
4127 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
4128 * ConnectivityManager methods in this callback as this is prone to race conditions :
4129 * calling these methods while in a callback may return an outdated or even a null object.
4130 *
4131 * @param network The {@link Network} whose link properties have changed.
4132 * @param linkProperties The new {@link LinkProperties} for this network.
4133 */
4134 public void onLinkPropertiesChanged(@NonNull Network network,
4135 @NonNull LinkProperties linkProperties) {}
4136
4137 /**
Chalard Jean22350c92023-10-07 19:21:45 +09004138 * Called when there is a change in the {@link LocalNetworkInfo} for this network.
4139 *
4140 * This is only called for local networks, that is those with the
4141 * NET_CAPABILITY_LOCAL_NETWORK network capability.
4142 *
4143 * @param network the {@link Network} whose local network info has changed.
4144 * @param localNetworkInfo the new {@link LocalNetworkInfo} for this network.
4145 * @hide
4146 */
4147 public void onLocalNetworkInfoChanged(@NonNull Network network,
4148 @NonNull LocalNetworkInfo localNetworkInfo) {}
4149
4150 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004151 * Called when the network the framework connected to for this request suspends data
4152 * transmission temporarily.
4153 *
4154 * <p>This generally means that while the TCP connections are still live temporarily
4155 * network data fails to transfer. To give a specific example, this is used on cellular
4156 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4157 * means read operations on sockets on this network will block once the buffers are
4158 * drained, and write operations will block once the buffers are full.
4159 *
4160 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4161 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4162 * this callback as this is prone to race conditions (there is no guarantee the objects
4163 * returned by these methods will be current).
4164 *
4165 * @hide
4166 */
4167 public void onNetworkSuspended(@NonNull Network network) {}
4168
4169 /**
4170 * Called when the network the framework connected to for this request
4171 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4172 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4173
4174 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4175 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4176 * this callback as this is prone to race conditions : calling these methods while in a
4177 * callback may return an outdated or even a null object.
4178 *
4179 * @hide
4180 */
4181 public void onNetworkResumed(@NonNull Network network) {}
4182
4183 /**
4184 * Called when access to the specified network is blocked or unblocked.
4185 *
4186 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4187 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4188 * this callback as this is prone to race conditions : calling these methods while in a
4189 * callback may return an outdated or even a null object.
4190 *
4191 * @param network The {@link Network} whose blocked status has changed.
4192 * @param blocked The blocked status of this {@link Network}.
4193 */
4194 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4195
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004196 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004197 * Called when access to the specified network is blocked or unblocked, or the reason for
4198 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004199 *
4200 * If a NetworkCallback object implements this method,
4201 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4202 *
4203 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4204 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4205 * this callback as this is prone to race conditions : calling these methods while in a
4206 * callback may return an outdated or even a null object.
4207 *
4208 * @param network The {@link Network} whose blocked status has changed.
4209 * @param blocked The blocked status of this {@link Network}.
4210 * @hide
4211 */
4212 @SystemApi(client = MODULE_LIBRARIES)
4213 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4214 onBlockedStatusChanged(network, blocked != 0);
4215 }
4216
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004217 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004218 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004219 }
4220
4221 /**
4222 * Constant error codes used by ConnectivityService to communicate about failures and errors
4223 * across a Binder boundary.
4224 * @hide
4225 */
4226 public interface Errors {
4227 int TOO_MANY_REQUESTS = 1;
4228 }
4229
4230 /** @hide */
4231 public static class TooManyRequestsException extends RuntimeException {}
4232
4233 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4234 switch (e.errorCode) {
4235 case Errors.TOO_MANY_REQUESTS:
4236 return new TooManyRequestsException();
4237 default:
4238 Log.w(TAG, "Unknown service error code " + e.errorCode);
4239 return new RuntimeException(e);
4240 }
4241 }
4242
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004243 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004244 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004245 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004246 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004247 /** @hide arg1 = TTL */
Chalard Jean22350c92023-10-07 19:21:45 +09004248 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004249 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004250 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004251 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004252 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004253 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004254 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004255 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004256 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004257 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Chalard Jean22350c92023-10-07 19:21:45 +09004258 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004259 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004260 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004261 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004262 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004263 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004264 public static final int CALLBACK_BLK_CHANGED = 11;
4265 /** @hide */
4266 public static final int CALLBACK_LOCAL_NETWORK_INFO_CHANGED = 12;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004267
4268 /** @hide */
4269 public static String getCallbackName(int whichCallback) {
4270 switch (whichCallback) {
4271 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4272 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4273 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4274 case CALLBACK_LOST: return "CALLBACK_LOST";
4275 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4276 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4277 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4278 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4279 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4280 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4281 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Chalard Jean22350c92023-10-07 19:21:45 +09004282 case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: return "CALLBACK_LOCAL_NETWORK_INFO_CHANGED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004283 default:
4284 return Integer.toString(whichCallback);
4285 }
4286 }
4287
zhujiatai79b0de92022-09-22 15:44:02 +08004288 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004289 private static final String TAG = "ConnectivityManager.CallbackHandler";
4290 private static final boolean DBG = false;
4291
4292 CallbackHandler(Looper looper) {
4293 super(looper);
4294 }
4295
4296 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004297 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004298 }
4299
4300 @Override
4301 public void handleMessage(Message message) {
4302 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004303 // the sInstance can't be null because to send this message a ConnectivityManager
4304 // instance must have been created prior to creating the thread on which this
4305 // Handler is running.
4306 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004307 return;
4308 }
4309
4310 final NetworkRequest request = getObject(message, NetworkRequest.class);
4311 final Network network = getObject(message, Network.class);
4312 final NetworkCallback callback;
4313 synchronized (sCallbacks) {
4314 callback = sCallbacks.get(request);
4315 if (callback == null) {
4316 Log.w(TAG,
4317 "callback not found for " + getCallbackName(message.what) + " message");
4318 return;
4319 }
4320 if (message.what == CALLBACK_UNAVAIL) {
4321 sCallbacks.remove(request);
4322 callback.networkRequest = ALREADY_UNREGISTERED;
4323 }
4324 }
4325 if (DBG) {
4326 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4327 }
4328
4329 switch (message.what) {
4330 case CALLBACK_PRECHECK: {
4331 callback.onPreCheck(network);
4332 break;
4333 }
4334 case CALLBACK_AVAILABLE: {
4335 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4336 LinkProperties lp = getObject(message, LinkProperties.class);
Chalard Jean22350c92023-10-07 19:21:45 +09004337 LocalNetworkInfo lni = getObject(message, LocalNetworkInfo.class);
4338 callback.onAvailable(network, cap, lp, lni, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004339 break;
4340 }
4341 case CALLBACK_LOSING: {
4342 callback.onLosing(network, message.arg1);
4343 break;
4344 }
4345 case CALLBACK_LOST: {
4346 callback.onLost(network);
4347 break;
4348 }
4349 case CALLBACK_UNAVAIL: {
4350 callback.onUnavailable();
4351 break;
4352 }
4353 case CALLBACK_CAP_CHANGED: {
4354 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4355 callback.onCapabilitiesChanged(network, cap);
4356 break;
4357 }
4358 case CALLBACK_IP_CHANGED: {
4359 LinkProperties lp = getObject(message, LinkProperties.class);
4360 callback.onLinkPropertiesChanged(network, lp);
4361 break;
4362 }
Chalard Jean22350c92023-10-07 19:21:45 +09004363 case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
4364 final LocalNetworkInfo info = getObject(message, LocalNetworkInfo.class);
4365 callback.onLocalNetworkInfoChanged(network, info);
4366 break;
4367 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004368 case CALLBACK_SUSPENDED: {
4369 callback.onNetworkSuspended(network);
4370 break;
4371 }
4372 case CALLBACK_RESUMED: {
4373 callback.onNetworkResumed(network);
4374 break;
4375 }
4376 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004377 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004378 }
4379 }
4380 }
4381
4382 private <T> T getObject(Message msg, Class<T> c) {
4383 return (T) msg.getData().getParcelable(c.getSimpleName());
4384 }
4385 }
4386
4387 private CallbackHandler getDefaultHandler() {
4388 synchronized (sCallbacks) {
4389 if (sCallbackHandler == null) {
4390 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4391 }
4392 return sCallbackHandler;
4393 }
4394 }
4395
4396 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4397 private static CallbackHandler sCallbackHandler;
4398
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004399 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4400 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4401 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004402 printStackTrace();
4403 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004404 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4405 throw new IllegalArgumentException("null NetworkCapabilities");
4406 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004407 final NetworkRequest request;
4408 final String callingPackageName = mContext.getOpPackageName();
4409 try {
4410 synchronized(sCallbacks) {
4411 if (callback.networkRequest != null
4412 && callback.networkRequest != ALREADY_UNREGISTERED) {
4413 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4414 // and requests (http://b/20701525).
4415 Log.e(TAG, "NetworkCallback was already registered");
4416 }
4417 Messenger messenger = new Messenger(handler);
4418 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004419 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004420 if (reqType == LISTEN) {
4421 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004422 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004423 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004424 } else {
4425 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004426 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4427 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004428 }
4429 if (request != null) {
4430 sCallbacks.put(request, callback);
4431 }
4432 callback.networkRequest = request;
4433 }
4434 } catch (RemoteException e) {
4435 throw e.rethrowFromSystemServer();
4436 } catch (ServiceSpecificException e) {
4437 throw convertServiceException(e);
4438 }
4439 return request;
4440 }
4441
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004442 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4443 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4444 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4445 legacyType, handler);
4446 }
4447
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004448 /**
4449 * Helper function to request a network with a particular legacy type.
4450 *
4451 * This API is only for use in internal system code that requests networks with legacy type and
4452 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4453 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4454 *
4455 * @param request {@link NetworkRequest} describing this request.
4456 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4457 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4458 * be a positive value (i.e. >0).
4459 * @param legacyType to specify the network type(#TYPE_*).
4460 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4461 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4462 * the callback must not be shared - it uniquely specifies this request.
4463 *
4464 * @hide
4465 */
4466 @SystemApi
4467 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4468 public void requestNetwork(@NonNull NetworkRequest request,
4469 int timeoutMs, int legacyType, @NonNull Handler handler,
4470 @NonNull NetworkCallback networkCallback) {
4471 if (legacyType == TYPE_NONE) {
4472 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4473 }
4474 CallbackHandler cbHandler = new CallbackHandler(handler);
4475 NetworkCapabilities nc = request.networkCapabilities;
4476 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4477 }
4478
4479 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004480 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004481 *
4482 * <p>This method will attempt to find the best network that matches the passed
4483 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4484 * criteria. The platform will evaluate which network is the best at its own discretion.
4485 * Throughput, latency, cost per byte, policy, user preference and other considerations
4486 * may be factored in the decision of what is considered the best network.
4487 *
4488 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4489 * matching this request, while always attempting to match the request to a better network if
4490 * possible. If a better match is found, the platform will switch this request to the now-best
4491 * network and inform the app of the newly best network by invoking
4492 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4493 * will not try to maintain any other network than the best one currently matching the request:
4494 * a network not matching any network request may be disconnected at any time.
4495 *
4496 * <p>For example, an application could use this method to obtain a connected cellular network
4497 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4498 * radio to consume additional power. Or, an application could inform the system that it wants
4499 * a network supporting sending MMSes and have the system let it know about the currently best
4500 * MMS-supporting network through the provided {@link NetworkCallback}.
4501 *
4502 * <p>The status of the request can be followed by listening to the various callbacks described
4503 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4504 * used to direct traffic to the network (although accessing some networks may be subject to
4505 * holding specific permissions). Callers will learn about the specific characteristics of the
4506 * network through
4507 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4508 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4509 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4510 * matching the request at any given time; therefore when a better network matching the request
4511 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4512 * with the new network after which no further updates are given about the previously-best
4513 * network, unless it becomes the best again at some later time. All callbacks are invoked
4514 * in order on the same thread, which by default is a thread created by the framework running
4515 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004516 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004517 * callbacks are invoked.
4518 *
4519 * <p>This{@link NetworkRequest} will live until released via
4520 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4521 * which point the system may let go of the network at any time.
4522 *
4523 * <p>A version of this method which takes a timeout is
4524 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4525 * wait for a limited amount of time for the network to become unavailable.
4526 *
4527 * <p>It is presently unsupported to request a network with mutable
4528 * {@link NetworkCapabilities} such as
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>This method requires the caller to hold either the
4537 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4538 * or the ability to modify system settings as determined by
4539 * {@link android.provider.Settings.System#canWrite}.</p>
4540 *
4541 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4542 * number of outstanding requests to 100 per app (identified by their UID), shared with
4543 * all variants of this method, of {@link #registerNetworkCallback} as well as
4544 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4545 * Requesting a network with this method will count toward this limit. If this limit is
4546 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4547 * make sure to unregister the callbacks with
4548 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4549 *
4550 * @param request {@link NetworkRequest} describing this request.
4551 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4552 * the callback must not be shared - it uniquely specifies this request.
4553 * The callback is invoked on the default internal Handler.
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 NetworkCallback networkCallback) {
4560 requestNetwork(request, networkCallback, getDefaultHandler());
4561 }
4562
4563 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004564 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004565 *
4566 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4567 * but runs all the callbacks on the passed Handler.
4568 *
4569 * <p>This method has the same permission requirements as
4570 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4571 * and throws the same exceptions in the same conditions.
4572 *
4573 * @param request {@link NetworkRequest} describing this request.
4574 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4575 * the callback must not be shared - it uniquely specifies this request.
4576 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4577 */
4578 public void requestNetwork(@NonNull NetworkRequest request,
4579 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4580 CallbackHandler cbHandler = new CallbackHandler(handler);
4581 NetworkCapabilities nc = request.networkCapabilities;
4582 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4583 }
4584
4585 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004586 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004587 * by a timeout.
4588 *
4589 * This function behaves identically to the non-timed-out version
4590 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4591 * is not found within the given time (in milliseconds) the
4592 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4593 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4594 * not have to be released if timed-out (it is automatically released). Unregistering a
4595 * request that timed out is not an error.
4596 *
4597 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4598 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4599 * for that purpose. Calling this method will attempt to bring up the requested network.
4600 *
4601 * <p>This method has the same permission requirements as
4602 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4603 * and throws the same exceptions in the same conditions.
4604 *
4605 * @param request {@link NetworkRequest} describing this request.
4606 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4607 * the callback must not be shared - it uniquely specifies this request.
4608 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4609 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4610 * be a positive value (i.e. >0).
4611 */
4612 public void requestNetwork(@NonNull NetworkRequest request,
4613 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4614 checkTimeout(timeoutMs);
4615 NetworkCapabilities nc = request.networkCapabilities;
4616 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4617 getDefaultHandler());
4618 }
4619
4620 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004621 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004622 * by a timeout.
4623 *
4624 * This method behaves identically to
4625 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4626 * on the passed Handler.
4627 *
4628 * <p>This method has the same permission requirements as
4629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4630 * and throws the same exceptions in the same conditions.
4631 *
4632 * @param request {@link NetworkRequest} describing this request.
4633 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4634 * the callback must not be shared - it uniquely specifies this request.
4635 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4636 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4637 * before {@link NetworkCallback#onUnavailable} is called.
4638 */
4639 public void requestNetwork(@NonNull NetworkRequest request,
4640 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4641 checkTimeout(timeoutMs);
4642 CallbackHandler cbHandler = new CallbackHandler(handler);
4643 NetworkCapabilities nc = request.networkCapabilities;
4644 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4645 }
4646
4647 /**
4648 * The lookup key for a {@link Network} object included with the intent after
4649 * successfully finding a network for the applications request. Retrieve it with
4650 * {@link android.content.Intent#getParcelableExtra(String)}.
4651 * <p>
4652 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4653 * then you must get a ConnectivityManager instance before doing so.
4654 */
4655 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4656
4657 /**
4658 * The lookup key for a {@link NetworkRequest} object included with the intent after
4659 * successfully finding a network for the applications request. Retrieve it with
4660 * {@link android.content.Intent#getParcelableExtra(String)}.
4661 */
4662 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4663
4664
4665 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004666 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004667 *
4668 * This function behaves identically to the version that takes a NetworkCallback, but instead
4669 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4670 * the request may outlive the calling application and get called back when a suitable
4671 * network is found.
4672 * <p>
4673 * The operation is an Intent broadcast that goes to a broadcast receiver that
4674 * you registered with {@link Context#registerReceiver} or through the
4675 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4676 * <p>
4677 * The operation Intent is delivered with two extras, a {@link Network} typed
4678 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4679 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4680 * the original requests parameters. It is important to create a new,
4681 * {@link NetworkCallback} based request before completing the processing of the
4682 * Intent to reserve the network or it will be released shortly after the Intent
4683 * is processed.
4684 * <p>
4685 * If there is already a request for this Intent registered (with the equality of
4686 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4687 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4688 * <p>
4689 * The request may be released normally by calling
4690 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4691 * <p>It is presently unsupported to request a network with either
4692 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4693 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4694 * as these {@code NetworkCapabilities} represent states that a particular
4695 * network may never attain, and whether a network will attain these states
4696 * is unknown prior to bringing up the network so the framework does not
4697 * know how to go about satisfying a request with these capabilities.
4698 *
4699 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4700 * number of outstanding requests to 100 per app (identified by their UID), shared with
4701 * all variants of this method, of {@link #registerNetworkCallback} as well as
4702 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4703 * Requesting a network with this method will count toward this limit. If this limit is
4704 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4705 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4706 * or {@link #releaseNetworkRequest(PendingIntent)}.
4707 *
4708 * <p>This method requires the caller to hold either the
4709 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4710 * or the ability to modify system settings as determined by
4711 * {@link android.provider.Settings.System#canWrite}.</p>
4712 *
4713 * @param request {@link NetworkRequest} describing this request.
4714 * @param operation Action to perform when the network is available (corresponds
4715 * to the {@link NetworkCallback#onAvailable} call. Typically
4716 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4717 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4718 * @throws SecurityException if missing the appropriate permissions.
4719 * @throws RuntimeException if the app already has too many callbacks registered.
4720 */
4721 public void requestNetwork(@NonNull NetworkRequest request,
4722 @NonNull PendingIntent operation) {
4723 printStackTrace();
4724 checkPendingIntentNotNull(operation);
4725 try {
4726 mService.pendingRequestForNetwork(
4727 request.networkCapabilities, operation, mContext.getOpPackageName(),
4728 getAttributionTag());
4729 } catch (RemoteException e) {
4730 throw e.rethrowFromSystemServer();
4731 } catch (ServiceSpecificException e) {
4732 throw convertServiceException(e);
4733 }
4734 }
4735
4736 /**
4737 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4738 * <p>
4739 * This method has the same behavior as
4740 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4741 * releasing network resources and disconnecting.
4742 *
4743 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4744 * PendingIntent passed to
4745 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4746 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4747 */
4748 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4749 printStackTrace();
4750 checkPendingIntentNotNull(operation);
4751 try {
4752 mService.releasePendingNetworkRequest(operation);
4753 } catch (RemoteException e) {
4754 throw e.rethrowFromSystemServer();
4755 }
4756 }
4757
4758 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004759 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004760 }
4761
4762 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004763 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004764 }
4765
4766 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004767 if (timeoutMs <= 0) {
4768 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4769 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004770 }
4771
4772 /**
4773 * Registers to receive notifications about all networks which satisfy the given
4774 * {@link NetworkRequest}. The callbacks will continue to be called until
4775 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4776 * called.
4777 *
4778 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4779 * number of outstanding requests to 100 per app (identified by their UID), shared with
4780 * all variants of this method, of {@link #requestNetwork} as well as
4781 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4782 * Requesting a network with this method will count toward this limit. If this limit is
4783 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4784 * make sure to unregister the callbacks with
4785 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4786 *
4787 * @param request {@link NetworkRequest} describing this request.
4788 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4789 * networks change state.
4790 * The callback is invoked on the default internal Handler.
4791 * @throws RuntimeException if the app already has too many callbacks registered.
4792 */
4793 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4794 public void registerNetworkCallback(@NonNull NetworkRequest request,
4795 @NonNull NetworkCallback networkCallback) {
4796 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4797 }
4798
4799 /**
4800 * Registers to receive notifications about all networks which satisfy the given
4801 * {@link NetworkRequest}. The callbacks will continue to be called until
4802 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4803 * called.
4804 *
4805 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4806 * number of outstanding requests to 100 per app (identified by their UID), shared with
4807 * all variants of this method, of {@link #requestNetwork} as well as
4808 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4809 * Requesting a network with this method will count toward this limit. If this limit is
4810 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4811 * make sure to unregister the callbacks with
4812 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4813 *
4814 *
4815 * @param request {@link NetworkRequest} describing this request.
4816 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4817 * networks change state.
4818 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4819 * @throws RuntimeException if the app already has too many callbacks registered.
4820 */
4821 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4822 public void registerNetworkCallback(@NonNull NetworkRequest request,
4823 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4824 CallbackHandler cbHandler = new CallbackHandler(handler);
4825 NetworkCapabilities nc = request.networkCapabilities;
4826 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4827 }
4828
4829 /**
4830 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4831 * {@link NetworkRequest}.
4832 *
4833 * This function behaves identically to the version that takes a NetworkCallback, but instead
4834 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4835 * the request may outlive the calling application and get called back when a suitable
4836 * network is found.
4837 * <p>
4838 * The operation is an Intent broadcast that goes to a broadcast receiver that
4839 * you registered with {@link Context#registerReceiver} or through the
4840 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4841 * <p>
4842 * The operation Intent is delivered with two extras, a {@link Network} typed
4843 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4844 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4845 * the original requests parameters.
4846 * <p>
4847 * If there is already a request for this Intent registered (with the equality of
4848 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4849 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4850 * <p>
4851 * The request may be released normally by calling
4852 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4853 *
4854 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4855 * number of outstanding requests to 100 per app (identified by their UID), shared with
4856 * all variants of this method, of {@link #requestNetwork} as well as
4857 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4858 * Requesting a network with this method will count toward this limit. If this limit is
4859 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4860 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4861 * or {@link #releaseNetworkRequest(PendingIntent)}.
4862 *
4863 * @param request {@link NetworkRequest} describing this request.
4864 * @param operation Action to perform when the network is available (corresponds
4865 * to the {@link NetworkCallback#onAvailable} call. Typically
4866 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4867 * @throws RuntimeException if the app already has too many callbacks registered.
4868 */
4869 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4870 public void registerNetworkCallback(@NonNull NetworkRequest request,
4871 @NonNull PendingIntent operation) {
4872 printStackTrace();
4873 checkPendingIntentNotNull(operation);
4874 try {
4875 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004876 request.networkCapabilities, operation, mContext.getOpPackageName(),
4877 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004878 } catch (RemoteException e) {
4879 throw e.rethrowFromSystemServer();
4880 } catch (ServiceSpecificException e) {
4881 throw convertServiceException(e);
4882 }
4883 }
4884
4885 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004886 * Registers to receive notifications about changes in the application's default network. This
4887 * may be a physical network or a virtual network, such as a VPN that applies to the
4888 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004889 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4890 *
4891 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4892 * number of outstanding requests to 100 per app (identified by their UID), shared with
4893 * all variants of this method, of {@link #requestNetwork} as well as
4894 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4895 * Requesting a network with this method will count toward this limit. If this limit is
4896 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4897 * make sure to unregister the callbacks with
4898 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4899 *
4900 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004901 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004902 * The callback is invoked on the default internal Handler.
4903 * @throws RuntimeException if the app already has too many callbacks registered.
4904 */
4905 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4906 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4907 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4908 }
4909
4910 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004911 * Registers to receive notifications about changes in the application's default network. This
4912 * may be a physical network or a virtual network, such as a VPN that applies to the
4913 * application. The callbacks will continue to be called until either the application exits or
4914 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4915 *
4916 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4917 * number of outstanding requests to 100 per app (identified by their UID), shared with
4918 * all variants of this method, of {@link #requestNetwork} as well as
4919 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4920 * Requesting a network with this method will count toward this limit. If this limit is
4921 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4922 * make sure to unregister the callbacks with
4923 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4924 *
4925 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4926 * application's default network changes.
4927 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4928 * @throws RuntimeException if the app already has too many callbacks registered.
4929 */
4930 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4931 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4932 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004933 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004934 }
4935
4936 /**
4937 * Registers to receive notifications about changes in the default network for the specified
4938 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4939 * UID. The callbacks will continue to be called until either the application exits or
4940 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4941 *
4942 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4943 * number of outstanding requests to 100 per app (identified by their UID), shared with
4944 * all variants of this method, of {@link #requestNetwork} as well as
4945 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4946 * Requesting a network with this method will count toward this limit. If this limit is
4947 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4948 * make sure to unregister the callbacks with
4949 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4950 *
4951 * @param uid the UID for which to track default network changes.
4952 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4953 * UID's default network changes.
4954 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4955 * @throws RuntimeException if the app already has too many callbacks registered.
4956 * @hide
4957 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004958 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004959 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4960 @RequiresPermission(anyOf = {
4961 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4962 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004963 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004964 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004965 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004966 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004967 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4968 }
4969
4970 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004971 * Registers to receive notifications about changes in the system default network. The callbacks
4972 * will continue to be called until either the application exits or
4973 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4974 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004975 * This method should not be used to determine networking state seen by applications, because in
4976 * many cases, most or even all application traffic may not use the default network directly,
4977 * and traffic from different applications may go on different networks by default. As an
4978 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4979 * and not onto the system default network. Applications or system components desiring to do
4980 * determine network state as seen by applications should use other methods such as
4981 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4982 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004983 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4984 * number of outstanding requests to 100 per app (identified by their UID), shared with
4985 * all variants of this method, of {@link #requestNetwork} as well as
4986 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4987 * Requesting a network with this method will count toward this limit. If this limit is
4988 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4989 * make sure to unregister the callbacks with
4990 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4991 *
4992 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4993 * system default network changes.
4994 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4995 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004996 *
4997 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004998 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004999 @SystemApi(client = MODULE_LIBRARIES)
5000 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
5001 @RequiresPermission(anyOf = {
5002 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08005003 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00005004 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08005005 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09005006 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005007 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005008 CallbackHandler cbHandler = new CallbackHandler(handler);
5009 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09005010 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005011 }
5012
5013 /**
junyulaibd123062021-03-15 11:48:48 +08005014 * Registers to receive notifications about the best matching network which satisfy the given
5015 * {@link NetworkRequest}. The callbacks will continue to be called until
5016 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
5017 * called.
5018 *
5019 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5020 * number of outstanding requests to 100 per app (identified by their UID), shared with
5021 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
5022 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5023 * Requesting a network with this method will count toward this limit. If this limit is
5024 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5025 * make sure to unregister the callbacks with
5026 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5027 *
5028 *
5029 * @param request {@link NetworkRequest} describing this request.
5030 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
5031 * networks change state.
5032 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5033 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08005034 */
junyulai5a5c99b2021-03-05 15:51:17 +08005035 @SuppressLint("ExecutorRegistration")
5036 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
5037 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
5038 final NetworkCapabilities nc = request.networkCapabilities;
5039 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08005040 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08005041 }
5042
5043 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005044 * Requests bandwidth update for a given {@link Network} and returns whether the update request
5045 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
5046 * network connection for updated bandwidth information. The caller will be notified via
5047 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
5048 * method assumes that the caller has previously called
5049 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
5050 * changes.
5051 *
5052 * @param network {@link Network} specifying which network you're interested.
5053 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5054 */
5055 public boolean requestBandwidthUpdate(@NonNull Network network) {
5056 try {
5057 return mService.requestBandwidthUpdate(network);
5058 } catch (RemoteException e) {
5059 throw e.rethrowFromSystemServer();
5060 }
5061 }
5062
5063 /**
5064 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
5065 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
5066 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005067 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
5068 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005069 *
5070 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
5071 * triggering it as soon as this call returns.
5072 *
5073 * @param networkCallback The {@link NetworkCallback} used when making the request.
5074 */
5075 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
5076 printStackTrace();
5077 checkCallbackNotNull(networkCallback);
5078 final List<NetworkRequest> reqs = new ArrayList<>();
5079 // Find all requests associated to this callback and stop callback triggers immediately.
5080 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
5081 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00005082 if (networkCallback.networkRequest == null) {
5083 throw new IllegalArgumentException("NetworkCallback was not registered");
5084 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005085 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
5086 Log.d(TAG, "NetworkCallback was already unregistered");
5087 return;
5088 }
5089 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
5090 if (e.getValue() == networkCallback) {
5091 reqs.add(e.getKey());
5092 }
5093 }
5094 // TODO: throw exception if callback was registered more than once (http://b/20701525).
5095 for (NetworkRequest r : reqs) {
5096 try {
5097 mService.releaseNetworkRequest(r);
5098 } catch (RemoteException e) {
5099 throw e.rethrowFromSystemServer();
5100 }
5101 // Only remove mapping if rpc was successful.
5102 sCallbacks.remove(r);
5103 }
5104 networkCallback.networkRequest = ALREADY_UNREGISTERED;
5105 }
5106 }
5107
5108 /**
5109 * Unregisters a callback previously registered via
5110 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5111 *
5112 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
5113 * PendingIntent passed to
5114 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5115 * Cannot be null.
5116 */
5117 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
5118 releaseNetworkRequest(operation);
5119 }
5120
5121 /**
5122 * Informs the system whether it should switch to {@code network} regardless of whether it is
5123 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
5124 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
5125 * the system default network regardless of any other network that's currently connected. If
5126 * {@code always} is true, then the choice is remembered, so that the next time the user
5127 * connects to this network, the system will switch to it.
5128 *
5129 * @param network The network to accept.
5130 * @param accept Whether to accept the network even if unvalidated.
5131 * @param always Whether to remember this choice in the future.
5132 *
5133 * @hide
5134 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005135 @SystemApi(client = MODULE_LIBRARIES)
5136 @RequiresPermission(anyOf = {
5137 android.Manifest.permission.NETWORK_SETTINGS,
5138 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5139 android.Manifest.permission.NETWORK_STACK,
5140 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5141 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005142 try {
5143 mService.setAcceptUnvalidated(network, accept, always);
5144 } catch (RemoteException e) {
5145 throw e.rethrowFromSystemServer();
5146 }
5147 }
5148
5149 /**
5150 * Informs the system whether it should consider the network as validated even if it only has
5151 * partial connectivity. If {@code accept} is true, then the network will be considered as
5152 * validated even if connectivity is only partial. If {@code always} is true, then the choice
5153 * is remembered, so that the next time the user connects to this network, the system will
5154 * switch to it.
5155 *
5156 * @param network The network to accept.
5157 * @param accept Whether to consider the network as validated even if it has partial
5158 * connectivity.
5159 * @param always Whether to remember this choice in the future.
5160 *
5161 * @hide
5162 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005163 @SystemApi(client = MODULE_LIBRARIES)
5164 @RequiresPermission(anyOf = {
5165 android.Manifest.permission.NETWORK_SETTINGS,
5166 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5167 android.Manifest.permission.NETWORK_STACK,
5168 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5169 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5170 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005171 try {
5172 mService.setAcceptPartialConnectivity(network, accept, always);
5173 } catch (RemoteException e) {
5174 throw e.rethrowFromSystemServer();
5175 }
5176 }
5177
5178 /**
5179 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5180 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5181 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5182 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5183 *
5184 * @param network The network to accept.
5185 *
5186 * @hide
5187 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005188 @SystemApi(client = MODULE_LIBRARIES)
5189 @RequiresPermission(anyOf = {
5190 android.Manifest.permission.NETWORK_SETTINGS,
5191 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5192 android.Manifest.permission.NETWORK_STACK,
5193 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5194 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005195 try {
5196 mService.setAvoidUnvalidated(network);
5197 } catch (RemoteException e) {
5198 throw e.rethrowFromSystemServer();
5199 }
5200 }
5201
5202 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005203 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005204 *
5205 * @param timeMs The expired current time. The value should be set within a limited time from
5206 * now.
5207 *
5208 * @hide
5209 */
5210 public void setTestAllowBadWifiUntil(long timeMs) {
5211 try {
5212 mService.setTestAllowBadWifiUntil(timeMs);
5213 } catch (RemoteException e) {
5214 throw e.rethrowFromSystemServer();
5215 }
5216 }
5217
5218 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005219 * Requests that the system open the captive portal app on the specified network.
5220 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005221 * <p>This is to be used on networks where a captive portal was detected, as per
5222 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5223 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005224 * @param network The network to log into.
5225 *
5226 * @hide
5227 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005228 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5229 @RequiresPermission(anyOf = {
5230 android.Manifest.permission.NETWORK_SETTINGS,
5231 android.Manifest.permission.NETWORK_STACK,
5232 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5233 })
5234 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005235 try {
5236 mService.startCaptivePortalApp(network);
5237 } catch (RemoteException e) {
5238 throw e.rethrowFromSystemServer();
5239 }
5240 }
5241
5242 /**
5243 * Requests that the system open the captive portal app with the specified extras.
5244 *
5245 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5246 * corresponding permission.
5247 * @param network Network on which the captive portal was detected.
5248 * @param appExtras Extras to include in the app start intent.
5249 * @hide
5250 */
5251 @SystemApi
5252 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5253 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5254 try {
5255 mService.startCaptivePortalAppInternal(network, appExtras);
5256 } catch (RemoteException e) {
5257 throw e.rethrowFromSystemServer();
5258 }
5259 }
5260
5261 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005262 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005263 * @hide
5264 */
5265 @SystemApi
5266 @RequiresPermission(anyOf = {
5267 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5268 android.Manifest.permission.NETWORK_STACK})
5269 public boolean shouldAvoidBadWifi() {
5270 try {
5271 return mService.shouldAvoidBadWifi();
5272 } catch (RemoteException e) {
5273 throw e.rethrowFromSystemServer();
5274 }
5275 }
5276
5277 /**
5278 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5279 * time-sensitive user-facing operations when the system default network is temporarily
5280 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5281 * this method), and the operation should be infrequent to ensure that data usage is limited.
5282 *
5283 * An example of such an operation might be a time-sensitive foreground activity, such as a
5284 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5285 */
5286 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5287
5288 /**
5289 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5290 * a backup channel for traffic that is primarily going over another network.
5291 *
5292 * An example might be maintaining backup connections to peers or servers for the purpose of
5293 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5294 * on backup paths should be negligible compared to the traffic on the main path.
5295 */
5296 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5297
5298 /**
5299 * It is acceptable to use metered data to improve network latency and performance.
5300 */
5301 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5302
5303 /**
5304 * Return value to use for unmetered networks. On such networks we currently set all the flags
5305 * to true.
5306 * @hide
5307 */
5308 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5309 MULTIPATH_PREFERENCE_HANDOVER |
5310 MULTIPATH_PREFERENCE_RELIABILITY |
5311 MULTIPATH_PREFERENCE_PERFORMANCE;
5312
Aaron Huangcff22942021-05-27 16:31:26 +08005313 /** @hide */
5314 @Retention(RetentionPolicy.SOURCE)
5315 @IntDef(flag = true, value = {
5316 MULTIPATH_PREFERENCE_HANDOVER,
5317 MULTIPATH_PREFERENCE_RELIABILITY,
5318 MULTIPATH_PREFERENCE_PERFORMANCE,
5319 })
5320 public @interface MultipathPreference {
5321 }
5322
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005323 /**
5324 * Provides a hint to the calling application on whether it is desirable to use the
5325 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5326 * for multipath data transfer on this network when it is not the system default network.
5327 * Applications desiring to use multipath network protocols should call this method before
5328 * each such operation.
5329 *
5330 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005331 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005332 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005333 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005334 */
5335 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5336 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5337 try {
5338 return mService.getMultipathPreference(network);
5339 } catch (RemoteException e) {
5340 throw e.rethrowFromSystemServer();
5341 }
5342 }
5343
5344 /**
5345 * Resets all connectivity manager settings back to factory defaults.
5346 * @hide
5347 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005348 @SystemApi(client = MODULE_LIBRARIES)
5349 @RequiresPermission(anyOf = {
5350 android.Manifest.permission.NETWORK_SETTINGS,
5351 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005352 public void factoryReset() {
5353 try {
5354 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005355 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005356 } catch (RemoteException e) {
5357 throw e.rethrowFromSystemServer();
5358 }
5359 }
5360
5361 /**
5362 * Binds the current process to {@code network}. All Sockets created in the future
5363 * (and not explicitly bound via a bound SocketFactory from
5364 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5365 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5366 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5367 * work and all host name resolutions will fail. This is by design so an application doesn't
5368 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5369 * To clear binding pass {@code null} for {@code network}. Using individually bound
5370 * Sockets created by Network.getSocketFactory().createSocket() and
5371 * performing network-specific host name resolutions via
5372 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5373 * {@code bindProcessToNetwork}.
5374 *
5375 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5376 * the current binding.
5377 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5378 */
5379 public boolean bindProcessToNetwork(@Nullable Network network) {
5380 // Forcing callers to call through non-static function ensures ConnectivityManager
5381 // instantiated.
5382 return setProcessDefaultNetwork(network);
5383 }
5384
5385 /**
5386 * Binds the current process to {@code network}. All Sockets created in the future
5387 * (and not explicitly bound via a bound SocketFactory from
5388 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5389 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5390 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5391 * work and all host name resolutions will fail. This is by design so an application doesn't
5392 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5393 * To clear binding pass {@code null} for {@code network}. Using individually bound
5394 * Sockets created by Network.getSocketFactory().createSocket() and
5395 * performing network-specific host name resolutions via
5396 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5397 * {@code setProcessDefaultNetwork}.
5398 *
5399 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5400 * the current binding.
5401 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5402 * @deprecated This function can throw {@link IllegalStateException}. Use
5403 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5404 * is a direct replacement.
5405 */
5406 @Deprecated
5407 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5408 int netId = (network == null) ? NETID_UNSET : network.netId;
5409 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5410
5411 if (netId != NETID_UNSET) {
5412 netId = network.getNetIdForResolv();
5413 }
5414
5415 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5416 return false;
5417 }
5418
5419 if (!isSameNetId) {
5420 // Set HTTP proxy system properties to match network.
5421 // TODO: Deprecate this static method and replace it with a non-static version.
5422 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005423 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005424 } catch (SecurityException e) {
5425 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5426 Log.e(TAG, "Can't set proxy properties", e);
5427 }
5428 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005429 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005430 // Must flush socket pool as idle sockets will be bound to previous network and may
5431 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005432 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005433 }
5434
5435 return true;
5436 }
5437
5438 /**
5439 * Returns the {@link Network} currently bound to this process via
5440 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5441 *
5442 * @return {@code Network} to which this process is bound, or {@code null}.
5443 */
5444 @Nullable
5445 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005446 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005447 // instantiated.
5448 return getProcessDefaultNetwork();
5449 }
5450
5451 /**
5452 * Returns the {@link Network} currently bound to this process via
5453 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5454 *
5455 * @return {@code Network} to which this process is bound, or {@code null}.
5456 * @deprecated Using this function can lead to other functions throwing
5457 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5458 * {@code getBoundNetworkForProcess} is a direct replacement.
5459 */
5460 @Deprecated
5461 @Nullable
5462 public static Network getProcessDefaultNetwork() {
5463 int netId = NetworkUtils.getBoundNetworkForProcess();
5464 if (netId == NETID_UNSET) return null;
5465 return new Network(netId);
5466 }
5467
5468 private void unsupportedStartingFrom(int version) {
5469 if (Process.myUid() == Process.SYSTEM_UID) {
5470 // The getApplicationInfo() call we make below is not supported in system context. Let
5471 // the call through here, and rely on the fact that ConnectivityService will refuse to
5472 // allow the system to use these APIs anyway.
5473 return;
5474 }
5475
5476 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5477 throw new UnsupportedOperationException(
5478 "This method is not supported in target SDK version " + version + " and above");
5479 }
5480 }
5481
5482 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5483 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5484 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5485 // remove these exemptions. Note that this check is not secure, and apps can still access these
5486 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5487 // so is unsupported and may break in the future. http://b/22728205
5488 private void checkLegacyRoutingApiAccess() {
5489 unsupportedStartingFrom(VERSION_CODES.M);
5490 }
5491
5492 /**
5493 * Binds host resolutions performed by this process to {@code network}.
5494 * {@link #bindProcessToNetwork} takes precedence over this setting.
5495 *
5496 * @param network The {@link Network} to bind host resolutions from the current process to, or
5497 * {@code null} to clear the current binding.
5498 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5499 * @hide
5500 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5501 */
5502 @Deprecated
5503 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5504 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5505 return NetworkUtils.bindProcessToNetworkForHostResolution(
5506 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5507 }
5508
5509 /**
5510 * Device is not restricting metered network activity while application is running on
5511 * background.
5512 */
5513 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5514
5515 /**
5516 * Device is restricting metered network activity while application is running on background,
5517 * but application is allowed to bypass it.
5518 * <p>
5519 * In this state, application should take action to mitigate metered network access.
5520 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5521 */
5522 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5523
5524 /**
5525 * Device is restricting metered network activity while application is running on background.
5526 * <p>
5527 * In this state, application should not try to use the network while running on background,
5528 * because it would be denied.
5529 */
5530 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5531
5532 /**
5533 * A change in the background metered network activity restriction has occurred.
5534 * <p>
5535 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5536 * applies to them.
5537 * <p>
5538 * This is only sent to registered receivers, not manifest receivers.
5539 */
5540 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5541 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5542 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5543
Aaron Huangcff22942021-05-27 16:31:26 +08005544 /** @hide */
5545 @Retention(RetentionPolicy.SOURCE)
5546 @IntDef(flag = false, value = {
5547 RESTRICT_BACKGROUND_STATUS_DISABLED,
5548 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5549 RESTRICT_BACKGROUND_STATUS_ENABLED,
5550 })
5551 public @interface RestrictBackgroundStatus {
5552 }
5553
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005554 /**
5555 * Determines if the calling application is subject to metered network restrictions while
5556 * running on background.
5557 *
5558 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5559 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5560 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5561 */
5562 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5563 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005564 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005565 } catch (RemoteException e) {
5566 throw e.rethrowFromSystemServer();
5567 }
5568 }
5569
5570 /**
5571 * The network watchlist is a list of domains and IP addresses that are associated with
5572 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5573 * currently used by the system for validation purposes.
5574 *
5575 * @return Hash of network watchlist config file. Null if config does not exist.
5576 */
5577 @Nullable
5578 public byte[] getNetworkWatchlistConfigHash() {
5579 try {
5580 return mService.getNetworkWatchlistConfigHash();
5581 } catch (RemoteException e) {
5582 Log.e(TAG, "Unable to get watchlist config hash");
5583 throw e.rethrowFromSystemServer();
5584 }
5585 }
5586
5587 /**
5588 * Returns the {@code uid} of the owner of a network connection.
5589 *
5590 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5591 * IPPROTO_UDP} currently supported.
5592 * @param local The local {@link InetSocketAddress} of a connection.
5593 * @param remote The remote {@link InetSocketAddress} of a connection.
5594 * @return {@code uid} if the connection is found and the app has permission to observe it
5595 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5596 * android.os.Process#INVALID_UID} if the connection is not found.
Sherri Lin443b7182023-02-08 04:49:29 +01005597 * @throws SecurityException if the caller is not the active VpnService for the current
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005598 * user.
Sherri Lin443b7182023-02-08 04:49:29 +01005599 * @throws IllegalArgumentException if an unsupported protocol is requested.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005600 */
5601 public int getConnectionOwnerUid(
5602 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5603 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5604 try {
5605 return mService.getConnectionOwnerUid(connectionInfo);
5606 } catch (RemoteException e) {
5607 throw e.rethrowFromSystemServer();
5608 }
5609 }
5610
5611 private void printStackTrace() {
5612 if (DEBUG) {
5613 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5614 final StringBuffer sb = new StringBuffer();
5615 for (int i = 3; i < callStack.length; i++) {
5616 final String stackTrace = callStack[i].toString();
5617 if (stackTrace == null || stackTrace.contains("android.os")) {
5618 break;
5619 }
5620 sb.append(" [").append(stackTrace).append("]");
5621 }
5622 Log.d(TAG, "StackLog:" + sb.toString());
5623 }
5624 }
5625
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005626 /** @hide */
5627 public TestNetworkManager startOrGetTestNetworkManager() {
5628 final IBinder tnBinder;
5629 try {
5630 tnBinder = mService.startOrGetTestNetworkService();
5631 } catch (RemoteException e) {
5632 throw e.rethrowFromSystemServer();
5633 }
5634
5635 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5636 }
5637
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005638 /** @hide */
5639 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5640 return new ConnectivityDiagnosticsManager(mContext, mService);
5641 }
5642
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005643 /**
5644 * Simulates a Data Stall for the specified Network.
5645 *
5646 * <p>This method should only be used for tests.
5647 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005648 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5649 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005650 *
5651 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005652 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5653 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5654 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005655 * @param network The Network for which a Data Stall is being simluated.
5656 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5657 * @throws SecurityException if the caller is not the owner of the given network.
5658 * @hide
5659 */
5660 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5661 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5662 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005663 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005664 @NonNull Network network, @NonNull PersistableBundle extras) {
5665 try {
5666 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5667 } catch (RemoteException e) {
5668 e.rethrowFromSystemServer();
5669 }
5670 }
5671
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005672 @NonNull
5673 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5674
5675 /**
5676 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5677 * receive available QoS events related to the {@link Network} and local ip + port
5678 * specified within socketInfo.
5679 * <p/>
5680 * The same {@link QosCallback} must be unregistered before being registered a second time,
5681 * otherwise {@link QosCallbackRegistrationException} is thrown.
5682 * <p/>
5683 * This API does not, in itself, require any permission if called with a network that is not
5684 * restricted. However, the underlying implementation currently only supports the IMS network,
5685 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5686 * useful, because they'd never be called back on networks that they would have access to.
5687 *
5688 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5689 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5690 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5691 * @throws RuntimeException if the app already has too many callbacks registered.
5692 *
5693 * Exceptions after the time of registration is passed through
5694 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5695 *
5696 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005697 * @param executor The executor on which the callback will be invoked. The provided
5698 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005699 * callbacks cannot be guaranteed.onQosCallbackRegistered
5700 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005701 *
5702 * @hide
5703 */
5704 @SystemApi
5705 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005706 @CallbackExecutor @NonNull final Executor executor,
5707 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005708 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005709 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005710 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005711
5712 try {
5713 synchronized (mQosCallbackConnections) {
5714 if (getQosCallbackConnection(callback) == null) {
5715 final QosCallbackConnection connection =
5716 new QosCallbackConnection(this, callback, executor);
5717 mQosCallbackConnections.add(connection);
5718 mService.registerQosSocketCallback(socketInfo, connection);
5719 } else {
5720 Log.e(TAG, "registerQosCallback: Callback already registered");
5721 throw new QosCallbackRegistrationException();
5722 }
5723 }
5724 } catch (final RemoteException e) {
5725 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5726
5727 // The same unregister method method is called for consistency even though nothing
5728 // will be sent to the ConnectivityService since the callback was never successfully
5729 // registered.
5730 unregisterQosCallback(callback);
5731 e.rethrowFromSystemServer();
5732 } catch (final ServiceSpecificException e) {
5733 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5734 unregisterQosCallback(callback);
5735 throw convertServiceException(e);
5736 }
5737 }
5738
5739 /**
5740 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5741 * events once unregistered and can be registered a second time.
5742 * <p/>
5743 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5744 *
5745 * @param callback the callback being unregistered
5746 *
5747 * @hide
5748 */
5749 @SystemApi
5750 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5751 Objects.requireNonNull(callback, "The callback must be non-null");
5752 try {
5753 synchronized (mQosCallbackConnections) {
5754 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5755 if (connection != null) {
5756 connection.stopReceivingMessages();
5757 mService.unregisterQosCallback(connection);
5758 mQosCallbackConnections.remove(connection);
5759 } else {
5760 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5761 }
5762 }
5763 } catch (final RemoteException e) {
5764 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5765 e.rethrowFromSystemServer();
5766 }
5767 }
5768
5769 /**
5770 * Gets the connection related to the callback.
5771 *
5772 * @param callback the callback to look up
5773 * @return the related connection
5774 */
5775 @Nullable
5776 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5777 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5778 // Checking by reference here is intentional
5779 if (connection.getCallback() == callback) {
5780 return connection;
5781 }
5782 }
5783 return null;
5784 }
5785
5786 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005787 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005788 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5789 * be used to request that the system provide a network without causing the network to be
5790 * in the foreground.
5791 *
5792 * <p>This method will attempt to find the best network that matches the passed
5793 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5794 * criteria. The platform will evaluate which network is the best at its own discretion.
5795 * Throughput, latency, cost per byte, policy, user preference and other considerations
5796 * may be factored in the decision of what is considered the best network.
5797 *
5798 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5799 * matching this request, while always attempting to match the request to a better network if
5800 * possible. If a better match is found, the platform will switch this request to the now-best
5801 * network and inform the app of the newly best network by invoking
5802 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5803 * will not try to maintain any other network than the best one currently matching the request:
5804 * a network not matching any network request may be disconnected at any time.
5805 *
5806 * <p>For example, an application could use this method to obtain a connected cellular network
5807 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5808 * radio to consume additional power. Or, an application could inform the system that it wants
5809 * a network supporting sending MMSes and have the system let it know about the currently best
5810 * MMS-supporting network through the provided {@link NetworkCallback}.
5811 *
5812 * <p>The status of the request can be followed by listening to the various callbacks described
5813 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5814 * used to direct traffic to the network (although accessing some networks may be subject to
5815 * holding specific permissions). Callers will learn about the specific characteristics of the
5816 * network through
5817 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5818 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5819 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5820 * matching the request at any given time; therefore when a better network matching the request
5821 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5822 * with the new network after which no further updates are given about the previously-best
5823 * network, unless it becomes the best again at some later time. All callbacks are invoked
5824 * in order on the same thread, which by default is a thread created by the framework running
5825 * in the app.
5826 *
5827 * <p>This{@link NetworkRequest} will live until released via
5828 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5829 * which point the system may let go of the network at any time.
5830 *
5831 * <p>It is presently unsupported to request a network with mutable
5832 * {@link NetworkCapabilities} such as
5833 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5834 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5835 * as these {@code NetworkCapabilities} represent states that a particular
5836 * network may never attain, and whether a network will attain these states
5837 * is unknown prior to bringing up the network so the framework does not
5838 * know how to go about satisfying a request with these capabilities.
5839 *
5840 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5841 * number of outstanding requests to 100 per app (identified by their UID), shared with
5842 * all variants of this method, of {@link #registerNetworkCallback} as well as
5843 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5844 * Requesting a network with this method will count toward this limit. If this limit is
5845 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5846 * make sure to unregister the callbacks with
5847 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5848 *
5849 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005850 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5851 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005852 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5853 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005854 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5855 * @throws SecurityException if missing the appropriate permissions.
5856 * @throws RuntimeException if the app already has too many callbacks registered.
5857 *
5858 * @hide
5859 */
5860 @SystemApi(client = MODULE_LIBRARIES)
5861 @SuppressLint("ExecutorRegistration")
5862 @RequiresPermission(anyOf = {
5863 android.Manifest.permission.NETWORK_SETTINGS,
5864 android.Manifest.permission.NETWORK_STACK,
5865 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5866 })
5867 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005868 @NonNull NetworkCallback networkCallback,
5869 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005870 final NetworkCapabilities nc = request.networkCapabilities;
5871 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005872 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005873 }
James Mattis12aeab82021-01-10 14:24:24 -08005874
5875 /**
James Mattis12aeab82021-01-10 14:24:24 -08005876 * Used by automotive devices to set the network preferences used to direct traffic at an
5877 * application level as per the given OemNetworkPreferences. An example use-case would be an
5878 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5879 * vehicle via a particular network.
5880 *
5881 * Calling this will overwrite the existing preference.
5882 *
5883 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5884 * @param executor the executor on which listener will be invoked.
5885 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5886 * communicate completion of setOemNetworkPreference(). This will only be
5887 * called once upon successful completion of setOemNetworkPreference().
5888 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5889 * @throws SecurityException if missing the appropriate permissions.
5890 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005891 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005892 */
James Mattis6e2d7022021-01-26 16:23:52 -08005893 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005894 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005895 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005896 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005897 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005898 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5899 if (null != listener) {
5900 Objects.requireNonNull(executor, "Executor must be non-null");
5901 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005902 final IOnCompleteListener listenerInternal = listener == null ? null :
5903 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005904 @Override
5905 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005906 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005907 }
5908 };
5909
5910 try {
5911 mService.setOemNetworkPreference(preference, listenerInternal);
5912 } catch (RemoteException e) {
5913 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5914 throw e.rethrowFromSystemServer();
5915 }
5916 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005917
Chalard Jeanad565e22021-02-25 17:23:40 +09005918 /**
5919 * Request that a user profile is put by default on a network matching a given preference.
5920 *
5921 * See the documentation for the individual preferences for a description of the supported
5922 * behaviors.
5923 *
5924 * @param profile the profile concerned.
5925 * @param preference the preference for this profile.
5926 * @param executor an executor to execute the listener on. Optional if listener is null.
5927 * @param listener an optional listener to listen for completion of the operation.
5928 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5929 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005930 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5931 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005932 * @hide
5933 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005934 // This function is for establishing per-profile default networking and can only be called by
5935 // the device policy manager, running as the system server. It would make no sense to call it
5936 // on a context for a user because it does not establish a setting on behalf of a user, rather
5937 // it establishes a setting for a user on behalf of the DPM.
5938 @SuppressLint({"UserHandle"})
5939 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005940 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005941 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005942 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005943 @ProfileNetworkPreferencePolicy final int preference,
5944 @Nullable @CallbackExecutor final Executor executor,
5945 @Nullable final Runnable listener) {
5946
5947 ProfileNetworkPreference.Builder preferenceBuilder =
5948 new ProfileNetworkPreference.Builder();
5949 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005950 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5951 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5952 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005953 setProfileNetworkPreferences(profile,
5954 List.of(preferenceBuilder.build()), executor, listener);
5955 }
5956
5957 /**
5958 * Set a list of default network selection policies for a user profile.
5959 *
5960 * Calling this API with a user handle defines the entire policy for that user handle.
5961 * It will overwrite any setting previously set for the same user profile,
5962 * and not affect previously set settings for other handles.
5963 *
5964 * Call this API with an empty list to remove settings for this user profile.
5965 *
5966 * See {@link ProfileNetworkPreference} for more details on each preference
5967 * parameter.
5968 *
5969 * @param profile the user profile for which the preference is being set.
5970 * @param profileNetworkPreferences the list of profile network preferences for the
5971 * provided profile.
5972 * @param executor an executor to execute the listener on. Optional if listener is null.
5973 * @param listener an optional listener to listen for completion of the operation.
5974 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5975 * @throws SecurityException if missing the appropriate permissions.
5976 * @hide
5977 */
5978 @SystemApi(client = MODULE_LIBRARIES)
5979 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5980 public void setProfileNetworkPreferences(
5981 @NonNull final UserHandle profile,
5982 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005983 @Nullable @CallbackExecutor final Executor executor,
5984 @Nullable final Runnable listener) {
5985 if (null != listener) {
5986 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5987 }
5988 final IOnCompleteListener proxy;
5989 if (null == listener) {
5990 proxy = null;
5991 } else {
5992 proxy = new IOnCompleteListener.Stub() {
5993 @Override
5994 public void onComplete() {
5995 executor.execute(listener::run);
5996 }
5997 };
5998 }
5999 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006000 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09006001 } catch (RemoteException e) {
6002 throw e.rethrowFromSystemServer();
6003 }
6004 }
6005
lucaslin5cdbcfb2021-03-12 00:46:33 +08006006 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08006007 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08006008 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08006009 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08006010
6011 /**
6012 * Get the network ID range reserved for IPSec tunnel interfaces.
6013 *
6014 * @return A Range which indicates the network ID range of IPSec tunnel interface.
6015 * @hide
6016 */
6017 @SystemApi(client = MODULE_LIBRARIES)
6018 @NonNull
6019 public static Range<Integer> getIpSecNetIdRange() {
6020 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
6021 }
markchien738ad912021-12-09 18:15:45 +08006022
6023 /**
Junyu Laidf210362023-10-24 02:47:50 +00006024 * Sets data saver switch.
6025 *
Junyu Laif3048232024-01-08 17:08:43 +08006026 * <p>This API configures the bandwidth control, and filling data saver status in BpfMap,
6027 * which is intended for internal use by the network stack to optimize performance
6028 * when frequently checking data saver status for multiple uids without doing IPC.
6029 * It does not directly control the global data saver mode that users manage in settings.
6030 * To query the comprehensive data saver status for a specific UID, including allowlist
6031 * considerations, use {@link #getRestrictBackgroundStatus}.
6032 *
Junyu Laidf210362023-10-24 02:47:50 +00006033 * @param enable True if enable.
6034 * @throws IllegalStateException if failed.
6035 * @hide
6036 */
6037 @FlaggedApi(Flags.SET_DATA_SAVER_VIA_CM)
6038 @SystemApi(client = MODULE_LIBRARIES)
6039 @RequiresPermission(anyOf = {
6040 android.Manifest.permission.NETWORK_SETTINGS,
6041 android.Manifest.permission.NETWORK_STACK,
6042 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6043 })
6044 public void setDataSaverEnabled(final boolean enable) {
6045 try {
6046 mService.setDataSaverEnabled(enable);
6047 } catch (RemoteException e) {
6048 throw e.rethrowFromSystemServer();
6049 }
6050 }
6051
6052 /**
markchiene46042b2022-03-02 18:07:35 +08006053 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
6054 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08006055 *
6056 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006057 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08006058 * @hide
6059 */
6060 @SystemApi(client = MODULE_LIBRARIES)
6061 @RequiresPermission(anyOf = {
6062 android.Manifest.permission.NETWORK_SETTINGS,
6063 android.Manifest.permission.NETWORK_STACK,
6064 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6065 })
markchiene46042b2022-03-02 18:07:35 +08006066 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006067 try {
markchiene46042b2022-03-02 18:07:35 +08006068 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08006069 } catch (RemoteException e) {
6070 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006071 }
6072 }
6073
6074 /**
markchiene46042b2022-03-02 18:07:35 +08006075 * Removes the specified UID from the list of UIDs that are allowed to use background data on
6076 * metered networks when background data is restricted. The deny list takes precedence over
6077 * the allow list.
6078 *
6079 * @param uid uid of target app
6080 * @throws IllegalStateException if updating allow list failed.
6081 * @hide
6082 */
6083 @SystemApi(client = MODULE_LIBRARIES)
6084 @RequiresPermission(anyOf = {
6085 android.Manifest.permission.NETWORK_SETTINGS,
6086 android.Manifest.permission.NETWORK_STACK,
6087 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6088 })
6089 public void removeUidFromMeteredNetworkAllowList(final int uid) {
6090 try {
6091 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
6092 } catch (RemoteException e) {
6093 throw e.rethrowFromSystemServer();
6094 }
6095 }
6096
6097 /**
6098 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
6099 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08006100 *
6101 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006102 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08006103 * @hide
6104 */
6105 @SystemApi(client = MODULE_LIBRARIES)
6106 @RequiresPermission(anyOf = {
6107 android.Manifest.permission.NETWORK_SETTINGS,
6108 android.Manifest.permission.NETWORK_STACK,
6109 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6110 })
markchiene46042b2022-03-02 18:07:35 +08006111 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006112 try {
markchiene46042b2022-03-02 18:07:35 +08006113 mService.updateMeteredNetworkDenyList(uid, true /* add */);
6114 } catch (RemoteException e) {
6115 throw e.rethrowFromSystemServer();
6116 }
6117 }
6118
6119 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09006120 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08006121 * networks if background data is not restricted. The deny list takes precedence over the
6122 * allow list.
6123 *
6124 * @param uid uid of target app
6125 * @throws IllegalStateException if updating deny list failed.
6126 * @hide
6127 */
6128 @SystemApi(client = MODULE_LIBRARIES)
6129 @RequiresPermission(anyOf = {
6130 android.Manifest.permission.NETWORK_SETTINGS,
6131 android.Manifest.permission.NETWORK_STACK,
6132 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6133 })
6134 public void removeUidFromMeteredNetworkDenyList(final int uid) {
6135 try {
6136 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08006137 } catch (RemoteException e) {
6138 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08006139 }
6140 }
6141
6142 /**
6143 * Sets a firewall rule for the specified UID on the specified chain.
6144 *
6145 * @param chain target chain.
6146 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08006147 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08006148 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08006149 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08006150 * @hide
6151 */
6152 @SystemApi(client = MODULE_LIBRARIES)
6153 @RequiresPermission(anyOf = {
6154 android.Manifest.permission.NETWORK_SETTINGS,
6155 android.Manifest.permission.NETWORK_STACK,
6156 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6157 })
markchien3c04e662022-03-22 16:29:56 +08006158 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
6159 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08006160 try {
markchien3c04e662022-03-22 16:29:56 +08006161 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08006162 } catch (RemoteException e) {
6163 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006164 }
6165 }
markchien98a6f952022-01-13 23:43:53 +08006166
6167 /**
Motomu Utsumi900b8062023-01-19 16:16:49 +09006168 * Get firewall rule of specified firewall chain on specified uid.
6169 *
6170 * @param chain target chain.
6171 * @param uid target uid
6172 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
6173 * @throws UnsupportedOperationException if called on pre-T devices.
6174 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6175 * cause of the failure.
6176 * @hide
6177 */
6178 @RequiresPermission(anyOf = {
6179 android.Manifest.permission.NETWORK_SETTINGS,
6180 android.Manifest.permission.NETWORK_STACK,
6181 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6182 })
6183 public int getUidFirewallRule(@FirewallChain final int chain, final int uid) {
6184 try {
6185 return mService.getUidFirewallRule(chain, uid);
6186 } catch (RemoteException e) {
6187 throw e.rethrowFromSystemServer();
6188 }
6189 }
6190
6191 /**
markchien98a6f952022-01-13 23:43:53 +08006192 * Enables or disables the specified firewall chain.
6193 *
6194 * @param chain target chain.
6195 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00006196 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08006197 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08006198 * @hide
6199 */
6200 @SystemApi(client = MODULE_LIBRARIES)
6201 @RequiresPermission(anyOf = {
6202 android.Manifest.permission.NETWORK_SETTINGS,
6203 android.Manifest.permission.NETWORK_STACK,
6204 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6205 })
6206 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
6207 try {
6208 mService.setFirewallChainEnabled(chain, enable);
6209 } catch (RemoteException e) {
6210 throw e.rethrowFromSystemServer();
6211 }
6212 }
markchien00a0bed2022-01-13 23:46:13 +08006213
6214 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00006215 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006216 *
6217 * @param chain target chain.
6218 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6219 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006220 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6221 * cause of the failure.
6222 * @hide
6223 */
6224 @RequiresPermission(anyOf = {
6225 android.Manifest.permission.NETWORK_SETTINGS,
6226 android.Manifest.permission.NETWORK_STACK,
6227 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6228 })
6229 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6230 try {
6231 return mService.getFirewallChainEnabled(chain);
6232 } catch (RemoteException e) {
6233 throw e.rethrowFromSystemServer();
6234 }
6235 }
6236
6237 /**
markchien00a0bed2022-01-13 23:46:13 +08006238 * Replaces the contents of the specified UID-based firewall chain.
6239 *
6240 * @param chain target chain to replace.
6241 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006242 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006243 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6244 * @hide
6245 */
6246 @SystemApi(client = MODULE_LIBRARIES)
6247 @RequiresPermission(anyOf = {
6248 android.Manifest.permission.NETWORK_SETTINGS,
6249 android.Manifest.permission.NETWORK_STACK,
6250 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6251 })
6252 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6253 Objects.requireNonNull(uids);
6254 try {
6255 mService.replaceFirewallChain(chain, uids);
6256 } catch (RemoteException e) {
6257 throw e.rethrowFromSystemServer();
6258 }
6259 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006260
Junyu Laie0031522023-08-29 18:32:57 +08006261 /**
Junyu Laic3dc5b62023-09-06 19:10:02 +08006262 * Return whether the network is blocked for the given uid and metered condition.
Junyu Laie0031522023-08-29 18:32:57 +08006263 *
6264 * Similar to {@link NetworkPolicyManager#isUidNetworkingBlocked}, but directly reads the BPF
6265 * maps and therefore considerably faster. For use by the NetworkStack process only.
6266 *
6267 * @param uid The target uid.
Junyu Laic3dc5b62023-09-06 19:10:02 +08006268 * @param isNetworkMetered Whether the target network is metered.
6269 *
6270 * @return True if all networking with the given condition is blocked. Otherwise, false.
Junyu Laie0031522023-08-29 18:32:57 +08006271 * @throws IllegalStateException if the map cannot be opened.
6272 * @throws ServiceSpecificException if the read fails.
6273 * @hide
6274 */
6275 // This isn't protected by a standard Android permission since it can't
6276 // afford to do IPC for performance reasons. Instead, the access control
6277 // is provided by linux file group permission AID_NET_BW_ACCT and the
6278 // selinux context fs_bpf_net*.
6279 // Only the system server process and the network stack have access.
Junyu Laibb594802023-09-04 11:37:03 +08006280 @FlaggedApi(Flags.SUPPORT_IS_UID_NETWORKING_BLOCKED)
6281 @SystemApi(client = MODULE_LIBRARIES)
Junyu Lai934d4832024-02-22 11:21:47 +08006282 // Note b/326143935 kernel bug can trigger crash on some T device.
6283 @RequiresApi(VERSION_CODES.UPSIDE_DOWN_CAKE)
Junyu Laie0031522023-08-29 18:32:57 +08006284 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Junyu Laic3dc5b62023-09-06 19:10:02 +08006285 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Junyu Lai934d4832024-02-22 11:21:47 +08006286 if (!SdkLevel.isAtLeastU()) {
6287 Log.wtf(TAG, "isUidNetworkingBlocked is not supported on pre-U devices");
6288 }
Junyu Laie0031522023-08-29 18:32:57 +08006289 final BpfNetMapsReader reader = BpfNetMapsReader.getInstance();
Junyu Lai38c75032023-12-04 07:52:19 +00006290 // Note that before V, the data saver status in bpf is written by ConnectivityService
6291 // when receiving {@link #ACTION_RESTRICT_BACKGROUND_CHANGED}. Thus,
6292 // the status is not synchronized.
6293 // On V+, the data saver status is set by platform code when enabling/disabling
6294 // data saver, which is synchronized.
6295 return reader.isUidNetworkingBlocked(uid, isNetworkMetered, reader.getDataSaverEnabled());
Junyu Laie0031522023-08-29 18:32:57 +08006296 }
6297
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006298 /** @hide */
6299 public IBinder getCompanionDeviceManagerProxyService() {
6300 try {
6301 return mService.getCompanionDeviceManagerProxyService();
6302 } catch (RemoteException e) {
6303 throw e.rethrowFromSystemServer();
6304 }
6305 }
Chalard Jean2fb66f12023-08-25 12:50:37 +09006306
6307 private static final Object sRoutingCoordinatorManagerLock = new Object();
6308 @GuardedBy("sRoutingCoordinatorManagerLock")
6309 private static RoutingCoordinatorManager sRoutingCoordinatorManager = null;
6310 /** @hide */
6311 @RequiresApi(Build.VERSION_CODES.S)
6312 public RoutingCoordinatorManager getRoutingCoordinatorManager() {
6313 try {
6314 synchronized (sRoutingCoordinatorManagerLock) {
6315 if (null == sRoutingCoordinatorManager) {
6316 sRoutingCoordinatorManager = new RoutingCoordinatorManager(mContext,
6317 IRoutingCoordinator.Stub.asInterface(
6318 mService.getRoutingCoordinatorService()));
6319 }
6320 return sRoutingCoordinatorManager;
6321 }
6322 } catch (RemoteException e) {
6323 throw e.rethrowFromSystemServer();
6324 }
6325 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006326}