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