blob: a934ddb0bcb9771bfec1be8b6673c3be1e6c4031 [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;
Junyu Laic3dc5b62023-09-06 19:10:02 +080019import static android.content.pm.ApplicationInfo.FLAG_PERSISTENT;
20import static android.content.pm.ApplicationInfo.FLAG_SYSTEM;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080021import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090022import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
23import static android.net.NetworkRequest.Type.LISTEN;
junyulai7664f622021-03-12 20:05:08 +080024import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090025import static android.net.NetworkRequest.Type.REQUEST;
26import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colittia77d05e2021-01-29 20:14:04 +090027import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090028import static android.net.QosCallback.QosCallbackRegistrationException;
29
Junyu Laic3dc5b62023-09-06 19:10:02 +080030import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE;
31
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090032import android.annotation.CallbackExecutor;
Junyu Laidf210362023-10-24 02:47:50 +000033import android.annotation.FlaggedApi;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090034import android.annotation.IntDef;
35import android.annotation.NonNull;
36import android.annotation.Nullable;
Chalard Jean2fb66f12023-08-25 12:50:37 +090037import android.annotation.RequiresApi;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090038import android.annotation.RequiresPermission;
39import android.annotation.SdkConstant;
40import android.annotation.SdkConstant.SdkConstantType;
41import android.annotation.SuppressLint;
42import android.annotation.SystemApi;
43import android.annotation.SystemService;
Junyu Laic3dc5b62023-09-06 19:10:02 +080044import android.annotation.TargetApi;
45import android.app.Application;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090046import android.app.PendingIntent;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090047import android.app.admin.DevicePolicyManager;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090048import android.compat.annotation.UnsupportedAppUsage;
Junyu Laic3dc5b62023-09-06 19:10:02 +080049import android.content.BroadcastReceiver;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090050import android.content.ComponentName;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090051import android.content.Context;
52import android.content.Intent;
Junyu Laic3dc5b62023-09-06 19:10:02 +080053import android.content.IntentFilter;
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +090054import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090055import android.net.IpSecManager.UdpEncapsulationSocket;
56import android.net.SocketKeepalive.Callback;
57import android.net.TetheringManager.StartTetheringCallback;
58import android.net.TetheringManager.TetheringEventCallback;
59import android.net.TetheringManager.TetheringRequest;
60import android.os.Binder;
61import android.os.Build;
62import android.os.Build.VERSION_CODES;
63import android.os.Bundle;
64import android.os.Handler;
65import android.os.IBinder;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090066import android.os.Looper;
67import android.os.Message;
68import android.os.Messenger;
69import android.os.ParcelFileDescriptor;
70import android.os.PersistableBundle;
71import android.os.Process;
72import android.os.RemoteException;
73import android.os.ResultReceiver;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090074import android.os.ServiceSpecificException;
Chalard Jeanad565e22021-02-25 17:23:40 +090075import android.os.UserHandle;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090076import android.provider.Settings;
77import android.telephony.SubscriptionManager;
78import android.telephony.TelephonyManager;
79import android.util.ArrayMap;
80import android.util.Log;
81import android.util.Range;
82import android.util.SparseIntArray;
83
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090084import com.android.internal.annotations.GuardedBy;
Junyu Laic3dc5b62023-09-06 19:10:02 +080085import com.android.internal.annotations.VisibleForTesting;
Junyu Lai9e880522023-11-14 15:44:37 +080086import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090087
88import libcore.net.event.NetworkEventDispatcher;
89
90import java.io.IOException;
91import java.io.UncheckedIOException;
92import java.lang.annotation.Retention;
93import java.lang.annotation.RetentionPolicy;
94import java.net.DatagramSocket;
95import java.net.InetAddress;
96import java.net.InetSocketAddress;
97import java.net.Socket;
98import java.util.ArrayList;
99import java.util.Collection;
100import java.util.HashMap;
101import java.util.List;
102import java.util.Map;
103import java.util.Objects;
104import java.util.concurrent.Executor;
105import java.util.concurrent.ExecutorService;
106import java.util.concurrent.Executors;
107import java.util.concurrent.RejectedExecutionException;
Junyu Laic3dc5b62023-09-06 19:10:02 +0800108import java.util.concurrent.atomic.AtomicBoolean;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900109
110/**
111 * Class that answers queries about the state of network connectivity. It also
112 * notifies applications when network connectivity changes.
113 * <p>
114 * The primary responsibilities of this class are to:
115 * <ol>
116 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
117 * <li>Send broadcast intents when network connectivity changes</li>
118 * <li>Attempt to "fail over" to another network when connectivity to a network
119 * is lost</li>
120 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
121 * state of the available networks</li>
122 * <li>Provide an API that allows applications to request and select networks for their data
123 * traffic</li>
124 * </ol>
125 */
126@SystemService(Context.CONNECTIVITY_SERVICE)
127public class ConnectivityManager {
128 private static final String TAG = "ConnectivityManager";
129 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
130
Junyu Laidf210362023-10-24 02:47:50 +0000131 // TODO : remove this class when udc-mainline-prod is abandoned and android.net.flags.Flags is
132 // available here
133 /** @hide */
134 public static class Flags {
135 static final String SET_DATA_SAVER_VIA_CM =
136 "com.android.net.flags.set_data_saver_via_cm";
Junyu Laibb594802023-09-04 11:37:03 +0800137 static final String SUPPORT_IS_UID_NETWORKING_BLOCKED =
138 "com.android.net.flags.support_is_uid_networking_blocked";
Suprabh Shukla2d893b62023-11-06 08:47:40 -0800139 static final String BASIC_BACKGROUND_RESTRICTIONS_ENABLED =
140 "com.android.net.flags.basic_background_restrictions_enabled";
Junyu Laidf210362023-10-24 02:47:50 +0000141 }
142
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900143 /**
144 * A change in network connectivity has occurred. A default connection has either
145 * been established or lost. The NetworkInfo for the affected network is
146 * sent as an extra; it should be consulted to see what kind of
147 * connectivity event occurred.
148 * <p/>
149 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
150 * broadcast if they declare the broadcast receiver in their manifest. Apps
151 * will still receive broadcasts if they register their
152 * {@link android.content.BroadcastReceiver} with
153 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
154 * and that context is still valid.
155 * <p/>
156 * If this is a connection that was the result of failing over from a
157 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
158 * set to true.
159 * <p/>
160 * For a loss of connectivity, if the connectivity manager is attempting
161 * to connect (or has already connected) to another network, the
162 * NetworkInfo for the new network is also passed as an extra. This lets
163 * any receivers of the broadcast know that they should not necessarily
164 * tell the user that no data traffic will be possible. Instead, the
165 * receiver should expect another broadcast soon, indicating either that
166 * the failover attempt succeeded (and so there is still overall data
167 * connectivity), or that the failover attempt failed, meaning that all
168 * connectivity has been lost.
169 * <p/>
170 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
171 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900172 * <p />
173 * Note that this broadcast is deprecated and generally tries to implement backwards
174 * compatibility with older versions of Android. As such, it may not reflect new
175 * capabilities of the system, like multiple networks being connected at the same
176 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900177 *
178 * @deprecated apps should use the more versatile {@link #requestNetwork},
179 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
180 * functions instead for faster and more detailed updates about the network
181 * changes they care about.
182 */
183 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
184 @Deprecated
185 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
186
187 /**
188 * The device has connected to a network that has presented a captive
189 * portal, which is blocking Internet connectivity. The user was presented
190 * with a notification that network sign in is required,
191 * and the user invoked the notification's action indicating they
192 * desire to sign in to the network. Apps handling this activity should
193 * facilitate signing in to the network. This action includes a
194 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
195 * the network presenting the captive portal; all communication with the
196 * captive portal must be done using this {@code Network} object.
197 * <p/>
198 * This activity includes a {@link CaptivePortal} extra named
199 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
200 * outcomes of the captive portal sign in to the system:
201 * <ul>
202 * <li> When the app handling this action believes the user has signed in to
203 * the network and the captive portal has been dismissed, the app should
204 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
205 * reevaluate the network. If reevaluation finds the network no longer
206 * subject to a captive portal, the network may become the default active
207 * data network.</li>
208 * <li> When the app handling this action believes the user explicitly wants
209 * to ignore the captive portal and the network, the app should call
210 * {@link CaptivePortal#ignoreNetwork}. </li>
211 * </ul>
212 */
213 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
214 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
215
216 /**
217 * The lookup key for a {@link NetworkInfo} object. Retrieve with
218 * {@link android.content.Intent#getParcelableExtra(String)}.
219 *
220 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
221 * can't accurately represent modern network characteristics.
222 * Please obtain information about networks from the {@link NetworkCapabilities}
223 * or {@link LinkProperties} objects instead.
224 */
225 @Deprecated
226 public static final String EXTRA_NETWORK_INFO = "networkInfo";
227
228 /**
229 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
230 *
231 * @see android.content.Intent#getIntExtra(String, int)
232 * @deprecated The network type is not rich enough to represent the characteristics
233 * of modern networks. Please use {@link NetworkCapabilities} instead,
234 * in particular the transports.
235 */
236 @Deprecated
237 public static final String EXTRA_NETWORK_TYPE = "networkType";
238
239 /**
240 * The lookup key for a boolean that indicates whether a connect event
241 * is for a network to which the connectivity manager was failing over
242 * following a disconnect on another network.
243 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
244 *
245 * @deprecated See {@link NetworkInfo}.
246 */
247 @Deprecated
248 public static final String EXTRA_IS_FAILOVER = "isFailover";
249 /**
250 * The lookup key for a {@link NetworkInfo} object. This is supplied when
251 * there is another network that it may be possible to connect to. Retrieve with
252 * {@link android.content.Intent#getParcelableExtra(String)}.
253 *
254 * @deprecated See {@link NetworkInfo}.
255 */
256 @Deprecated
257 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
258 /**
259 * The lookup key for a boolean that indicates whether there is a
260 * complete lack of connectivity, i.e., no network is available.
261 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
262 */
263 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
264 /**
265 * The lookup key for a string that indicates why an attempt to connect
266 * to a network failed. The string has no particular structure. It is
267 * intended to be used in notifications presented to users. Retrieve
268 * it with {@link android.content.Intent#getStringExtra(String)}.
269 */
270 public static final String EXTRA_REASON = "reason";
271 /**
272 * The lookup key for a string that provides optionally supplied
273 * extra information about the network state. The information
274 * may be passed up from the lower networking layers, and its
275 * meaning may be specific to a particular network type. Retrieve
276 * it with {@link android.content.Intent#getStringExtra(String)}.
277 *
278 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
279 */
280 @Deprecated
281 public static final String EXTRA_EXTRA_INFO = "extraInfo";
282 /**
283 * The lookup key for an int that provides information about
284 * our connection to the internet at large. 0 indicates no connection,
285 * 100 indicates a great connection. Retrieve it with
286 * {@link android.content.Intent#getIntExtra(String, int)}.
287 * {@hide}
288 */
289 public static final String EXTRA_INET_CONDITION = "inetCondition";
290 /**
291 * The lookup key for a {@link CaptivePortal} object included with the
292 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
293 * object can be used to either indicate to the system that the captive
294 * portal has been dismissed or that the user does not want to pursue
295 * signing in to captive portal. Retrieve it with
296 * {@link android.content.Intent#getParcelableExtra(String)}.
297 */
298 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
299
300 /**
301 * Key for passing a URL to the captive portal login activity.
302 */
303 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
304
305 /**
306 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
307 * portal login activity.
308 * {@hide}
309 */
310 @SystemApi
311 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
312 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
313
314 /**
315 * Key for passing a user agent string to the captive portal login activity.
316 * {@hide}
317 */
318 @SystemApi
319 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
320 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
321
322 /**
323 * Broadcast action to indicate the change of data activity status
324 * (idle or active) on a network in a recent period.
325 * The network becomes active when data transmission is started, or
326 * idle if there is no data transmission for a period of time.
327 * {@hide}
328 */
329 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
330 public static final String ACTION_DATA_ACTIVITY_CHANGE =
331 "android.net.conn.DATA_ACTIVITY_CHANGE";
332 /**
333 * The lookup key for an enum that indicates the network device type on which this data activity
334 * change happens.
335 * {@hide}
336 */
337 public static final String EXTRA_DEVICE_TYPE = "deviceType";
338 /**
339 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
340 * it is actively sending or receiving data and {@code false} means it is idle.
341 * {@hide}
342 */
343 public static final String EXTRA_IS_ACTIVE = "isActive";
344 /**
345 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
346 * {@hide}
347 */
348 public static final String EXTRA_REALTIME_NS = "tsNanos";
349
350 /**
351 * Broadcast Action: The setting for background data usage has changed
352 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
353 * <p>
354 * If an application uses the network in the background, it should listen
355 * for this broadcast and stop using the background data if the value is
356 * {@code false}.
357 * <p>
358 *
359 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
360 * of background data depends on several combined factors, and
361 * this broadcast is no longer sent. Instead, when background
362 * data is unavailable, {@link #getActiveNetworkInfo()} will now
363 * appear disconnected. During first boot after a platform
364 * upgrade, this broadcast will be sent once if
365 * {@link #getBackgroundDataSetting()} was {@code false} before
366 * the upgrade.
367 */
368 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
369 @Deprecated
370 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
371 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
372
373 /**
374 * Broadcast Action: The network connection may not be good
375 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
376 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
377 * the network and it's condition.
378 * @hide
379 */
380 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
381 @UnsupportedAppUsage
382 public static final String INET_CONDITION_ACTION =
383 "android.net.conn.INET_CONDITION_ACTION";
384
385 /**
386 * Broadcast Action: A tetherable connection has come or gone.
387 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
388 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
389 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
390 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
391 * the current state of tethering. Each include a list of
392 * interface names in that state (may be empty).
393 * @hide
394 */
395 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
396 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
397 public static final String ACTION_TETHER_STATE_CHANGED =
398 TetheringManager.ACTION_TETHER_STATE_CHANGED;
399
400 /**
401 * @hide
402 * gives a String[] listing all the interfaces configured for
403 * tethering and currently available for tethering.
404 */
405 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
406 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
407
408 /**
409 * @hide
410 * gives a String[] listing all the interfaces currently in local-only
411 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
412 */
413 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
414
415 /**
416 * @hide
417 * gives a String[] listing all the interfaces currently tethered
418 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
419 */
420 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
421 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
422
423 /**
424 * @hide
425 * gives a String[] listing all the interfaces we tried to tether and
426 * failed. Use {@link #getLastTetherError} to find the error code
427 * for any interfaces listed here.
428 */
429 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
430 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
431
432 /**
433 * Broadcast Action: The captive portal tracker has finished its test.
434 * Sent only while running Setup Wizard, in lieu of showing a user
435 * notification.
436 * @hide
437 */
438 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
439 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
440 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
441 /**
442 * The lookup key for a boolean that indicates whether a captive portal was detected.
443 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
444 * @hide
445 */
446 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
447
448 /**
449 * Action used to display a dialog that asks the user whether to connect to a network that is
450 * not validated. This intent is used to start the dialog in settings via startActivity.
451 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800452 * This action includes a {@link Network} typed extra which is called
453 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
454 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900455 * @hide
456 */
lucaslincf6d4502021-03-04 17:09:51 +0800457 @SystemApi(client = MODULE_LIBRARIES)
458 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900459
460 /**
461 * Action used to display a dialog that asks the user whether to avoid a network that is no
462 * longer validated. This intent is used to start the dialog in settings via startActivity.
463 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800464 * This action includes a {@link Network} typed extra which is called
465 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
466 * validated.
467 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900468 * @hide
469 */
lucaslincf6d4502021-03-04 17:09:51 +0800470 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900471 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800472 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900473
474 /**
475 * Action used to display a dialog that asks the user whether to stay connected to a network
476 * that has not validated. This intent is used to start the dialog in settings via
477 * startActivity.
478 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800479 * This action includes a {@link Network} typed extra which is called
480 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
481 * connectivity.
482 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900483 * @hide
484 */
lucaslincf6d4502021-03-04 17:09:51 +0800485 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900486 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800487 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900488
489 /**
paulhub49c8422021-04-07 16:18:13 +0800490 * Clear DNS Cache Action: This is broadcast when networks have changed and old
491 * DNS entries should be cleared.
492 * @hide
493 */
494 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
495 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
496 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
497
498 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900499 * Invalid tethering type.
500 * @see #startTethering(int, boolean, OnStartTetheringCallback)
501 * @hide
502 */
503 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
504
505 /**
506 * Wifi tethering type.
507 * @see #startTethering(int, boolean, OnStartTetheringCallback)
508 * @hide
509 */
510 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900511 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900512
513 /**
514 * USB tethering type.
515 * @see #startTethering(int, boolean, OnStartTetheringCallback)
516 * @hide
517 */
518 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900519 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900520
521 /**
522 * Bluetooth tethering type.
523 * @see #startTethering(int, boolean, OnStartTetheringCallback)
524 * @hide
525 */
526 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900527 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900528
529 /**
530 * Wifi P2p tethering type.
531 * Wifi P2p tethering is set through events automatically, and don't
532 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
533 * @hide
534 */
535 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
536
537 /**
538 * Extra used for communicating with the TetherService. Includes the type of tethering to
539 * enable if any.
540 * @hide
541 */
542 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
543
544 /**
545 * Extra used for communicating with the TetherService. Includes the type of tethering for
546 * which to cancel provisioning.
547 * @hide
548 */
549 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
550
551 /**
552 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
553 * provisioning.
554 * @hide
555 */
556 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
557
558 /**
559 * Tells the TetherService to run a provision check now.
560 * @hide
561 */
562 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
563
564 /**
565 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
566 * which will receive provisioning results. Can be left empty.
567 * @hide
568 */
569 public static final String EXTRA_PROVISION_CALLBACK =
570 TetheringConstants.EXTRA_PROVISION_CALLBACK;
571
572 /**
573 * The absence of a connection type.
574 * @hide
575 */
576 @SystemApi
577 public static final int TYPE_NONE = -1;
578
579 /**
580 * A Mobile data connection. Devices may support more than one.
581 *
582 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
583 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000584 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900585 */
586 @Deprecated
587 public static final int TYPE_MOBILE = 0;
588
589 /**
590 * A WIFI data connection. Devices may support more than one.
591 *
592 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
593 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000594 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900595 */
596 @Deprecated
597 public static final int TYPE_WIFI = 1;
598
599 /**
600 * An MMS-specific Mobile data connection. This network type may use the
601 * same network interface as {@link #TYPE_MOBILE} or it may use a different
602 * one. This is used by applications needing to talk to the carrier's
603 * Multimedia Messaging Service servers.
604 *
605 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
606 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
607 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
608 */
609 @Deprecated
610 public static final int TYPE_MOBILE_MMS = 2;
611
612 /**
613 * A SUPL-specific Mobile data connection. This network type may use the
614 * same network interface as {@link #TYPE_MOBILE} or it may use a different
615 * one. This is used by applications needing to talk to the carrier's
616 * Secure User Plane Location servers for help locating the device.
617 *
618 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
619 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
620 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
621 */
622 @Deprecated
623 public static final int TYPE_MOBILE_SUPL = 3;
624
625 /**
626 * A DUN-specific Mobile data connection. This network type may use the
627 * same network interface as {@link #TYPE_MOBILE} or it may use a different
628 * one. This is sometimes by the system when setting up an upstream connection
629 * for tethering so that the carrier is aware of DUN traffic.
630 *
631 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
632 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
633 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
634 */
635 @Deprecated
636 public static final int TYPE_MOBILE_DUN = 4;
637
638 /**
639 * A High Priority Mobile data connection. This network type uses the
640 * same network interface as {@link #TYPE_MOBILE} but the routing setup
641 * is different.
642 *
643 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
644 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000645 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900646 */
647 @Deprecated
648 public static final int TYPE_MOBILE_HIPRI = 5;
649
650 /**
651 * A WiMAX data connection.
652 *
653 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
654 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000655 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900656 */
657 @Deprecated
658 public static final int TYPE_WIMAX = 6;
659
660 /**
661 * A Bluetooth data connection.
662 *
663 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
664 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000665 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900666 */
667 @Deprecated
668 public static final int TYPE_BLUETOOTH = 7;
669
670 /**
671 * Fake data connection. This should not be used on shipping devices.
672 * @deprecated This is not used any more.
673 */
674 @Deprecated
675 public static final int TYPE_DUMMY = 8;
676
677 /**
678 * An Ethernet data connection.
679 *
680 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
681 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000682 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900683 */
684 @Deprecated
685 public static final int TYPE_ETHERNET = 9;
686
687 /**
688 * Over the air Administration.
689 * @deprecated Use {@link NetworkCapabilities} instead.
690 * {@hide}
691 */
692 @Deprecated
693 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
694 public static final int TYPE_MOBILE_FOTA = 10;
695
696 /**
697 * IP Multimedia Subsystem.
698 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
699 * {@hide}
700 */
701 @Deprecated
702 @UnsupportedAppUsage
703 public static final int TYPE_MOBILE_IMS = 11;
704
705 /**
706 * Carrier Branded Services.
707 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
708 * {@hide}
709 */
710 @Deprecated
711 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
712 public static final int TYPE_MOBILE_CBS = 12;
713
714 /**
715 * A Wi-Fi p2p connection. Only requesting processes will have access to
716 * the peers connected.
717 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
718 * {@hide}
719 */
720 @Deprecated
721 @SystemApi
722 public static final int TYPE_WIFI_P2P = 13;
723
724 /**
725 * The network to use for initially attaching to the network
726 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
727 * {@hide}
728 */
729 @Deprecated
730 @UnsupportedAppUsage
731 public static final int TYPE_MOBILE_IA = 14;
732
733 /**
734 * Emergency PDN connection for emergency services. This
735 * may include IMS and MMS in emergency situations.
736 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
737 * {@hide}
738 */
739 @Deprecated
740 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
741 public static final int TYPE_MOBILE_EMERGENCY = 15;
742
743 /**
744 * The network that uses proxy to achieve connectivity.
745 * @deprecated Use {@link NetworkCapabilities} instead.
746 * {@hide}
747 */
748 @Deprecated
749 @SystemApi
750 public static final int TYPE_PROXY = 16;
751
752 /**
753 * A virtual network using one or more native bearers.
754 * It may or may not be providing security services.
755 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
756 */
757 @Deprecated
758 public static final int TYPE_VPN = 17;
759
760 /**
761 * A network that is exclusively meant to be used for testing
762 *
763 * @deprecated Use {@link NetworkCapabilities} instead.
764 * @hide
765 */
766 @Deprecated
767 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
768
769 /**
770 * @deprecated Use {@link NetworkCapabilities} instead.
771 * @hide
772 */
773 @Deprecated
774 @Retention(RetentionPolicy.SOURCE)
775 @IntDef(prefix = { "TYPE_" }, value = {
776 TYPE_NONE,
777 TYPE_MOBILE,
778 TYPE_WIFI,
779 TYPE_MOBILE_MMS,
780 TYPE_MOBILE_SUPL,
781 TYPE_MOBILE_DUN,
782 TYPE_MOBILE_HIPRI,
783 TYPE_WIMAX,
784 TYPE_BLUETOOTH,
785 TYPE_DUMMY,
786 TYPE_ETHERNET,
787 TYPE_MOBILE_FOTA,
788 TYPE_MOBILE_IMS,
789 TYPE_MOBILE_CBS,
790 TYPE_WIFI_P2P,
791 TYPE_MOBILE_IA,
792 TYPE_MOBILE_EMERGENCY,
793 TYPE_PROXY,
794 TYPE_VPN,
795 TYPE_TEST
796 })
797 public @interface LegacyNetworkType {}
798
799 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
800 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
801 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
802 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
803 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
804
805 /** {@hide} */
806 public static final int MAX_RADIO_TYPE = TYPE_TEST;
807
808 /** {@hide} */
809 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
810
811 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
812
813 /**
814 * If you want to set the default network preference,you can directly
815 * change the networkAttributes array in framework's config.xml.
816 *
817 * @deprecated Since we support so many more networks now, the single
818 * network default network preference can't really express
819 * the hierarchy. Instead, the default is defined by the
820 * networkAttributes in config.xml. You can determine
821 * the current value by calling {@link #getNetworkPreference()}
822 * from an App.
823 */
824 @Deprecated
825 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
826
827 /**
828 * @hide
829 */
830 public static final int REQUEST_ID_UNSET = 0;
831
832 /**
833 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
834 * This allows to distinguish when unregistering NetworkCallbacks those that were never
835 * registered from those that were already unregistered.
836 * @hide
837 */
838 private static final NetworkRequest ALREADY_UNREGISTERED =
839 new NetworkRequest.Builder().clearCapabilities().build();
840
841 /**
842 * A NetID indicating no Network is selected.
843 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
844 * @hide
845 */
846 public static final int NETID_UNSET = 0;
847
848 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000849 * Flag to indicate that an app is not subject to any restrictions that could result in its
850 * network access blocked.
851 *
852 * @hide
853 */
854 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
855 public static final int BLOCKED_REASON_NONE = 0;
856
857 /**
858 * Flag to indicate that an app is subject to Battery saver restrictions that would
859 * result in its network access being blocked.
860 *
861 * @hide
862 */
863 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
864 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
865
866 /**
867 * Flag to indicate that an app is subject to Doze restrictions that would
868 * result in its network access being blocked.
869 *
870 * @hide
871 */
872 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
873 public static final int BLOCKED_REASON_DOZE = 1 << 1;
874
875 /**
876 * Flag to indicate that an app is subject to App Standby restrictions that would
877 * result in its network access being blocked.
878 *
879 * @hide
880 */
881 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
882 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
883
884 /**
885 * Flag to indicate that an app is subject to Restricted mode restrictions that would
886 * result in its network access being blocked.
887 *
888 * @hide
889 */
890 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
891 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
892
893 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900894 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
895 * is not currently connected.
896 *
897 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
898 *
899 * @hide
900 */
901 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
902 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
903
904 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100905 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
906 * result in its network access being blocked.
907 *
908 * @hide
909 */
910 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
911 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
912
913 /**
Suprabh Shukla2d893b62023-11-06 08:47:40 -0800914 * Flag to indicate that an app is subject to default background restrictions that would
915 * result in its network access being blocked.
916 *
917 * @hide
918 */
919 @FlaggedApi(Flags.BASIC_BACKGROUND_RESTRICTIONS_ENABLED)
920 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
921 public static final int BLOCKED_REASON_APP_BACKGROUND = 1 << 6;
922
923 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000924 * Flag to indicate that an app is subject to Data saver restrictions that would
925 * result in its metered network access being blocked.
926 *
927 * @hide
928 */
929 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
930 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
931
932 /**
933 * Flag to indicate that an app is subject to user restrictions that would
934 * result in its metered network access being blocked.
935 *
936 * @hide
937 */
938 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
939 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
940
941 /**
942 * Flag to indicate that an app is subject to Device admin restrictions that would
943 * result in its metered network access being blocked.
944 *
945 * @hide
946 */
947 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
948 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
949
950 /**
951 * @hide
952 */
953 @Retention(RetentionPolicy.SOURCE)
954 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
955 BLOCKED_REASON_NONE,
956 BLOCKED_REASON_BATTERY_SAVER,
957 BLOCKED_REASON_DOZE,
958 BLOCKED_REASON_APP_STANDBY,
959 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900960 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100961 BLOCKED_REASON_LOW_POWER_STANDBY,
Suprabh Shukla2d893b62023-11-06 08:47:40 -0800962 BLOCKED_REASON_APP_BACKGROUND,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000963 BLOCKED_METERED_REASON_DATA_SAVER,
964 BLOCKED_METERED_REASON_USER_RESTRICTED,
965 BLOCKED_METERED_REASON_ADMIN_DISABLED,
966 })
967 public @interface BlockedReason {}
968
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900969 /**
970 * Set of blocked reasons that are only applicable on metered networks.
971 *
972 * @hide
973 */
974 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
975 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
976
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900977 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
978 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900979
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900980 /**
markchiene1561fa2021-12-09 22:00:56 +0800981 * Firewall chain for device idle (doze mode).
982 * Allowlist of apps that have network access in device idle.
983 * @hide
984 */
985 @SystemApi(client = MODULE_LIBRARIES)
986 public static final int FIREWALL_CHAIN_DOZABLE = 1;
987
988 /**
989 * Firewall chain used for app standby.
990 * Denylist of apps that do not have network access.
991 * @hide
992 */
993 @SystemApi(client = MODULE_LIBRARIES)
994 public static final int FIREWALL_CHAIN_STANDBY = 2;
995
996 /**
997 * Firewall chain used for battery saver.
998 * Allowlist of apps that have network access when battery saver is on.
999 * @hide
1000 */
1001 @SystemApi(client = MODULE_LIBRARIES)
1002 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
1003
1004 /**
1005 * Firewall chain used for restricted networking mode.
1006 * Allowlist of apps that have access in restricted networking mode.
1007 * @hide
1008 */
1009 @SystemApi(client = MODULE_LIBRARIES)
1010 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
1011
Robert Horvath34cba142022-01-27 19:52:43 +01001012 /**
1013 * Firewall chain used for low power standby.
1014 * Allowlist of apps that have access in low power standby.
1015 * @hide
1016 */
1017 @SystemApi(client = MODULE_LIBRARIES)
1018 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
1019
Motomu Utsumib08654c2022-05-11 05:56:26 +00001020 /**
Suprabh Shukla2d893b62023-11-06 08:47:40 -08001021 * Firewall chain used for always-on default background restrictions.
1022 * Allowlist of apps that have access because either they are in the foreground or they are
1023 * exempted for specific situations while in the background.
1024 * @hide
1025 */
1026 @FlaggedApi(Flags.BASIC_BACKGROUND_RESTRICTIONS_ENABLED)
1027 @SystemApi(client = MODULE_LIBRARIES)
1028 public static final int FIREWALL_CHAIN_BACKGROUND = 6;
1029
1030 /**
Motomu Utsumid9801492022-06-01 13:57:27 +00001031 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001032 *
1033 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1034 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1035 *
1036 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1037 * independent of the others. The chains can be enabled and disabled independently, and apps can
1038 * be added and removed from each chain independently.
1039 *
1040 * @see #FIREWALL_CHAIN_OEM_DENY_2
1041 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001042 * @hide
1043 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001044 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001045 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1046
1047 /**
1048 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001049 *
1050 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1051 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1052 *
1053 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1054 * independent of the others. The chains can be enabled and disabled independently, and apps can
1055 * be added and removed from each chain independently.
1056 *
1057 * @see #FIREWALL_CHAIN_OEM_DENY_1
1058 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001059 * @hide
1060 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001061 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001062 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1063
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001064 /**
1065 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001066 *
1067 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1068 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1069 *
1070 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1071 * independent of the others. The chains can be enabled and disabled independently, and apps can
1072 * be added and removed from each chain independently.
1073 *
1074 * @see #FIREWALL_CHAIN_OEM_DENY_1
1075 * @see #FIREWALL_CHAIN_OEM_DENY_2
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001076 * @hide
1077 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001078 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001079 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1080
markchiene1561fa2021-12-09 22:00:56 +08001081 /** @hide */
1082 @Retention(RetentionPolicy.SOURCE)
1083 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1084 FIREWALL_CHAIN_DOZABLE,
1085 FIREWALL_CHAIN_STANDBY,
1086 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001087 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001088 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Suprabh Shukla2d893b62023-11-06 08:47:40 -08001089 FIREWALL_CHAIN_BACKGROUND,
Motomu Utsumid9801492022-06-01 13:57:27 +00001090 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001091 FIREWALL_CHAIN_OEM_DENY_2,
1092 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001093 })
1094 public @interface FirewallChain {}
1095
1096 /**
markchien011a7f52022-03-29 01:07:22 +08001097 * A firewall rule which allows or drops packets depending on existing policy.
1098 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1099 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001100 * @hide
1101 */
1102 @SystemApi(client = MODULE_LIBRARIES)
1103 public static final int FIREWALL_RULE_DEFAULT = 0;
1104
1105 /**
markchien011a7f52022-03-29 01:07:22 +08001106 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1107 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001108 * @hide
1109 */
1110 @SystemApi(client = MODULE_LIBRARIES)
1111 public static final int FIREWALL_RULE_ALLOW = 1;
1112
1113 /**
markchien011a7f52022-03-29 01:07:22 +08001114 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1115 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001116 * @hide
1117 */
1118 @SystemApi(client = MODULE_LIBRARIES)
1119 public static final int FIREWALL_RULE_DENY = 2;
1120
1121 /** @hide */
1122 @Retention(RetentionPolicy.SOURCE)
1123 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1124 FIREWALL_RULE_DEFAULT,
1125 FIREWALL_RULE_ALLOW,
1126 FIREWALL_RULE_DENY
1127 })
1128 public @interface FirewallRule {}
1129
1130 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001131 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1132 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1133 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1134 * methods that take a Context argument.
1135 */
1136 private static ConnectivityManager sInstance;
1137
1138 private final Context mContext;
1139
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001140 @GuardedBy("mTetheringEventCallbacks")
1141 private TetheringManager mTetheringManager;
1142
1143 private TetheringManager getTetheringManager() {
1144 synchronized (mTetheringEventCallbacks) {
1145 if (mTetheringManager == null) {
1146 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1147 }
1148 return mTetheringManager;
1149 }
1150 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001151
1152 /**
1153 * Tests if a given integer represents a valid network type.
1154 * @param networkType the type to be tested
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001155 * @return {@code true} if the type is valid, else {@code false}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001156 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1157 * validate a network type.
1158 */
1159 @Deprecated
1160 public static boolean isNetworkTypeValid(int networkType) {
1161 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1162 }
1163
1164 /**
1165 * Returns a non-localized string representing a given network type.
1166 * ONLY used for debugging output.
1167 * @param type the type needing naming
1168 * @return a String for the given type, or a string version of the type ("87")
1169 * if no name is known.
1170 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1171 * {@hide}
1172 */
1173 @Deprecated
1174 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1175 public static String getNetworkTypeName(int type) {
1176 switch (type) {
1177 case TYPE_NONE:
1178 return "NONE";
1179 case TYPE_MOBILE:
1180 return "MOBILE";
1181 case TYPE_WIFI:
1182 return "WIFI";
1183 case TYPE_MOBILE_MMS:
1184 return "MOBILE_MMS";
1185 case TYPE_MOBILE_SUPL:
1186 return "MOBILE_SUPL";
1187 case TYPE_MOBILE_DUN:
1188 return "MOBILE_DUN";
1189 case TYPE_MOBILE_HIPRI:
1190 return "MOBILE_HIPRI";
1191 case TYPE_WIMAX:
1192 return "WIMAX";
1193 case TYPE_BLUETOOTH:
1194 return "BLUETOOTH";
1195 case TYPE_DUMMY:
1196 return "DUMMY";
1197 case TYPE_ETHERNET:
1198 return "ETHERNET";
1199 case TYPE_MOBILE_FOTA:
1200 return "MOBILE_FOTA";
1201 case TYPE_MOBILE_IMS:
1202 return "MOBILE_IMS";
1203 case TYPE_MOBILE_CBS:
1204 return "MOBILE_CBS";
1205 case TYPE_WIFI_P2P:
1206 return "WIFI_P2P";
1207 case TYPE_MOBILE_IA:
1208 return "MOBILE_IA";
1209 case TYPE_MOBILE_EMERGENCY:
1210 return "MOBILE_EMERGENCY";
1211 case TYPE_PROXY:
1212 return "PROXY";
1213 case TYPE_VPN:
1214 return "VPN";
Junyu Laic9f1ca62022-07-25 16:31:59 +08001215 case TYPE_TEST:
1216 return "TEST";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001217 default:
1218 return Integer.toString(type);
1219 }
1220 }
1221
1222 /**
1223 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001224 */
lucaslin10774b72021-03-17 14:16:01 +08001225 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001226 public void systemReady() {
1227 try {
1228 mService.systemReady();
1229 } catch (RemoteException e) {
1230 throw e.rethrowFromSystemServer();
1231 }
1232 }
1233
1234 /**
1235 * Checks if a given type uses the cellular data connection.
1236 * This should be replaced in the future by a network property.
1237 * @param networkType the type to check
1238 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1239 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1240 * {@hide}
1241 */
1242 @Deprecated
1243 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1244 public static boolean isNetworkTypeMobile(int networkType) {
1245 switch (networkType) {
1246 case TYPE_MOBILE:
1247 case TYPE_MOBILE_MMS:
1248 case TYPE_MOBILE_SUPL:
1249 case TYPE_MOBILE_DUN:
1250 case TYPE_MOBILE_HIPRI:
1251 case TYPE_MOBILE_FOTA:
1252 case TYPE_MOBILE_IMS:
1253 case TYPE_MOBILE_CBS:
1254 case TYPE_MOBILE_IA:
1255 case TYPE_MOBILE_EMERGENCY:
1256 return true;
1257 default:
1258 return false;
1259 }
1260 }
1261
1262 /**
1263 * Checks if the given network type is backed by a Wi-Fi radio.
1264 *
1265 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1266 * @hide
1267 */
1268 @Deprecated
1269 public static boolean isNetworkTypeWifi(int networkType) {
1270 switch (networkType) {
1271 case TYPE_WIFI:
1272 case TYPE_WIFI_P2P:
1273 return true;
1274 default:
1275 return false;
1276 }
1277 }
1278
1279 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001280 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001281 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Junyu Lai35665cc2022-12-19 17:37:48 +08001282 * Specify that the traffic for this user should by follow the default rules:
1283 * applications in the profile designated by the UserHandle behave like any
1284 * other application and use the system default network as their default
1285 * network. Compare other PROFILE_NETWORK_PREFERENCE_* settings.
Chalard Jeanad565e22021-02-25 17:23:40 +09001286 * @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_DEFAULT = 0;
1290
1291 /**
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)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001294 * Specify that the traffic for this user should by default go on a network with
1295 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1296 * if no such network is available.
1297 * @hide
1298 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001299 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001300 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1301
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001302 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001303 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001304 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001305 * Specify that the traffic for this user should by default go on a network with
1306 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
Junyu Lai35665cc2022-12-19 17:37:48 +08001307 * should not have a default network at all (that is, network accesses that
1308 * do not specify a network explicitly terminate with an error), even if there
1309 * is a system default network available to apps outside this preference.
1310 * The apps can still use a non-enterprise network if they request it explicitly
1311 * provided that specific network doesn't require any specific permission they
1312 * do not hold.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001313 * @hide
1314 */
1315 @SystemApi(client = MODULE_LIBRARIES)
1316 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1317
Junyu Lai35665cc2022-12-19 17:37:48 +08001318 /**
1319 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
1320 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1321 * Specify that the traffic for this user should by default go on a network with
1322 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}.
1323 * If there is no such network, the apps will have no default
1324 * network at all, even if there are available non-enterprise networks on the
1325 * device (that is, network accesses that do not specify a network explicitly
1326 * terminate with an error). Additionally, the designated apps should be
1327 * blocked from using any non-enterprise network even if they specify it
1328 * explicitly, unless they hold specific privilege overriding this (see
1329 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS}).
1330 * @hide
1331 */
1332 @SystemApi(client = MODULE_LIBRARIES)
1333 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING = 3;
1334
Chalard Jeanad565e22021-02-25 17:23:40 +09001335 /** @hide */
1336 @Retention(RetentionPolicy.SOURCE)
1337 @IntDef(value = {
1338 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001339 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1340 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001341 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001342 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001343 }
1344
1345 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001346 * Specifies the preferred network type. When the device has more
1347 * than one type available the preferred network type will be used.
1348 *
1349 * @param preference the network type to prefer over all others. It is
1350 * unspecified what happens to the old preferred network in the
1351 * overall ordering.
1352 * @deprecated Functionality has been removed as it no longer makes sense,
1353 * with many more than two networks - we'd need an array to express
1354 * preference. Instead we use dynamic network properties of
1355 * the networks to describe their precedence.
1356 */
1357 @Deprecated
1358 public void setNetworkPreference(int preference) {
1359 }
1360
1361 /**
1362 * Retrieves the current preferred network type.
1363 *
1364 * @return an integer representing the preferred network type
1365 *
1366 * @deprecated Functionality has been removed as it no longer makes sense,
1367 * with many more than two networks - we'd need an array to express
1368 * preference. Instead we use dynamic network properties of
1369 * the networks to describe their precedence.
1370 */
1371 @Deprecated
1372 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1373 public int getNetworkPreference() {
1374 return TYPE_NONE;
1375 }
1376
1377 /**
1378 * Returns details about the currently active default data network. When
1379 * connected, this network is the default route for outgoing connections.
1380 * You should always check {@link NetworkInfo#isConnected()} before initiating
1381 * network traffic. This may return {@code null} when there is no default
1382 * network.
1383 * Note that if the default network is a VPN, this method will return the
1384 * NetworkInfo for one of its underlying networks instead, or null if the
1385 * VPN agent did not specify any. Apps interested in learning about VPNs
1386 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1387 *
1388 * @return a {@link NetworkInfo} object for the current default network
1389 * or {@code null} if no default network is currently active
1390 * @deprecated See {@link NetworkInfo}.
1391 */
1392 @Deprecated
1393 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1394 @Nullable
1395 public NetworkInfo getActiveNetworkInfo() {
1396 try {
1397 return mService.getActiveNetworkInfo();
1398 } catch (RemoteException e) {
1399 throw e.rethrowFromSystemServer();
1400 }
1401 }
1402
1403 /**
1404 * Returns a {@link Network} object corresponding to the currently active
1405 * default data network. In the event that the current active default data
1406 * network disconnects, the returned {@code Network} object will no longer
1407 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001408 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001409 *
1410 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001411 * {@code null} if no default network is currently active or if
1412 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001413 */
1414 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1415 @Nullable
1416 public Network getActiveNetwork() {
1417 try {
1418 return mService.getActiveNetwork();
1419 } catch (RemoteException e) {
1420 throw e.rethrowFromSystemServer();
1421 }
1422 }
1423
1424 /**
1425 * Returns a {@link Network} object corresponding to the currently active
1426 * default data network for a specific UID. In the event that the default data
1427 * network disconnects, the returned {@code Network} object will no longer
1428 * be usable. This will return {@code null} when there is no default
1429 * network for the UID.
1430 *
1431 * @return a {@link Network} object for the current default network for the
1432 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001433 *
1434 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001435 */
1436 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1437 @Nullable
1438 public Network getActiveNetworkForUid(int uid) {
1439 return getActiveNetworkForUid(uid, false);
1440 }
1441
1442 /** {@hide} */
1443 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1444 try {
1445 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1446 } catch (RemoteException e) {
1447 throw e.rethrowFromSystemServer();
1448 }
1449 }
1450
lucaslin3ba7cc22022-12-19 02:35:33 +00001451 private static UidRange[] getUidRangeArray(@NonNull Collection<Range<Integer>> ranges) {
1452 Objects.requireNonNull(ranges);
1453 final UidRange[] rangesArray = new UidRange[ranges.size()];
1454 int index = 0;
1455 for (Range<Integer> range : ranges) {
1456 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1457 }
1458
1459 return rangesArray;
1460 }
1461
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001462 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001463 * Adds or removes a requirement for given UID ranges to use the VPN.
1464 *
1465 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1466 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1467 * otherwise have permission to bypass the VPN (e.g., because they have the
1468 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1469 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1470 * set to {@code false}, a previously-added restriction is removed.
1471 * <p>
1472 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1473 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1474 * remove a previously-added range, the exact range must be removed as is.
1475 * <p>
1476 * The changes are applied asynchronously and may not have been applied by the time the method
1477 * returns. Apps will be notified about any changes that apply to them via
1478 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1479 * effect.
1480 * <p>
lucaslin3ba7cc22022-12-19 02:35:33 +00001481 * This method will block the specified UIDs from accessing non-VPN networks, but does not
1482 * affect what the UIDs get as their default network.
1483 * Compare {@link #setVpnDefaultForUids(String, Collection)}, which declares that the UIDs
1484 * should only have a VPN as their default network, but does not block them from accessing other
1485 * networks if they request them explicitly with the {@link Network} API.
1486 * <p>
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001487 * This method should be called only by the VPN code.
1488 *
1489 * @param ranges the UID ranges to restrict
1490 * @param requireVpn whether the specified UID ranges must use a VPN
1491 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001492 * @hide
1493 */
1494 @RequiresPermission(anyOf = {
1495 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001496 android.Manifest.permission.NETWORK_STACK,
1497 android.Manifest.permission.NETWORK_SETTINGS})
1498 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001499 public void setRequireVpnForUids(boolean requireVpn,
1500 @NonNull Collection<Range<Integer>> ranges) {
1501 Objects.requireNonNull(ranges);
1502 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1503 // This method is not necessarily expected to be used outside the system server, so
1504 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1505 // stack process, or by tests.
lucaslin3ba7cc22022-12-19 02:35:33 +00001506 final UidRange[] rangesArray = getUidRangeArray(ranges);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001507 try {
1508 mService.setRequireVpnForUids(requireVpn, rangesArray);
1509 } catch (RemoteException e) {
1510 throw e.rethrowFromSystemServer();
1511 }
1512 }
1513
1514 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001515 * Inform the system that this VPN session should manage the passed UIDs.
1516 *
1517 * A VPN with the specified session ID may call this method to inform the system that the UIDs
1518 * in the specified range are subject to a VPN.
1519 * When this is called, the system will only choose a VPN for the default network of the UIDs in
1520 * the specified ranges.
1521 *
1522 * This method declares that the UIDs in the range will only have a VPN for their default
1523 * network, but does not block the UIDs from accessing other networks (permissions allowing) by
1524 * explicitly requesting it with the {@link Network} API.
1525 * Compare {@link #setRequireVpnForUids(boolean, Collection)}, which does not affect what
1526 * network the UIDs get as default, but will block them from accessing non-VPN networks.
1527 *
1528 * @param session The VPN session which manages the passed UIDs.
1529 * @param ranges The uid ranges which will treat VPN as their only default network.
1530 *
1531 * @hide
1532 */
1533 @RequiresPermission(anyOf = {
1534 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1535 android.Manifest.permission.NETWORK_STACK,
1536 android.Manifest.permission.NETWORK_SETTINGS})
1537 @SystemApi(client = MODULE_LIBRARIES)
1538 public void setVpnDefaultForUids(@NonNull String session,
1539 @NonNull Collection<Range<Integer>> ranges) {
1540 Objects.requireNonNull(ranges);
1541 final UidRange[] rangesArray = getUidRangeArray(ranges);
1542 try {
1543 mService.setVpnNetworkPreference(session, rangesArray);
1544 } catch (RemoteException e) {
1545 throw e.rethrowFromSystemServer();
1546 }
1547 }
1548
1549 /**
chiachangwange0192a72023-02-06 13:25:01 +00001550 * Temporarily set automaticOnOff keeplaive TCP polling alarm timer to 1 second.
1551 *
1552 * TODO: Remove this when the TCP polling design is replaced with callback.
Jean Chalard17cbf062023-02-13 05:07:48 +00001553 * @param timeMs The time of expiry, with System.currentTimeMillis() base. The value should be
1554 * set no more than 5 minutes in the future.
chiachangwange0192a72023-02-06 13:25:01 +00001555 * @hide
1556 */
1557 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
1558 try {
1559 mService.setTestLowTcpPollingTimerForKeepalive(timeMs);
1560 } catch (RemoteException e) {
1561 throw e.rethrowFromSystemServer();
1562 }
1563 }
1564
1565 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001566 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1567 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1568 * but is still supported for backwards compatibility.
1569 * <p>
1570 * This type of VPN is assumed always to use the system default network, and must always declare
1571 * exactly one underlying network, which is the network that was the default when the VPN
1572 * connected.
1573 * <p>
1574 * Calling this method with {@code true} enables legacy behaviour, specifically:
1575 * <ul>
1576 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1577 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1578 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1579 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1580 * underlying the VPN.</li>
1581 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1582 * similarly replaced by the VPN network state.</li>
1583 * <li>Information on current network interfaces passed to NetworkStatsService will not
1584 * include any VPN interfaces.</li>
1585 * </ul>
1586 *
1587 * @param enabled whether legacy lockdown VPN is enabled or disabled
1588 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001589 * @hide
1590 */
1591 @RequiresPermission(anyOf = {
1592 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001593 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001594 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001595 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001596 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1597 try {
1598 mService.setLegacyLockdownVpnEnabled(enabled);
1599 } catch (RemoteException e) {
1600 throw e.rethrowFromSystemServer();
1601 }
1602 }
1603
1604 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001605 * Returns details about the currently active default data network for a given uid.
1606 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001607 *
1608 * @return a {@link NetworkInfo} object for the current default network
1609 * for the given uid or {@code null} if no default network is
1610 * available for the specified uid.
1611 *
1612 * {@hide}
1613 */
1614 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1615 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1616 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1617 return getActiveNetworkInfoForUid(uid, false);
1618 }
1619
1620 /** {@hide} */
1621 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1622 try {
1623 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1624 } catch (RemoteException e) {
1625 throw e.rethrowFromSystemServer();
1626 }
1627 }
1628
1629 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001630 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001631 *
1632 * @param networkType integer specifying which networkType in
1633 * which you're interested.
1634 * @return a {@link NetworkInfo} object for the requested
1635 * network type or {@code null} if the type is not
1636 * supported by the device. If {@code networkType} is
1637 * TYPE_VPN and a VPN is active for the calling app,
1638 * then this method will try to return one of the
1639 * underlying networks for the VPN or null if the
1640 * VPN agent didn't specify any.
1641 *
1642 * @deprecated This method does not support multiple connected networks
1643 * of the same type. Use {@link #getAllNetworks} and
1644 * {@link #getNetworkInfo(android.net.Network)} instead.
1645 */
1646 @Deprecated
1647 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1648 @Nullable
1649 public NetworkInfo getNetworkInfo(int networkType) {
1650 try {
1651 return mService.getNetworkInfo(networkType);
1652 } catch (RemoteException e) {
1653 throw e.rethrowFromSystemServer();
1654 }
1655 }
1656
1657 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001658 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001659 *
1660 * @param network {@link Network} specifying which network
1661 * in which you're interested.
1662 * @return a {@link NetworkInfo} object for the requested
1663 * network or {@code null} if the {@code Network}
1664 * is not valid.
1665 * @deprecated See {@link NetworkInfo}.
1666 */
1667 @Deprecated
1668 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1669 @Nullable
1670 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1671 return getNetworkInfoForUid(network, Process.myUid(), false);
1672 }
1673
1674 /** {@hide} */
1675 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1676 try {
1677 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1678 } catch (RemoteException e) {
1679 throw e.rethrowFromSystemServer();
1680 }
1681 }
1682
1683 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001684 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001685 *
1686 * @return an array of {@link NetworkInfo} objects. Check each
1687 * {@link NetworkInfo#getType} for which type each applies.
1688 *
1689 * @deprecated This method does not support multiple connected networks
1690 * of the same type. Use {@link #getAllNetworks} and
1691 * {@link #getNetworkInfo(android.net.Network)} instead.
1692 */
1693 @Deprecated
1694 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1695 @NonNull
1696 public NetworkInfo[] getAllNetworkInfo() {
1697 try {
1698 return mService.getAllNetworkInfo();
1699 } catch (RemoteException e) {
1700 throw e.rethrowFromSystemServer();
1701 }
1702 }
1703
1704 /**
junyulaib1211372021-03-03 12:09:05 +08001705 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1706 * connected.
1707 * @hide
1708 */
1709 @SystemApi(client = MODULE_LIBRARIES)
1710 @RequiresPermission(anyOf = {
1711 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1712 android.Manifest.permission.NETWORK_STACK,
1713 android.Manifest.permission.NETWORK_SETTINGS})
1714 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001715 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001716 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001717 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001718 } catch (RemoteException e) {
1719 throw e.rethrowFromSystemServer();
1720 }
1721 }
1722
1723 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001724 * Returns the {@link Network} object currently serving a given type, or
1725 * null if the given type is not connected.
1726 *
1727 * @hide
1728 * @deprecated This method does not support multiple connected networks
1729 * of the same type. Use {@link #getAllNetworks} and
1730 * {@link #getNetworkInfo(android.net.Network)} instead.
1731 */
1732 @Deprecated
1733 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1734 @UnsupportedAppUsage
1735 public Network getNetworkForType(int networkType) {
1736 try {
1737 return mService.getNetworkForType(networkType);
1738 } catch (RemoteException e) {
1739 throw e.rethrowFromSystemServer();
1740 }
1741 }
1742
1743 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001744 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001745 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001746 * @deprecated This method does not provide any notification of network state changes, forcing
1747 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1748 * Apps should use methods such as
1749 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1750 * Apps that desire to obtain information about networks that do not apply to them
1751 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1752 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001753 * @return an array of {@link Network} objects.
1754 */
1755 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1756 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001757 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001758 public Network[] getAllNetworks() {
1759 try {
1760 return mService.getAllNetworks();
1761 } catch (RemoteException e) {
1762 throw e.rethrowFromSystemServer();
1763 }
1764 }
1765
1766 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001767 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001768 * the Networks that applications run by the given user will use by default.
1769 * @hide
1770 */
1771 @UnsupportedAppUsage
1772 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1773 try {
1774 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001775 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001776 } catch (RemoteException e) {
1777 throw e.rethrowFromSystemServer();
1778 }
1779 }
1780
1781 /**
1782 * Returns the IP information for the current default network.
1783 *
1784 * @return a {@link LinkProperties} object describing the IP info
1785 * for the current default network, or {@code null} if there
1786 * is no current default network.
1787 *
1788 * {@hide}
1789 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1790 * value of {@link #getActiveNetwork()} instead. In particular,
1791 * this method will return non-null LinkProperties even if the
1792 * app is blocked by policy from using this network.
1793 */
1794 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1795 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1796 public LinkProperties getActiveLinkProperties() {
1797 try {
1798 return mService.getActiveLinkProperties();
1799 } catch (RemoteException e) {
1800 throw e.rethrowFromSystemServer();
1801 }
1802 }
1803
1804 /**
1805 * Returns the IP information for a given network type.
1806 *
1807 * @param networkType the network type of interest.
1808 * @return a {@link LinkProperties} object describing the IP info
1809 * for the given networkType, or {@code null} if there is
1810 * no current default network.
1811 *
1812 * {@hide}
1813 * @deprecated This method does not support multiple connected networks
1814 * of the same type. Use {@link #getAllNetworks},
1815 * {@link #getNetworkInfo(android.net.Network)}, and
1816 * {@link #getLinkProperties(android.net.Network)} instead.
1817 */
1818 @Deprecated
1819 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1820 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1821 public LinkProperties getLinkProperties(int networkType) {
1822 try {
1823 return mService.getLinkPropertiesForType(networkType);
1824 } catch (RemoteException e) {
1825 throw e.rethrowFromSystemServer();
1826 }
1827 }
1828
1829 /**
1830 * Get the {@link LinkProperties} for the given {@link Network}. This
1831 * will return {@code null} if the network is unknown.
1832 *
1833 * @param network The {@link Network} object identifying the network in question.
1834 * @return The {@link LinkProperties} for the network, or {@code null}.
1835 */
1836 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1837 @Nullable
1838 public LinkProperties getLinkProperties(@Nullable Network network) {
1839 try {
1840 return mService.getLinkProperties(network);
1841 } catch (RemoteException e) {
1842 throw e.rethrowFromSystemServer();
1843 }
1844 }
1845
1846 /**
lucaslinc582d502022-01-27 09:07:00 +08001847 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001848 *
lucaslinc582d502022-01-27 09:07:00 +08001849 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1850 * given package, considering its permissions.
1851 *
1852 * @param lp A {@link LinkProperties} which will be redacted.
1853 * @param uid The target uid.
1854 * @param packageName The name of the package, for appops logging.
1855 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1856 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1857 * @hide
1858 */
1859 @RequiresPermission(anyOf = {
1860 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1861 android.Manifest.permission.NETWORK_STACK,
1862 android.Manifest.permission.NETWORK_SETTINGS})
1863 @SystemApi(client = MODULE_LIBRARIES)
1864 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001865 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001866 @NonNull String packageName) {
1867 try {
lucaslind2b06132022-03-02 10:56:57 +08001868 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001869 lp, uid, packageName, getAttributionTag());
1870 } catch (RemoteException e) {
1871 throw e.rethrowFromSystemServer();
1872 }
1873 }
1874
1875 /**
1876 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1877 *
1878 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1879 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1880 * sensitive information. To retrieve this location sensitive information (subject to
1881 * the caller's location permissions), use a {@link NetworkCallback} with the
1882 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1883 *
1884 * This method returns {@code null} if the network is unknown or if the |network| argument
1885 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001886 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001887 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001888 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001889 */
1890 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1891 @Nullable
1892 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1893 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001894 return mService.getNetworkCapabilities(
1895 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001896 } catch (RemoteException e) {
1897 throw e.rethrowFromSystemServer();
1898 }
1899 }
1900
1901 /**
lucaslinc582d502022-01-27 09:07:00 +08001902 * Redact {@link NetworkCapabilities} for a given package.
1903 *
1904 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001905 * to the given package, considering its permissions. If the passed capabilities contain
1906 * location-sensitive information, they will be redacted to the correct degree for the location
1907 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1908 * that level of location. If the UID holds no location permission, the returned object will
1909 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001910 *
1911 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1912 * @param uid The target uid.
1913 * @param packageName The name of the package, for appops logging.
1914 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1915 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1916 * @hide
1917 */
1918 @RequiresPermission(anyOf = {
1919 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1920 android.Manifest.permission.NETWORK_STACK,
1921 android.Manifest.permission.NETWORK_SETTINGS})
1922 @SystemApi(client = MODULE_LIBRARIES)
1923 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001924 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001925 @NonNull NetworkCapabilities nc,
1926 int uid, @NonNull String packageName) {
1927 try {
lucaslind2b06132022-03-02 10:56:57 +08001928 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001929 getAttributionTag());
1930 } catch (RemoteException e) {
1931 throw e.rethrowFromSystemServer();
1932 }
1933 }
1934
1935 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001936 * Gets a URL that can be used for resolving whether a captive portal is present.
1937 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1938 * portal is present.
1939 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1940 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1941 *
1942 * The system network validation may be using different strategies to detect captive portals,
1943 * so this method does not necessarily return a URL used by the system. It only returns a URL
1944 * that may be relevant for other components trying to detect captive portals.
1945 *
1946 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001947 * @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 +09001948 * system.
1949 */
1950 @Deprecated
1951 @SystemApi
1952 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1953 public String getCaptivePortalServerUrl() {
1954 try {
1955 return mService.getCaptivePortalServerUrl();
1956 } catch (RemoteException e) {
1957 throw e.rethrowFromSystemServer();
1958 }
1959 }
1960
1961 /**
1962 * Tells the underlying networking system that the caller wants to
1963 * begin using the named feature. The interpretation of {@code feature}
1964 * is completely up to each networking implementation.
1965 *
1966 * <p>This method requires the caller to hold either the
1967 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1968 * or the ability to modify system settings as determined by
1969 * {@link android.provider.Settings.System#canWrite}.</p>
1970 *
1971 * @param networkType specifies which network the request pertains to
1972 * @param feature the name of the feature to be used
1973 * @return an integer value representing the outcome of the request.
1974 * The interpretation of this value is specific to each networking
1975 * implementation+feature combination, except that the value {@code -1}
1976 * always indicates failure.
1977 *
1978 * @deprecated Deprecated in favor of the cleaner
1979 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1980 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1981 * throw {@code UnsupportedOperationException} if called.
1982 * @removed
1983 */
1984 @Deprecated
1985 public int startUsingNetworkFeature(int networkType, String feature) {
1986 checkLegacyRoutingApiAccess();
1987 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1988 if (netCap == null) {
1989 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1990 feature);
1991 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1992 }
1993
1994 NetworkRequest request = null;
1995 synchronized (sLegacyRequests) {
1996 LegacyRequest l = sLegacyRequests.get(netCap);
1997 if (l != null) {
1998 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1999 renewRequestLocked(l);
2000 if (l.currentNetwork != null) {
2001 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
2002 } else {
2003 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
2004 }
2005 }
2006
2007 request = requestNetworkForFeatureLocked(netCap);
2008 }
2009 if (request != null) {
2010 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
2011 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
2012 } else {
2013 Log.d(TAG, " request Failed");
2014 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
2015 }
2016 }
2017
2018 /**
2019 * Tells the underlying networking system that the caller is finished
2020 * using the named feature. The interpretation of {@code feature}
2021 * is completely up to each networking implementation.
2022 *
2023 * <p>This method requires the caller to hold either the
2024 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2025 * or the ability to modify system settings as determined by
2026 * {@link android.provider.Settings.System#canWrite}.</p>
2027 *
2028 * @param networkType specifies which network the request pertains to
2029 * @param feature the name of the feature that is no longer needed
2030 * @return an integer value representing the outcome of the request.
2031 * The interpretation of this value is specific to each networking
2032 * implementation+feature combination, except that the value {@code -1}
2033 * always indicates failure.
2034 *
2035 * @deprecated Deprecated in favor of the cleaner
2036 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
2037 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2038 * throw {@code UnsupportedOperationException} if called.
2039 * @removed
2040 */
2041 @Deprecated
2042 public int stopUsingNetworkFeature(int networkType, String feature) {
2043 checkLegacyRoutingApiAccess();
2044 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
2045 if (netCap == null) {
2046 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
2047 feature);
2048 return -1;
2049 }
2050
2051 if (removeRequestForFeature(netCap)) {
2052 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
2053 }
2054 return 1;
2055 }
2056
2057 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2058 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
2059 if (networkType == TYPE_MOBILE) {
2060 switch (feature) {
2061 case "enableCBS":
2062 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
2063 case "enableDUN":
2064 case "enableDUNAlways":
2065 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
2066 case "enableFOTA":
2067 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
2068 case "enableHIPRI":
2069 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
2070 case "enableIMS":
2071 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
2072 case "enableMMS":
2073 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
2074 case "enableSUPL":
2075 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
2076 default:
2077 return null;
2078 }
2079 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
2080 return networkCapabilitiesForType(TYPE_WIFI_P2P);
2081 }
2082 return null;
2083 }
2084
2085 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
2086 if (netCap == null) return TYPE_NONE;
2087 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
2088 return TYPE_MOBILE_CBS;
2089 }
2090 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2091 return TYPE_MOBILE_IMS;
2092 }
2093 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
2094 return TYPE_MOBILE_FOTA;
2095 }
2096 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
2097 return TYPE_MOBILE_DUN;
2098 }
2099 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
2100 return TYPE_MOBILE_SUPL;
2101 }
2102 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2103 return TYPE_MOBILE_MMS;
2104 }
2105 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
2106 return TYPE_MOBILE_HIPRI;
2107 }
2108 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
2109 return TYPE_WIFI_P2P;
2110 }
2111 return TYPE_NONE;
2112 }
2113
2114 private static class LegacyRequest {
2115 NetworkCapabilities networkCapabilities;
2116 NetworkRequest networkRequest;
2117 int expireSequenceNumber;
2118 Network currentNetwork;
2119 int delay = -1;
2120
2121 private void clearDnsBinding() {
2122 if (currentNetwork != null) {
2123 currentNetwork = null;
2124 setProcessDefaultNetworkForHostResolution(null);
2125 }
2126 }
2127
2128 NetworkCallback networkCallback = new NetworkCallback() {
2129 @Override
2130 public void onAvailable(Network network) {
2131 currentNetwork = network;
2132 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
2133 setProcessDefaultNetworkForHostResolution(network);
2134 }
2135 @Override
2136 public void onLost(Network network) {
2137 if (network.equals(currentNetwork)) clearDnsBinding();
2138 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2139 }
2140 };
2141 }
2142
2143 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2144 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2145 new HashMap<>();
2146
2147 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2148 synchronized (sLegacyRequests) {
2149 LegacyRequest l = sLegacyRequests.get(netCap);
2150 if (l != null) return l.networkRequest;
2151 }
2152 return null;
2153 }
2154
2155 private void renewRequestLocked(LegacyRequest l) {
2156 l.expireSequenceNumber++;
2157 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2158 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2159 }
2160
2161 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2162 int ourSeqNum = -1;
2163 synchronized (sLegacyRequests) {
2164 LegacyRequest l = sLegacyRequests.get(netCap);
2165 if (l == null) return;
2166 ourSeqNum = l.expireSequenceNumber;
2167 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2168 }
2169 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2170 }
2171
2172 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2173 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2174 int delay = -1;
2175 int type = legacyTypeForNetworkCapabilities(netCap);
2176 try {
2177 delay = mService.getRestoreDefaultNetworkDelay(type);
2178 } catch (RemoteException e) {
2179 throw e.rethrowFromSystemServer();
2180 }
2181 LegacyRequest l = new LegacyRequest();
2182 l.networkCapabilities = netCap;
2183 l.delay = delay;
2184 l.expireSequenceNumber = 0;
2185 l.networkRequest = sendRequestForNetwork(
2186 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2187 if (l.networkRequest == null) return null;
2188 sLegacyRequests.put(netCap, l);
2189 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2190 return l.networkRequest;
2191 }
2192
2193 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2194 if (delay >= 0) {
2195 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2196 CallbackHandler handler = getDefaultHandler();
2197 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2198 handler.sendMessageDelayed(msg, delay);
2199 }
2200 }
2201
2202 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2203 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2204 final LegacyRequest l;
2205 synchronized (sLegacyRequests) {
2206 l = sLegacyRequests.remove(netCap);
2207 }
2208 if (l == null) return false;
2209 unregisterNetworkCallback(l.networkCallback);
2210 l.clearDnsBinding();
2211 return true;
2212 }
2213
2214 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2215 static {
2216 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2217 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2218 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2219 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2220 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2221 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2222 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2223 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2224 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2225 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2226 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2227 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2228 }
2229
2230 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2231 static {
2232 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2233 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2234 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2235 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2236 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2237 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2238 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2239 }
2240
2241 /**
2242 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2243 * instance suitable for registering a request or callback. Throws an
2244 * IllegalArgumentException if no mapping from the legacy type to
2245 * NetworkCapabilities is known.
2246 *
2247 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2248 * to find the network instead.
2249 * @hide
2250 */
2251 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2252 final NetworkCapabilities nc = new NetworkCapabilities();
2253
2254 // Map from type to transports.
2255 final int NOT_FOUND = -1;
2256 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002257 if (transport == NOT_FOUND) {
2258 throw new IllegalArgumentException("unknown legacy type: " + type);
2259 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002260 nc.addTransportType(transport);
2261
2262 // Map from type to capabilities.
2263 nc.addCapability(sLegacyTypeToCapability.get(
2264 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2265 nc.maybeMarkCapabilitiesRestricted();
2266 return nc;
2267 }
2268
2269 /** @hide */
2270 public static class PacketKeepaliveCallback {
2271 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2272 public PacketKeepaliveCallback() {
2273 }
2274 /** The requested keepalive was successfully started. */
2275 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2276 public void onStarted() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002277 /** The keepalive was resumed after being paused by the system. */
2278 public void onResumed() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002279 /** The keepalive was successfully stopped. */
2280 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2281 public void onStopped() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002282 /** The keepalive was paused automatically by the system. */
2283 public void onPaused() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002284 /** An error occurred. */
2285 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2286 public void onError(int error) {}
2287 }
2288
2289 /**
2290 * Allows applications to request that the system periodically send specific packets on their
2291 * behalf, using hardware offload to save battery power.
2292 *
2293 * To request that the system send keepalives, call one of the methods that return a
2294 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2295 * passing in a non-null callback. If the callback is successfully started, the callback's
2296 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2297 * specifying one of the {@code ERROR_*} constants in this class.
2298 *
2299 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2300 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2301 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2302 *
2303 * @deprecated Use {@link SocketKeepalive} instead.
2304 *
2305 * @hide
2306 */
2307 public class PacketKeepalive {
2308
2309 private static final String TAG = "PacketKeepalive";
2310
2311 /** @hide */
2312 public static final int SUCCESS = 0;
2313
2314 /** @hide */
2315 public static final int NO_KEEPALIVE = -1;
2316
2317 /** @hide */
2318 public static final int BINDER_DIED = -10;
2319
2320 /** The specified {@code Network} is not connected. */
2321 public static final int ERROR_INVALID_NETWORK = -20;
2322 /** The specified IP addresses are invalid. For example, the specified source IP address is
2323 * not configured on the specified {@code Network}. */
2324 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2325 /** The requested port is invalid. */
2326 public static final int ERROR_INVALID_PORT = -22;
2327 /** The packet length is invalid (e.g., too long). */
2328 public static final int ERROR_INVALID_LENGTH = -23;
2329 /** The packet transmission interval is invalid (e.g., too short). */
2330 public static final int ERROR_INVALID_INTERVAL = -24;
2331
2332 /** The hardware does not support this request. */
2333 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2334 /** The hardware returned an error. */
2335 public static final int ERROR_HARDWARE_ERROR = -31;
2336
2337 /** The NAT-T destination port for IPsec */
2338 public static final int NATT_PORT = 4500;
2339
2340 /** The minimum interval in seconds between keepalive packet transmissions */
2341 public static final int MIN_INTERVAL = 10;
2342
2343 private final Network mNetwork;
2344 private final ISocketKeepaliveCallback mCallback;
2345 private final ExecutorService mExecutor;
2346
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002347 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2348 public void stop() {
2349 try {
2350 mExecutor.execute(() -> {
2351 try {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002352 mService.stopKeepalive(mCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002353 } catch (RemoteException e) {
2354 Log.e(TAG, "Error stopping packet keepalive: ", e);
2355 throw e.rethrowFromSystemServer();
2356 }
2357 });
2358 } catch (RejectedExecutionException e) {
2359 // The internal executor has already stopped due to previous event.
2360 }
2361 }
2362
2363 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002364 Objects.requireNonNull(network, "network cannot be null");
2365 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002366 mNetwork = network;
2367 mExecutor = Executors.newSingleThreadExecutor();
2368 mCallback = new ISocketKeepaliveCallback.Stub() {
2369 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002370 public void onStarted() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002371 final long token = Binder.clearCallingIdentity();
2372 try {
2373 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002374 callback.onStarted();
2375 });
2376 } finally {
2377 Binder.restoreCallingIdentity(token);
2378 }
2379 }
2380
2381 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002382 public void onResumed() {
2383 final long token = Binder.clearCallingIdentity();
2384 try {
2385 mExecutor.execute(() -> {
2386 callback.onResumed();
2387 });
2388 } finally {
2389 Binder.restoreCallingIdentity(token);
2390 }
2391 }
2392
2393 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002394 public void onStopped() {
2395 final long token = Binder.clearCallingIdentity();
2396 try {
2397 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002398 callback.onStopped();
2399 });
2400 } finally {
2401 Binder.restoreCallingIdentity(token);
2402 }
2403 mExecutor.shutdown();
2404 }
2405
2406 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002407 public void onPaused() {
2408 final long token = Binder.clearCallingIdentity();
2409 try {
2410 mExecutor.execute(() -> {
2411 callback.onPaused();
2412 });
2413 } finally {
2414 Binder.restoreCallingIdentity(token);
2415 }
2416 mExecutor.shutdown();
2417 }
2418
2419 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002420 public void onError(int error) {
2421 final long token = Binder.clearCallingIdentity();
2422 try {
2423 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002424 callback.onError(error);
2425 });
2426 } finally {
2427 Binder.restoreCallingIdentity(token);
2428 }
2429 mExecutor.shutdown();
2430 }
2431
2432 @Override
2433 public void onDataReceived() {
2434 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2435 // this callback when data is received.
2436 }
2437 };
2438 }
2439 }
2440
2441 /**
2442 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2443 *
2444 * @deprecated Use {@link #createSocketKeepalive} instead.
2445 *
2446 * @hide
2447 */
2448 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2449 public PacketKeepalive startNattKeepalive(
2450 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2451 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2452 final PacketKeepalive k = new PacketKeepalive(network, callback);
2453 try {
2454 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2455 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2456 } catch (RemoteException e) {
2457 Log.e(TAG, "Error starting packet keepalive: ", e);
2458 throw e.rethrowFromSystemServer();
2459 }
2460 return k;
2461 }
2462
2463 // Construct an invalid fd.
2464 private ParcelFileDescriptor createInvalidFd() {
2465 final int invalidFd = -1;
2466 return ParcelFileDescriptor.adoptFd(invalidFd);
2467 }
2468
2469 /**
2470 * Request that keepalives be started on a IPsec NAT-T socket.
2471 *
2472 * @param network The {@link Network} the socket is on.
2473 * @param socket The socket that needs to be kept alive.
2474 * @param source The source address of the {@link UdpEncapsulationSocket}.
2475 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2476 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2477 * must run callback sequentially, otherwise the order of callbacks cannot be
2478 * guaranteed.
2479 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2480 * changes. Must be extended by applications that use this API.
2481 *
2482 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2483 * given socket.
2484 **/
2485 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2486 @NonNull UdpEncapsulationSocket socket,
2487 @NonNull InetAddress source,
2488 @NonNull InetAddress destination,
2489 @NonNull @CallbackExecutor Executor executor,
2490 @NonNull Callback callback) {
2491 ParcelFileDescriptor dup;
2492 try {
2493 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2494 // which cannot be obtained by the app process.
2495 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2496 } catch (IOException ignored) {
2497 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2498 // ERROR_INVALID_SOCKET.
2499 dup = createInvalidFd();
2500 }
2501 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2502 destination, executor, callback);
2503 }
2504
2505 /**
2506 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2507 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2508 *
2509 * @param network The {@link Network} the socket is on.
2510 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2511 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2512 * from that port.
2513 * @param source The source address of the {@link UdpEncapsulationSocket}.
2514 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2515 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2516 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2517 * must run callback sequentially, otherwise the order of callbacks cannot be
2518 * guaranteed.
2519 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2520 * changes. Must be extended by applications that use this API.
2521 *
2522 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2523 * given socket.
2524 * @hide
2525 */
2526 @SystemApi
2527 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2528 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2529 @NonNull ParcelFileDescriptor pfd,
2530 @NonNull InetAddress source,
2531 @NonNull InetAddress destination,
2532 @NonNull @CallbackExecutor Executor executor,
2533 @NonNull Callback callback) {
2534 ParcelFileDescriptor dup;
2535 try {
2536 // TODO: Consider remove unnecessary dup.
2537 dup = pfd.dup();
2538 } catch (IOException ignored) {
2539 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2540 // ERROR_INVALID_SOCKET.
2541 dup = createInvalidFd();
2542 }
2543 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002544 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002545 }
2546
2547 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002548 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002549 *
2550 * @param network The {@link Network} the socket is on.
2551 * @param socket The socket that needs to be kept alive.
2552 * @param executor The executor on which callback will be invoked. This implementation assumes
2553 * the provided {@link Executor} runs the callbacks in sequence with no
2554 * concurrency. Failing this, no guarantee of correctness can be made. It is
2555 * the responsibility of the caller to ensure the executor provides this
2556 * guarantee. A simple way of creating such an executor is with the standard
2557 * tool {@code Executors.newSingleThreadExecutor}.
2558 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2559 * changes. Must be extended by applications that use this API.
2560 *
2561 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2562 * given socket.
2563 * @hide
2564 */
2565 @SystemApi
2566 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2567 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2568 @NonNull Socket socket,
Sherri Lin443b7182023-02-08 04:49:29 +01002569 @NonNull @CallbackExecutor Executor executor,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002570 @NonNull Callback callback) {
2571 ParcelFileDescriptor dup;
2572 try {
2573 dup = ParcelFileDescriptor.fromSocket(socket);
2574 } catch (UncheckedIOException ignored) {
2575 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2576 // ERROR_INVALID_SOCKET.
2577 dup = createInvalidFd();
2578 }
2579 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2580 }
2581
2582 /**
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +09002583 * Get the supported keepalive count for each transport configured in resource overlays.
2584 *
2585 * @return An array of supported keepalive count for each transport type.
2586 * @hide
2587 */
2588 @RequiresPermission(anyOf = { android.Manifest.permission.NETWORK_SETTINGS,
2589 // CTS 13 used QUERY_ALL_PACKAGES to get the resource value, which was implemented
2590 // as below in KeepaliveUtils. Also allow that permission so that KeepaliveUtils can
2591 // use this method and avoid breaking released CTS. Apps that have this permission
2592 // can query the resource themselves anyway.
2593 android.Manifest.permission.QUERY_ALL_PACKAGES })
2594 public int[] getSupportedKeepalives() {
2595 try {
2596 return mService.getSupportedKeepalives();
2597 } catch (RemoteException e) {
2598 throw e.rethrowFromSystemServer();
2599 }
2600 }
2601
2602 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002603 * Ensure that a network route exists to deliver traffic to the specified
2604 * host via the specified network interface. An attempt to add a route that
2605 * already exists is ignored, but treated as successful.
2606 *
2607 * <p>This method requires the caller to hold either the
2608 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2609 * or the ability to modify system settings as determined by
2610 * {@link android.provider.Settings.System#canWrite}.</p>
2611 *
2612 * @param networkType the type of the network over which traffic to the specified
2613 * host is to be routed
2614 * @param hostAddress the IP address of the host to which the route is desired
2615 * @return {@code true} on success, {@code false} on failure
2616 *
2617 * @deprecated Deprecated in favor of the
2618 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2619 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2620 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2621 * throw {@code UnsupportedOperationException} if called.
2622 * @removed
2623 */
2624 @Deprecated
2625 public boolean requestRouteToHost(int networkType, int hostAddress) {
2626 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2627 }
2628
2629 /**
2630 * Ensure that a network route exists to deliver traffic to the specified
2631 * host via the specified network interface. An attempt to add a route that
2632 * already exists is ignored, but treated as successful.
2633 *
2634 * <p>This method requires the caller to hold either the
2635 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2636 * or the ability to modify system settings as determined by
2637 * {@link android.provider.Settings.System#canWrite}.</p>
2638 *
2639 * @param networkType the type of the network over which traffic to the specified
2640 * host is to be routed
2641 * @param hostAddress the IP address of the host to which the route is desired
2642 * @return {@code true} on success, {@code false} on failure
2643 * @hide
2644 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2645 * {@link #bindProcessToNetwork} API.
2646 */
2647 @Deprecated
2648 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002649 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002650 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2651 checkLegacyRoutingApiAccess();
2652 try {
2653 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2654 mContext.getOpPackageName(), getAttributionTag());
2655 } catch (RemoteException e) {
2656 throw e.rethrowFromSystemServer();
2657 }
2658 }
2659
2660 /**
2661 * @return the context's attribution tag
2662 */
2663 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2664 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002665 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002666 }
2667
2668 /**
2669 * Returns the value of the setting for background data usage. If false,
2670 * applications should not use the network if the application is not in the
2671 * foreground. Developers should respect this setting, and check the value
2672 * of this before performing any background data operations.
2673 * <p>
2674 * All applications that have background services that use the network
2675 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2676 * <p>
2677 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2678 * background data depends on several combined factors, and this method will
2679 * always return {@code true}. Instead, when background data is unavailable,
2680 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2681 *
2682 * @return Whether background data usage is allowed.
2683 */
2684 @Deprecated
2685 public boolean getBackgroundDataSetting() {
2686 // assume that background data is allowed; final authority is
2687 // NetworkInfo which may be blocked.
2688 return true;
2689 }
2690
2691 /**
2692 * Sets the value of the setting for background data usage.
2693 *
2694 * @param allowBackgroundData Whether an application should use data while
2695 * it is in the background.
2696 *
2697 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2698 * @see #getBackgroundDataSetting()
2699 * @hide
2700 */
2701 @Deprecated
2702 @UnsupportedAppUsage
2703 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2704 // ignored
2705 }
2706
2707 /**
2708 * @hide
2709 * @deprecated Talk to TelephonyManager directly
2710 */
2711 @Deprecated
2712 @UnsupportedAppUsage
2713 public boolean getMobileDataEnabled() {
2714 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2715 if (tm != null) {
2716 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2717 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2718 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2719 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2720 + " retVal=" + retVal);
2721 return retVal;
2722 }
2723 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2724 return false;
2725 }
2726
2727 /**
2728 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2729 * to find out when the system default network has gone in to a high power state.
2730 */
2731 public interface OnNetworkActiveListener {
2732 /**
2733 * Called on the main thread of the process to report that the current data network
2734 * has become active, and it is now a good time to perform any pending network
2735 * operations. Note that this listener only tells you when the network becomes
2736 * active; if at any other time you want to know whether it is active (and thus okay
2737 * to initiate network traffic), you can retrieve its instantaneous state with
2738 * {@link ConnectivityManager#isDefaultNetworkActive}.
2739 */
2740 void onNetworkActive();
2741 }
2742
Chiachang Wang2de41682021-09-23 10:46:03 +08002743 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002744 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2745 mNetworkActivityListeners = new ArrayMap<>();
2746
2747 /**
2748 * Start listening to reports when the system's default data network is active, meaning it is
2749 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2750 * to determine the current state of the system's default network after registering the
2751 * listener.
2752 * <p>
2753 * If the process default network has been set with
2754 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2755 * reflect the process's default, but the system default.
2756 *
2757 * @param l The listener to be told when the network is active.
2758 */
2759 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002760 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002761 @Override
2762 public void onNetworkActive() throws RemoteException {
2763 l.onNetworkActive();
2764 }
2765 };
2766
Chiachang Wang2de41682021-09-23 10:46:03 +08002767 synchronized (mNetworkActivityListeners) {
2768 try {
2769 mService.registerNetworkActivityListener(rl);
2770 mNetworkActivityListeners.put(l, rl);
2771 } catch (RemoteException e) {
2772 throw e.rethrowFromSystemServer();
2773 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002774 }
2775 }
2776
2777 /**
2778 * Remove network active listener previously registered with
2779 * {@link #addDefaultNetworkActiveListener}.
2780 *
2781 * @param l Previously registered listener.
2782 */
2783 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002784 synchronized (mNetworkActivityListeners) {
2785 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2786 if (rl == null) {
2787 throw new IllegalArgumentException("Listener was not registered.");
2788 }
2789 try {
2790 mService.unregisterNetworkActivityListener(rl);
2791 mNetworkActivityListeners.remove(l);
2792 } catch (RemoteException e) {
2793 throw e.rethrowFromSystemServer();
2794 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002795 }
2796 }
2797
2798 /**
2799 * Return whether the data network is currently active. An active network means that
2800 * it is currently in a high power state for performing data transmission. On some
2801 * types of networks, it may be expensive to move and stay in such a state, so it is
2802 * more power efficient to batch network traffic together when the radio is already in
2803 * this state. This method tells you whether right now is currently a good time to
2804 * initiate network traffic, as the network is already active.
2805 */
2806 public boolean isDefaultNetworkActive() {
2807 try {
lucaslin709eb842021-01-21 02:04:15 +08002808 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002809 } catch (RemoteException e) {
2810 throw e.rethrowFromSystemServer();
2811 }
2812 }
2813
2814 /**
2815 * {@hide}
2816 */
2817 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002818 this(context, service, true /* newStatic */);
2819 }
2820
2821 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002822 mContext = Objects.requireNonNull(context, "missing context");
2823 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002824 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2825 // different ConnectivityManager, but that's still OK considering its usage.
2826 if (sInstance == null && newStatic) {
2827 final Context appContext = mContext.getApplicationContext();
2828 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2829 // If the application context is null, we're either in the system process or
2830 // it's the application context very early in app initialization. In both these
2831 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2832 // service. http://b/27532714 .
2833 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2834 false /* newStatic */);
2835 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002836 }
2837
2838 /** {@hide} */
2839 @UnsupportedAppUsage
2840 public static ConnectivityManager from(Context context) {
2841 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2842 }
2843
2844 /** @hide */
2845 public NetworkRequest getDefaultRequest() {
2846 try {
2847 // This is not racy as the default request is final in ConnectivityService.
2848 return mService.getDefaultRequest();
2849 } catch (RemoteException e) {
2850 throw e.rethrowFromSystemServer();
2851 }
2852 }
2853
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002854 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002855 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002856 * happened.
2857 *
2858 * @return {@code true} iff the package is allowed to write settings.
2859 */
2860 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2861 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2862 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2863 boolean throwException) {
2864 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002865 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002866 }
2867
2868 /**
2869 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2870 * situations where a Context pointer is unavailable.
2871 * @hide
2872 */
2873 @Deprecated
2874 static ConnectivityManager getInstanceOrNull() {
2875 return sInstance;
2876 }
2877
2878 /**
2879 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2880 * situations where a Context pointer is unavailable.
2881 * @hide
2882 */
2883 @Deprecated
2884 @UnsupportedAppUsage
2885 private static ConnectivityManager getInstance() {
2886 if (getInstanceOrNull() == null) {
2887 throw new IllegalStateException("No ConnectivityManager yet constructed");
2888 }
2889 return getInstanceOrNull();
2890 }
2891
2892 /**
2893 * Get the set of tetherable, available interfaces. This list is limited by
2894 * device configuration and current interface existence.
2895 *
2896 * @return an array of 0 or more Strings of tetherable interface names.
2897 *
2898 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2899 * {@hide}
2900 */
2901 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2902 @UnsupportedAppUsage
2903 @Deprecated
2904 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002905 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002906 }
2907
2908 /**
2909 * Get the set of tethered interfaces.
2910 *
2911 * @return an array of 0 or more String of currently tethered interface names.
2912 *
2913 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2914 * {@hide}
2915 */
2916 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2917 @UnsupportedAppUsage
2918 @Deprecated
2919 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002920 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002921 }
2922
2923 /**
2924 * Get the set of interface names which attempted to tether but
2925 * failed. Re-attempting to tether may cause them to reset to the Tethered
2926 * state. Alternatively, causing the interface to be destroyed and recreated
2927 * may cause them to reset to the available state.
2928 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2929 * information on the cause of the errors.
2930 *
2931 * @return an array of 0 or more String indicating the interface names
2932 * which failed to tether.
2933 *
2934 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2935 * {@hide}
2936 */
2937 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2938 @UnsupportedAppUsage
2939 @Deprecated
2940 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002941 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002942 }
2943
2944 /**
2945 * Get the set of tethered dhcp ranges.
2946 *
2947 * @deprecated This method is not supported.
2948 * TODO: remove this function when all of clients are removed.
2949 * {@hide}
2950 */
2951 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2952 @Deprecated
2953 public String[] getTetheredDhcpRanges() {
2954 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2955 }
2956
2957 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002958 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002959 * on the interface, forward and NAT IP packets and forward DNS requests
2960 * to the best active upstream network interface. Note that if no upstream
2961 * IP network interface is available, dhcp will still run and traffic will be
2962 * allowed between the tethered devices and this device, though upstream net
2963 * access will of course fail until an upstream network interface becomes
2964 * active.
2965 *
2966 * <p>This method requires the caller to hold either the
2967 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2968 * or the ability to modify system settings as determined by
2969 * {@link android.provider.Settings.System#canWrite}.</p>
2970 *
2971 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2972 * and WifiStateMachine which need direct access. All other clients should use
2973 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2974 * logic.</p>
2975 *
2976 * @param iface the interface name to tether.
2977 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2978 * @deprecated Use {@link TetheringManager#startTethering} instead
2979 *
2980 * {@hide}
2981 */
2982 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2983 @Deprecated
2984 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002985 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002986 }
2987
2988 /**
2989 * Stop tethering the named interface.
2990 *
2991 * <p>This method requires the caller to hold either the
2992 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2993 * or the ability to modify system settings as determined by
2994 * {@link android.provider.Settings.System#canWrite}.</p>
2995 *
2996 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2997 * and WifiStateMachine which need direct access. All other clients should use
2998 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2999 * logic.</p>
3000 *
3001 * @param iface the interface name to untether.
3002 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3003 *
3004 * {@hide}
3005 */
3006 @UnsupportedAppUsage
3007 @Deprecated
3008 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003009 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003010 }
3011
3012 /**
3013 * Check if the device allows for tethering. It may be disabled via
3014 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
3015 * due to device configuration.
3016 *
3017 * <p>If this app does not have permission to use this API, it will always
3018 * return false rather than throw an exception.</p>
3019 *
3020 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
3021 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
3022 *
3023 * <p>Otherwise, this method requires the caller to hold the ability to modify system
3024 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
3025 *
3026 * @return a boolean - {@code true} indicating Tethering is supported.
3027 *
3028 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
3029 * {@hide}
3030 */
3031 @SystemApi
3032 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
3033 android.Manifest.permission.WRITE_SETTINGS})
3034 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003035 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003036 }
3037
3038 /**
3039 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
3040 *
3041 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
3042 * @hide
3043 */
3044 @SystemApi
3045 @Deprecated
3046 public static abstract class OnStartTetheringCallback {
3047 /**
3048 * Called when tethering has been successfully started.
3049 */
3050 public void onTetheringStarted() {}
3051
3052 /**
3053 * Called when starting tethering failed.
3054 */
3055 public void onTetheringFailed() {}
3056 }
3057
3058 /**
3059 * Convenient overload for
3060 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
3061 * handler to run on the current thread's {@link Looper}.
3062 *
3063 * @deprecated Use {@link TetheringManager#startTethering} instead.
3064 * @hide
3065 */
3066 @SystemApi
3067 @Deprecated
3068 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3069 public void startTethering(int type, boolean showProvisioningUi,
3070 final OnStartTetheringCallback callback) {
3071 startTethering(type, showProvisioningUi, callback, null);
3072 }
3073
3074 /**
3075 * Runs tether provisioning for the given type if needed and then starts tethering if
3076 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
3077 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
3078 * schedules tether provisioning re-checks if appropriate.
3079 *
3080 * @param type The type of tethering to start. Must be one of
3081 * {@link ConnectivityManager.TETHERING_WIFI},
3082 * {@link ConnectivityManager.TETHERING_USB}, or
3083 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3084 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
3085 * is one. This should be true the first time this function is called and also any time
3086 * the user can see this UI. It gives users information from their carrier about the
3087 * check failing and how they can sign up for tethering if possible.
3088 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
3089 * of the result of trying to tether.
3090 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3091 *
3092 * @deprecated Use {@link TetheringManager#startTethering} instead.
3093 * @hide
3094 */
3095 @SystemApi
3096 @Deprecated
3097 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3098 public void startTethering(int type, boolean showProvisioningUi,
3099 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003100 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003101
3102 final Executor executor = new Executor() {
3103 @Override
3104 public void execute(Runnable command) {
3105 if (handler == null) {
3106 command.run();
3107 } else {
3108 handler.post(command);
3109 }
3110 }
3111 };
3112
3113 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
3114 @Override
3115 public void onTetheringStarted() {
3116 callback.onTetheringStarted();
3117 }
3118
3119 @Override
3120 public void onTetheringFailed(final int error) {
3121 callback.onTetheringFailed();
3122 }
3123 };
3124
3125 final TetheringRequest request = new TetheringRequest.Builder(type)
3126 .setShouldShowEntitlementUi(showProvisioningUi).build();
3127
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003128 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003129 }
3130
3131 /**
3132 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
3133 * applicable.
3134 *
3135 * @param type The type of tethering to stop. Must be one of
3136 * {@link ConnectivityManager.TETHERING_WIFI},
3137 * {@link ConnectivityManager.TETHERING_USB}, or
3138 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3139 *
3140 * @deprecated Use {@link TetheringManager#stopTethering} instead.
3141 * @hide
3142 */
3143 @SystemApi
3144 @Deprecated
3145 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3146 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003147 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003148 }
3149
3150 /**
3151 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
3152 * upstream status.
3153 *
3154 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
3155 * @hide
3156 */
3157 @SystemApi
3158 @Deprecated
3159 public abstract static class OnTetheringEventCallback {
3160
3161 /**
3162 * Called when tethering upstream changed. This can be called multiple times and can be
3163 * called any time.
3164 *
3165 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
3166 * have any upstream.
3167 */
3168 public void onUpstreamChanged(@Nullable Network network) {}
3169 }
3170
3171 @GuardedBy("mTetheringEventCallbacks")
3172 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
3173 mTetheringEventCallbacks = new ArrayMap<>();
3174
3175 /**
3176 * Start listening to tethering change events. Any new added callback will receive the last
3177 * tethering status right away. If callback is registered when tethering has no upstream or
3178 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3179 * with a null argument. The same callback object cannot be registered twice.
3180 *
3181 * @param executor the executor on which callback will be invoked.
3182 * @param callback the callback to be called when tethering has change events.
3183 *
3184 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3185 * @hide
3186 */
3187 @SystemApi
3188 @Deprecated
3189 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3190 public void registerTetheringEventCallback(
3191 @NonNull @CallbackExecutor Executor executor,
3192 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003193 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003194
3195 final TetheringEventCallback tetherCallback =
3196 new TetheringEventCallback() {
3197 @Override
3198 public void onUpstreamChanged(@Nullable Network network) {
3199 callback.onUpstreamChanged(network);
3200 }
3201 };
3202
3203 synchronized (mTetheringEventCallbacks) {
3204 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003205 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003206 }
3207 }
3208
3209 /**
3210 * Remove tethering event callback previously registered with
3211 * {@link #registerTetheringEventCallback}.
3212 *
3213 * @param callback previously registered callback.
3214 *
3215 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3216 * @hide
3217 */
3218 @SystemApi
3219 @Deprecated
3220 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3221 public void unregisterTetheringEventCallback(
3222 @NonNull final OnTetheringEventCallback callback) {
3223 Objects.requireNonNull(callback, "The callback must be non-null");
3224 synchronized (mTetheringEventCallbacks) {
3225 final TetheringEventCallback tetherCallback =
3226 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003227 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003228 }
3229 }
3230
3231
3232 /**
3233 * Get the list of regular expressions that define any tetherable
3234 * USB network interfaces. If USB tethering is not supported by the
3235 * device, this list should be empty.
3236 *
3237 * @return an array of 0 or more regular expression Strings defining
3238 * what interfaces are considered tetherable usb interfaces.
3239 *
3240 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3241 * {@hide}
3242 */
3243 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3244 @UnsupportedAppUsage
3245 @Deprecated
3246 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003247 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003248 }
3249
3250 /**
3251 * Get the list of regular expressions that define any tetherable
3252 * Wifi network interfaces. If Wifi tethering is not supported by the
3253 * device, this list should be empty.
3254 *
3255 * @return an array of 0 or more regular expression Strings defining
3256 * what interfaces are considered tetherable wifi interfaces.
3257 *
3258 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3259 * {@hide}
3260 */
3261 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3262 @UnsupportedAppUsage
3263 @Deprecated
3264 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003265 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003266 }
3267
3268 /**
3269 * Get the list of regular expressions that define any tetherable
3270 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3271 * device, this list should be empty.
3272 *
3273 * @return an array of 0 or more regular expression Strings defining
3274 * what interfaces are considered tetherable bluetooth interfaces.
3275 *
3276 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3277 *TetheringManager.TetheringInterfaceRegexps)} instead.
3278 * {@hide}
3279 */
3280 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3281 @UnsupportedAppUsage
3282 @Deprecated
3283 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003284 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003285 }
3286
3287 /**
3288 * Attempt to both alter the mode of USB and Tethering of USB. A
3289 * utility method to deal with some of the complexity of USB - will
3290 * attempt to switch to Rndis and subsequently tether the resulting
3291 * interface on {@code true} or turn off tethering and switch off
3292 * Rndis on {@code false}.
3293 *
3294 * <p>This method requires the caller to hold either the
3295 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3296 * or the ability to modify system settings as determined by
3297 * {@link android.provider.Settings.System#canWrite}.</p>
3298 *
3299 * @param enable a boolean - {@code true} to enable tethering
3300 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3301 * @deprecated Use {@link TetheringManager#startTethering} instead
3302 *
3303 * {@hide}
3304 */
3305 @UnsupportedAppUsage
3306 @Deprecated
3307 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003308 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003309 }
3310
3311 /**
3312 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3313 * {@hide}
3314 */
3315 @SystemApi
3316 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003317 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003318 /**
3319 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3320 * {@hide}
3321 */
3322 @Deprecated
3323 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3324 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3325 /**
3326 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3327 * {@hide}
3328 */
3329 @Deprecated
3330 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3331 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3332 /**
3333 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3334 * {@hide}
3335 */
3336 @Deprecated
3337 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3338 /**
3339 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3340 * {@hide}
3341 */
3342 @Deprecated
3343 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3344 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3345 /**
3346 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3347 * {@hide}
3348 */
3349 @Deprecated
3350 public static final int TETHER_ERROR_MASTER_ERROR =
3351 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3352 /**
3353 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3354 * {@hide}
3355 */
3356 @Deprecated
3357 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3358 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3359 /**
3360 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3361 * {@hide}
3362 */
3363 @Deprecated
3364 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3365 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3366 /**
3367 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3368 * {@hide}
3369 */
3370 @Deprecated
3371 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3372 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3373 /**
3374 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3375 * {@hide}
3376 */
3377 @Deprecated
3378 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3379 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3380 /**
3381 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3382 * {@hide}
3383 */
3384 @Deprecated
3385 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3386 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3387 /**
3388 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3389 * {@hide}
3390 */
3391 @SystemApi
3392 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003393 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003394 /**
3395 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3396 * {@hide}
3397 */
3398 @Deprecated
3399 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3400 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3401 /**
3402 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3403 * {@hide}
3404 */
3405 @SystemApi
3406 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003407 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003408
3409 /**
3410 * Get a more detailed error code after a Tethering or Untethering
3411 * request asynchronously failed.
3412 *
3413 * @param iface The name of the interface of interest
3414 * @return error The error code of the last error tethering or untethering the named
3415 * interface
3416 *
3417 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3418 * {@hide}
3419 */
3420 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3421 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3422 @Deprecated
3423 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003424 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003425 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3426 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3427 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3428 // instead.
3429 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3430 }
3431 return error;
3432 }
3433
3434 /** @hide */
3435 @Retention(RetentionPolicy.SOURCE)
3436 @IntDef(value = {
3437 TETHER_ERROR_NO_ERROR,
3438 TETHER_ERROR_PROVISION_FAILED,
3439 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3440 })
3441 public @interface EntitlementResultCode {
3442 }
3443
3444 /**
3445 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3446 * entitlement succeeded.
3447 *
3448 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3449 * @hide
3450 */
3451 @SystemApi
3452 @Deprecated
3453 public interface OnTetheringEntitlementResultListener {
3454 /**
3455 * Called to notify entitlement result.
3456 *
3457 * @param resultCode an int value of entitlement result. It may be one of
3458 * {@link #TETHER_ERROR_NO_ERROR},
3459 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3460 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3461 */
3462 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3463 }
3464
3465 /**
3466 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003467 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3468 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003469 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003470 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003471 * any reason will update the cached value.
3472 *
3473 * @param type the downstream type of tethering. Must be one of
3474 * {@link #TETHERING_WIFI},
3475 * {@link #TETHERING_USB}, or
3476 * {@link #TETHERING_BLUETOOTH}.
3477 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3478 * @param executor the executor on which callback will be invoked.
3479 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3480 * notify the caller of the result of entitlement check. The listener may be called zero
3481 * or one time.
3482 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3483 * {@hide}
3484 */
3485 @SystemApi
3486 @Deprecated
3487 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3488 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3489 @NonNull @CallbackExecutor Executor executor,
3490 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003491 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003492 ResultReceiver wrappedListener = new ResultReceiver(null) {
3493 @Override
3494 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003495 final long token = Binder.clearCallingIdentity();
3496 try {
3497 executor.execute(() -> {
3498 listener.onTetheringEntitlementResult(resultCode);
3499 });
3500 } finally {
3501 Binder.restoreCallingIdentity(token);
3502 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003503 }
3504 };
3505
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003506 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003507 showEntitlementUi);
3508 }
3509
3510 /**
3511 * Report network connectivity status. This is currently used only
3512 * to alter status bar UI.
3513 * <p>This method requires the caller to hold the permission
3514 * {@link android.Manifest.permission#STATUS_BAR}.
3515 *
3516 * @param networkType The type of network you want to report on
3517 * @param percentage The quality of the connection 0 is bad, 100 is good
3518 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3519 * {@hide}
3520 */
3521 public void reportInetCondition(int networkType, int percentage) {
3522 printStackTrace();
3523 try {
3524 mService.reportInetCondition(networkType, percentage);
3525 } catch (RemoteException e) {
3526 throw e.rethrowFromSystemServer();
3527 }
3528 }
3529
3530 /**
3531 * Report a problem network to the framework. This provides a hint to the system
3532 * that there might be connectivity problems on this network and may cause
3533 * the framework to re-evaluate network connectivity and/or switch to another
3534 * network.
3535 *
3536 * @param network The {@link Network} the application was attempting to use
3537 * or {@code null} to indicate the current default network.
3538 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3539 * working and non-working connectivity.
3540 */
3541 @Deprecated
3542 public void reportBadNetwork(@Nullable Network network) {
3543 printStackTrace();
3544 try {
3545 // One of these will be ignored because it matches system's current state.
3546 // The other will trigger the necessary reevaluation.
3547 mService.reportNetworkConnectivity(network, true);
3548 mService.reportNetworkConnectivity(network, false);
3549 } catch (RemoteException e) {
3550 throw e.rethrowFromSystemServer();
3551 }
3552 }
3553
3554 /**
3555 * Report to the framework whether a network has working connectivity.
3556 * This provides a hint to the system that a particular network is providing
3557 * working connectivity or not. In response the framework may re-evaluate
3558 * the network's connectivity and might take further action thereafter.
3559 *
3560 * @param network The {@link Network} the application was attempting to use
3561 * or {@code null} to indicate the current default network.
3562 * @param hasConnectivity {@code true} if the application was able to successfully access the
3563 * Internet using {@code network} or {@code false} if not.
3564 */
3565 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3566 printStackTrace();
3567 try {
3568 mService.reportNetworkConnectivity(network, hasConnectivity);
3569 } catch (RemoteException e) {
3570 throw e.rethrowFromSystemServer();
3571 }
3572 }
3573
3574 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003575 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003576 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003577 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3578 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3579 * accessing any network, regardless of what the settings for that network are.
3580 *
3581 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3582 * proxy is likely to break networking on multiple networks. This method is only meant
3583 * for device policy clients looking to do general internal filtering or similar use cases.
3584 *
chiachangwang9473c592022-07-15 02:25:52 +00003585 * @see #getGlobalProxy
3586 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003587 *
3588 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3589 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003590 * @hide
3591 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003592 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003593 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003594 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003595 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003596 try {
3597 mService.setGlobalProxy(p);
3598 } catch (RemoteException e) {
3599 throw e.rethrowFromSystemServer();
3600 }
3601 }
3602
3603 /**
3604 * Retrieve any network-independent global HTTP proxy.
3605 *
3606 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3607 * if no global HTTP proxy is set.
3608 * @hide
3609 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003610 @SystemApi(client = MODULE_LIBRARIES)
3611 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003612 public ProxyInfo getGlobalProxy() {
3613 try {
3614 return mService.getGlobalProxy();
3615 } catch (RemoteException e) {
3616 throw e.rethrowFromSystemServer();
3617 }
3618 }
3619
3620 /**
3621 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3622 * network-specific HTTP proxy. If {@code network} is null, the
3623 * network-specific proxy returned is the proxy of the default active
3624 * network.
3625 *
3626 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3627 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3628 * or when {@code network} is {@code null},
3629 * the {@code ProxyInfo} for the default active network. Returns
3630 * {@code null} when no proxy applies or the caller doesn't have
3631 * permission to use {@code network}.
3632 * @hide
3633 */
3634 public ProxyInfo getProxyForNetwork(Network network) {
3635 try {
3636 return mService.getProxyForNetwork(network);
3637 } catch (RemoteException e) {
3638 throw e.rethrowFromSystemServer();
3639 }
3640 }
3641
3642 /**
3643 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3644 * otherwise if this process is bound to a {@link Network} using
3645 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3646 * the default network's proxy is returned.
3647 *
3648 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3649 * HTTP proxy is active.
3650 */
3651 @Nullable
3652 public ProxyInfo getDefaultProxy() {
3653 return getProxyForNetwork(getBoundNetworkForProcess());
3654 }
3655
3656 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003657 * Returns whether the hardware supports the given network type.
3658 *
3659 * This doesn't indicate there is coverage or such a network is available, just whether the
3660 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3661 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003662 *
3663 * @param networkType The network type we'd like to check
3664 * @return {@code true} if supported, else {@code false}
3665 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3666 * @hide
3667 */
3668 @Deprecated
3669 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3670 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3671 public boolean isNetworkSupported(int networkType) {
3672 try {
3673 return mService.isNetworkSupported(networkType);
3674 } catch (RemoteException e) {
3675 throw e.rethrowFromSystemServer();
3676 }
3677 }
3678
3679 /**
3680 * Returns if the currently active data network is metered. A network is
3681 * classified as metered when the user is sensitive to heavy data usage on
3682 * that connection due to monetary costs, data limitations or
3683 * battery/performance issues. You should check this before doing large
3684 * data transfers, and warn the user or delay the operation until another
3685 * network is available.
3686 *
3687 * @return {@code true} if large transfers should be avoided, otherwise
3688 * {@code false}.
3689 */
3690 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3691 public boolean isActiveNetworkMetered() {
3692 try {
3693 return mService.isActiveNetworkMetered();
3694 } catch (RemoteException e) {
3695 throw e.rethrowFromSystemServer();
3696 }
3697 }
3698
3699 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003700 * Set sign in error notification to visible or invisible
3701 *
3702 * @hide
3703 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3704 */
3705 @Deprecated
3706 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3707 String action) {
3708 try {
3709 mService.setProvisioningNotificationVisible(visible, networkType, action);
3710 } catch (RemoteException e) {
3711 throw e.rethrowFromSystemServer();
3712 }
3713 }
3714
3715 /**
3716 * Set the value for enabling/disabling airplane mode
3717 *
3718 * @param enable whether to enable airplane mode or not
3719 *
3720 * @hide
3721 */
3722 @RequiresPermission(anyOf = {
3723 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3724 android.Manifest.permission.NETWORK_SETTINGS,
3725 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3726 android.Manifest.permission.NETWORK_STACK})
3727 @SystemApi
3728 public void setAirplaneMode(boolean enable) {
3729 try {
3730 mService.setAirplaneMode(enable);
3731 } catch (RemoteException e) {
3732 throw e.rethrowFromSystemServer();
3733 }
3734 }
3735
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003736 /**
3737 * Registers the specified {@link NetworkProvider}.
3738 * Each listener must only be registered once. The listener can be unregistered with
3739 * {@link #unregisterNetworkProvider}.
3740 *
3741 * @param provider the provider to register
3742 * @return the ID of the provider. This ID must be used by the provider when registering
3743 * {@link android.net.NetworkAgent}s.
3744 * @hide
3745 */
3746 @SystemApi
3747 @RequiresPermission(anyOf = {
3748 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3749 android.Manifest.permission.NETWORK_FACTORY})
3750 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3751 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3752 throw new IllegalStateException("NetworkProviders can only be registered once");
3753 }
3754
3755 try {
3756 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3757 provider.getName());
3758 provider.setProviderId(providerId);
3759 } catch (RemoteException e) {
3760 throw e.rethrowFromSystemServer();
3761 }
3762 return provider.getProviderId();
3763 }
3764
3765 /**
3766 * Unregisters the specified NetworkProvider.
3767 *
3768 * @param provider the provider to unregister
3769 * @hide
3770 */
3771 @SystemApi
3772 @RequiresPermission(anyOf = {
3773 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3774 android.Manifest.permission.NETWORK_FACTORY})
3775 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3776 try {
3777 mService.unregisterNetworkProvider(provider.getMessenger());
3778 } catch (RemoteException e) {
3779 throw e.rethrowFromSystemServer();
3780 }
3781 provider.setProviderId(NetworkProvider.ID_NONE);
3782 }
3783
Chalard Jeand1b498b2021-01-05 08:40:09 +09003784 /**
3785 * Register or update a network offer with ConnectivityService.
3786 *
3787 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003788 * them to networking requests made by apps or the system. A callback identifies an offer
3789 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3790 * score and the capabilities of the network it might be able to bring up ; these act as
3791 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003792 * provider.
3793 *
3794 * The provider is under no obligation to be able to bring up the network it offers at any
3795 * given time. Instead, this mechanism is meant to limit requests received by providers
3796 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3797 * the quality of the network satisfying a given request to their own offer.
3798 *
3799 * An offer can be updated by calling this again with the same callback object. This is
3800 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3801 * provider with the changes caused by the changes in the offer.
3802 *
3803 * @param provider The provider making this offer.
3804 * @param score The prospective score of the network.
3805 * @param caps The prospective capabilities of the network.
3806 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003807 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003808 */
3809 @RequiresPermission(anyOf = {
3810 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3811 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003812 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003813 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3814 @NonNull final INetworkOfferCallback callback) {
3815 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003816 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003817 Objects.requireNonNull(score, "null score"),
3818 Objects.requireNonNull(caps, "null caps"),
3819 Objects.requireNonNull(callback, "null callback"));
3820 } catch (RemoteException e) {
3821 throw e.rethrowFromSystemServer();
3822 }
3823 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003824
Chalard Jeand1b498b2021-01-05 08:40:09 +09003825 /**
3826 * Withdraw a network offer made with {@link #offerNetwork}.
3827 *
3828 * @param callback The callback passed at registration time. This must be the same object
3829 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003830 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003831 */
3832 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3833 try {
3834 mService.unofferNetwork(Objects.requireNonNull(callback));
3835 } catch (RemoteException e) {
3836 throw e.rethrowFromSystemServer();
3837 }
3838 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003839 /** @hide exposed via the NetworkProvider class. */
3840 @RequiresPermission(anyOf = {
3841 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3842 android.Manifest.permission.NETWORK_FACTORY})
3843 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3844 try {
3845 mService.declareNetworkRequestUnfulfillable(request);
3846 } catch (RemoteException e) {
3847 throw e.rethrowFromSystemServer();
3848 }
3849 }
3850
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003851 /**
3852 * @hide
3853 * Register a NetworkAgent with ConnectivityService.
3854 * @return Network corresponding to NetworkAgent.
3855 */
3856 @RequiresPermission(anyOf = {
3857 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3858 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003859 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3860 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3861 @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId) {
3862 return registerNetworkAgent(na, ni, lp, nc, null /* localNetworkConfig */, score, config,
3863 providerId);
3864 }
3865
3866 /**
3867 * @hide
3868 * Register a NetworkAgent with ConnectivityService.
3869 * @return Network corresponding to NetworkAgent.
3870 */
3871 @RequiresPermission(anyOf = {
3872 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3873 android.Manifest.permission.NETWORK_FACTORY})
3874 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3875 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3876 @Nullable LocalNetworkConfig localNetworkConfig, @NonNull NetworkScore score,
3877 @NonNull NetworkAgentConfig config, int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003878 try {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003879 return mService.registerNetworkAgent(na, ni, lp, nc, score, localNetworkConfig, config,
3880 providerId);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003881 } catch (RemoteException e) {
3882 throw e.rethrowFromSystemServer();
3883 }
3884 }
3885
3886 /**
3887 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3888 * changes. Should be extended by applications wanting notifications.
3889 *
3890 * A {@code NetworkCallback} is registered by calling
3891 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3892 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3893 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3894 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3895 * A {@code NetworkCallback} should be registered at most once at any time.
3896 * A {@code NetworkCallback} that has been unregistered can be registered again.
3897 */
3898 public static class NetworkCallback {
3899 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003900 * No flags associated with this callback.
3901 * @hide
3902 */
3903 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003904
Roshan Piuse08bc182020-12-22 15:10:42 -08003905 /**
lucaslinc582d502022-01-27 09:07:00 +08003906 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3907 *
3908 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3909 * Prior to Android 12, this information is always returned to apps holding the appropriate
3910 * permission, possibly noting that the app has used location.
3911 * <p>In Android 12 and above, by default the sent objects do not contain any location
3912 * information, even if the app holds the necessary permissions, and the system does not
3913 * take note of location usage by the app. Apps can request that location information is
3914 * included, in which case the system will check location permission and the location
3915 * toggle state, and take note of location usage by the app if any such information is
3916 * returned.
3917 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003918 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3919 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3920 * <p>
3921 * These include:
3922 * <li> Some transport info instances (retrieved via
3923 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3924 * contain location sensitive information.
3925 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003926 * sensitive for wifi suggestor apps (i.e using
3927 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003928 * </p>
3929 * <p>
3930 * Note:
3931 * <li> Retrieving this location sensitive information (subject to app's location
3932 * permissions) will be noted by system. </li>
3933 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003934 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003935 */
Roshan Pius189d0092021-03-11 21:16:44 -08003936 // Note: Some existing fields which are location sensitive may still be included without
3937 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003938 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3939
3940 /** @hide */
3941 @Retention(RetentionPolicy.SOURCE)
3942 @IntDef(flag = true, prefix = "FLAG_", value = {
3943 FLAG_NONE,
3944 FLAG_INCLUDE_LOCATION_INFO
3945 })
3946 public @interface Flag { }
3947
3948 /**
3949 * All the valid flags for error checking.
3950 */
3951 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3952
3953 public NetworkCallback() {
3954 this(FLAG_NONE);
3955 }
3956
3957 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003958 if ((flags & VALID_FLAGS) != flags) {
3959 throw new IllegalArgumentException("Invalid flags");
3960 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003961 mFlags = flags;
3962 }
3963
3964 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003965 * Called when the framework connects to a new network to evaluate whether it satisfies this
3966 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3967 * callback. There is no guarantee that this new network will satisfy any requests, or that
3968 * the network will stay connected for longer than the time necessary to evaluate it.
3969 * <p>
3970 * Most applications <b>should not</b> act on this callback, and should instead use
3971 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3972 * the framework in properly evaluating the network &mdash; for example, an application that
3973 * can automatically log in to a captive portal without user intervention.
3974 *
3975 * @param network The {@link Network} of the network that is being evaluated.
3976 *
3977 * @hide
3978 */
3979 public void onPreCheck(@NonNull Network network) {}
3980
3981 /**
3982 * Called when the framework connects and has declared a new network ready for use.
3983 * This callback may be called more than once if the {@link Network} that is
3984 * satisfying the request changes.
3985 *
3986 * @param network The {@link Network} of the satisfying network.
3987 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3988 * @param linkProperties The {@link LinkProperties} of the satisfying network.
Chalard Jean22350c92023-10-07 19:21:45 +09003989 * @param localInfo The {@link LocalNetworkInfo} of the satisfying network, or null
3990 * if this network is not a local network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003991 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3992 * @hide
3993 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003994 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003995 @NonNull NetworkCapabilities networkCapabilities,
Chalard Jean22350c92023-10-07 19:21:45 +09003996 @NonNull LinkProperties linkProperties,
3997 @Nullable LocalNetworkInfo localInfo,
3998 @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003999 // Internally only this method is called when a new network is available, and
4000 // it calls the callback in the same way and order that older versions used
4001 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004002 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
Chalard Jean22350c92023-10-07 19:21:45 +09004003 if (null != localInfo) onLocalNetworkInfoChanged(network, localInfo);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004004 onBlockedStatusChanged(network, blocked);
4005 }
4006
4007 /**
4008 * Legacy variant of onAvailable that takes a boolean blocked reason.
4009 *
4010 * This method has never been public API, but it's not final, so there may be apps that
4011 * implemented it and rely on it being called. Do our best not to break them.
4012 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
4013 * this method is called. There does not seem to be a way to avoid this.
4014 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
4015 *
4016 * @hide
4017 */
4018 public void onAvailable(@NonNull Network network,
4019 @NonNull NetworkCapabilities networkCapabilities,
Chalard Jean22350c92023-10-07 19:21:45 +09004020 @NonNull LinkProperties linkProperties,
4021 boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004022 onAvailable(network);
4023 if (!networkCapabilities.hasCapability(
4024 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
4025 onNetworkSuspended(network);
4026 }
4027 onCapabilitiesChanged(network, networkCapabilities);
4028 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004029 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004030 }
4031
4032 /**
4033 * Called when the framework connects and has declared a new network ready for use.
4034 *
4035 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
4036 * be available at the same time, and onAvailable will be called for each of these as they
4037 * appear.
4038 *
4039 * <p>For callbacks registered with {@link #requestNetwork} and
4040 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
4041 * is the new best network for this request and is now tracked by this callback ; this
4042 * callback will no longer receive method calls about other networks that may have been
4043 * passed to this method previously. The previously-best network may have disconnected, or
4044 * it may still be around and the newly-best network may simply be better.
4045 *
4046 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
4047 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
4048 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
4049 * to {@link #onBlockedStatusChanged(Network, boolean)}.
4050 *
4051 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4052 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4053 * this callback as this is prone to race conditions (there is no guarantee the objects
4054 * returned by these methods will be current). Instead, wait for a call to
4055 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
4056 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
4057 * to be well-ordered with respect to other callbacks.
4058 *
4059 * @param network The {@link Network} of the satisfying network.
4060 */
4061 public void onAvailable(@NonNull Network network) {}
4062
4063 /**
4064 * Called when the network is about to be lost, typically because there are no outstanding
4065 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
4066 * with the new replacement network for graceful handover. This method is not guaranteed
4067 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
4068 * network is suddenly disconnected.
4069 *
4070 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4071 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4072 * this callback as this is prone to race conditions ; calling these methods while in a
4073 * callback may return an outdated or even a null object.
4074 *
4075 * @param network The {@link Network} that is about to be lost.
4076 * @param maxMsToLive The time in milliseconds the system intends to keep the network
4077 * connected for graceful handover; note that the network may still
4078 * suffer a hard loss at any time.
4079 */
4080 public void onLosing(@NonNull Network network, int maxMsToLive) {}
4081
4082 /**
4083 * Called when a network disconnects or otherwise no longer satisfies this request or
4084 * callback.
4085 *
4086 * <p>If the callback was registered with requestNetwork() or
4087 * registerDefaultNetworkCallback(), it will only be invoked against the last network
4088 * returned by onAvailable() when that network is lost and no other network satisfies
4089 * the criteria of the request.
4090 *
4091 * <p>If the callback was registered with registerNetworkCallback() it will be called for
4092 * each network which no longer satisfies the criteria of the callback.
4093 *
4094 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4095 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4096 * this callback as this is prone to race conditions ; calling these methods while in a
4097 * callback may return an outdated or even a null object.
4098 *
4099 * @param network The {@link Network} lost.
4100 */
4101 public void onLost(@NonNull Network network) {}
4102
4103 /**
4104 * Called if no network is found within the timeout time specified in
4105 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
4106 * requested network request cannot be fulfilled (whether or not a timeout was
4107 * specified). When this callback is invoked the associated
4108 * {@link NetworkRequest} will have already been removed and released, as if
4109 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
4110 */
4111 public void onUnavailable() {}
4112
4113 /**
4114 * Called when the network corresponding to this request changes capabilities but still
4115 * satisfies the requested criteria.
4116 *
4117 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4118 * to be called immediately after {@link #onAvailable}.
4119 *
4120 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
4121 * ConnectivityManager methods in this callback as this is prone to race conditions :
4122 * calling these methods while in a callback may return an outdated or even a null object.
4123 *
4124 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08004125 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004126 * network.
4127 */
4128 public void onCapabilitiesChanged(@NonNull Network network,
4129 @NonNull NetworkCapabilities networkCapabilities) {}
4130
4131 /**
4132 * Called when the network corresponding to this request changes {@link LinkProperties}.
4133 *
4134 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4135 * to be called immediately after {@link #onAvailable}.
4136 *
4137 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
4138 * ConnectivityManager methods in this callback as this is prone to race conditions :
4139 * calling these methods while in a callback may return an outdated or even a null object.
4140 *
4141 * @param network The {@link Network} whose link properties have changed.
4142 * @param linkProperties The new {@link LinkProperties} for this network.
4143 */
4144 public void onLinkPropertiesChanged(@NonNull Network network,
4145 @NonNull LinkProperties linkProperties) {}
4146
4147 /**
Chalard Jean22350c92023-10-07 19:21:45 +09004148 * Called when there is a change in the {@link LocalNetworkInfo} for this network.
4149 *
4150 * This is only called for local networks, that is those with the
4151 * NET_CAPABILITY_LOCAL_NETWORK network capability.
4152 *
4153 * @param network the {@link Network} whose local network info has changed.
4154 * @param localNetworkInfo the new {@link LocalNetworkInfo} for this network.
4155 * @hide
4156 */
4157 public void onLocalNetworkInfoChanged(@NonNull Network network,
4158 @NonNull LocalNetworkInfo localNetworkInfo) {}
4159
4160 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004161 * Called when the network the framework connected to for this request suspends data
4162 * transmission temporarily.
4163 *
4164 * <p>This generally means that while the TCP connections are still live temporarily
4165 * network data fails to transfer. To give a specific example, this is used on cellular
4166 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4167 * means read operations on sockets on this network will block once the buffers are
4168 * drained, and write operations will block once the buffers are full.
4169 *
4170 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4171 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4172 * this callback as this is prone to race conditions (there is no guarantee the objects
4173 * returned by these methods will be current).
4174 *
4175 * @hide
4176 */
4177 public void onNetworkSuspended(@NonNull Network network) {}
4178
4179 /**
4180 * Called when the network the framework connected to for this request
4181 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4182 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4183
4184 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4185 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4186 * this callback as this is prone to race conditions : calling these methods while in a
4187 * callback may return an outdated or even a null object.
4188 *
4189 * @hide
4190 */
4191 public void onNetworkResumed(@NonNull Network network) {}
4192
4193 /**
4194 * Called when access to the specified network is blocked or unblocked.
4195 *
4196 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4197 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4198 * this callback as this is prone to race conditions : calling these methods while in a
4199 * callback may return an outdated or even a null object.
4200 *
4201 * @param network The {@link Network} whose blocked status has changed.
4202 * @param blocked The blocked status of this {@link Network}.
4203 */
4204 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4205
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004206 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004207 * Called when access to the specified network is blocked or unblocked, or the reason for
4208 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004209 *
4210 * If a NetworkCallback object implements this method,
4211 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4212 *
4213 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4214 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4215 * this callback as this is prone to race conditions : calling these methods while in a
4216 * callback may return an outdated or even a null object.
4217 *
4218 * @param network The {@link Network} whose blocked status has changed.
4219 * @param blocked The blocked status of this {@link Network}.
4220 * @hide
4221 */
4222 @SystemApi(client = MODULE_LIBRARIES)
4223 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4224 onBlockedStatusChanged(network, blocked != 0);
4225 }
4226
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004227 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004228 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004229 }
4230
4231 /**
4232 * Constant error codes used by ConnectivityService to communicate about failures and errors
4233 * across a Binder boundary.
4234 * @hide
4235 */
4236 public interface Errors {
4237 int TOO_MANY_REQUESTS = 1;
4238 }
4239
4240 /** @hide */
4241 public static class TooManyRequestsException extends RuntimeException {}
4242
4243 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4244 switch (e.errorCode) {
4245 case Errors.TOO_MANY_REQUESTS:
4246 return new TooManyRequestsException();
4247 default:
4248 Log.w(TAG, "Unknown service error code " + e.errorCode);
4249 return new RuntimeException(e);
4250 }
4251 }
4252
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004253 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004254 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004255 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004256 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004257 /** @hide arg1 = TTL */
Chalard Jean22350c92023-10-07 19:21:45 +09004258 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004259 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004260 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004261 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004262 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004263 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004264 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004265 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004266 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004267 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Chalard Jean22350c92023-10-07 19:21:45 +09004268 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004269 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004270 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004271 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004272 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004273 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004274 public static final int CALLBACK_BLK_CHANGED = 11;
4275 /** @hide */
4276 public static final int CALLBACK_LOCAL_NETWORK_INFO_CHANGED = 12;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004277
4278 /** @hide */
4279 public static String getCallbackName(int whichCallback) {
4280 switch (whichCallback) {
4281 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4282 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4283 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4284 case CALLBACK_LOST: return "CALLBACK_LOST";
4285 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4286 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4287 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4288 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4289 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4290 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4291 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Chalard Jean22350c92023-10-07 19:21:45 +09004292 case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: return "CALLBACK_LOCAL_NETWORK_INFO_CHANGED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004293 default:
4294 return Integer.toString(whichCallback);
4295 }
4296 }
4297
zhujiatai79b0de92022-09-22 15:44:02 +08004298 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004299 private static final String TAG = "ConnectivityManager.CallbackHandler";
4300 private static final boolean DBG = false;
4301
4302 CallbackHandler(Looper looper) {
4303 super(looper);
4304 }
4305
4306 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004307 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004308 }
4309
4310 @Override
4311 public void handleMessage(Message message) {
4312 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004313 // the sInstance can't be null because to send this message a ConnectivityManager
4314 // instance must have been created prior to creating the thread on which this
4315 // Handler is running.
4316 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004317 return;
4318 }
4319
4320 final NetworkRequest request = getObject(message, NetworkRequest.class);
4321 final Network network = getObject(message, Network.class);
4322 final NetworkCallback callback;
4323 synchronized (sCallbacks) {
4324 callback = sCallbacks.get(request);
4325 if (callback == null) {
4326 Log.w(TAG,
4327 "callback not found for " + getCallbackName(message.what) + " message");
4328 return;
4329 }
4330 if (message.what == CALLBACK_UNAVAIL) {
4331 sCallbacks.remove(request);
4332 callback.networkRequest = ALREADY_UNREGISTERED;
4333 }
4334 }
4335 if (DBG) {
4336 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4337 }
4338
4339 switch (message.what) {
4340 case CALLBACK_PRECHECK: {
4341 callback.onPreCheck(network);
4342 break;
4343 }
4344 case CALLBACK_AVAILABLE: {
4345 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4346 LinkProperties lp = getObject(message, LinkProperties.class);
Chalard Jean22350c92023-10-07 19:21:45 +09004347 LocalNetworkInfo lni = getObject(message, LocalNetworkInfo.class);
4348 callback.onAvailable(network, cap, lp, lni, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004349 break;
4350 }
4351 case CALLBACK_LOSING: {
4352 callback.onLosing(network, message.arg1);
4353 break;
4354 }
4355 case CALLBACK_LOST: {
4356 callback.onLost(network);
4357 break;
4358 }
4359 case CALLBACK_UNAVAIL: {
4360 callback.onUnavailable();
4361 break;
4362 }
4363 case CALLBACK_CAP_CHANGED: {
4364 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4365 callback.onCapabilitiesChanged(network, cap);
4366 break;
4367 }
4368 case CALLBACK_IP_CHANGED: {
4369 LinkProperties lp = getObject(message, LinkProperties.class);
4370 callback.onLinkPropertiesChanged(network, lp);
4371 break;
4372 }
Chalard Jean22350c92023-10-07 19:21:45 +09004373 case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
4374 final LocalNetworkInfo info = getObject(message, LocalNetworkInfo.class);
4375 callback.onLocalNetworkInfoChanged(network, info);
4376 break;
4377 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004378 case CALLBACK_SUSPENDED: {
4379 callback.onNetworkSuspended(network);
4380 break;
4381 }
4382 case CALLBACK_RESUMED: {
4383 callback.onNetworkResumed(network);
4384 break;
4385 }
4386 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004387 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004388 }
4389 }
4390 }
4391
4392 private <T> T getObject(Message msg, Class<T> c) {
4393 return (T) msg.getData().getParcelable(c.getSimpleName());
4394 }
4395 }
4396
4397 private CallbackHandler getDefaultHandler() {
4398 synchronized (sCallbacks) {
4399 if (sCallbackHandler == null) {
4400 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4401 }
4402 return sCallbackHandler;
4403 }
4404 }
4405
4406 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4407 private static CallbackHandler sCallbackHandler;
4408
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004409 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4410 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4411 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004412 printStackTrace();
4413 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004414 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4415 throw new IllegalArgumentException("null NetworkCapabilities");
4416 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004417 final NetworkRequest request;
4418 final String callingPackageName = mContext.getOpPackageName();
4419 try {
4420 synchronized(sCallbacks) {
4421 if (callback.networkRequest != null
4422 && callback.networkRequest != ALREADY_UNREGISTERED) {
4423 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4424 // and requests (http://b/20701525).
4425 Log.e(TAG, "NetworkCallback was already registered");
4426 }
4427 Messenger messenger = new Messenger(handler);
4428 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004429 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004430 if (reqType == LISTEN) {
4431 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004432 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004433 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004434 } else {
4435 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004436 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4437 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004438 }
4439 if (request != null) {
4440 sCallbacks.put(request, callback);
4441 }
4442 callback.networkRequest = request;
4443 }
4444 } catch (RemoteException e) {
4445 throw e.rethrowFromSystemServer();
4446 } catch (ServiceSpecificException e) {
4447 throw convertServiceException(e);
4448 }
4449 return request;
4450 }
4451
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004452 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4453 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4454 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4455 legacyType, handler);
4456 }
4457
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004458 /**
4459 * Helper function to request a network with a particular legacy type.
4460 *
4461 * This API is only for use in internal system code that requests networks with legacy type and
4462 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4463 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4464 *
4465 * @param request {@link NetworkRequest} describing this request.
4466 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4467 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4468 * be a positive value (i.e. >0).
4469 * @param legacyType to specify the network type(#TYPE_*).
4470 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4471 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4472 * the callback must not be shared - it uniquely specifies this request.
4473 *
4474 * @hide
4475 */
4476 @SystemApi
4477 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4478 public void requestNetwork(@NonNull NetworkRequest request,
4479 int timeoutMs, int legacyType, @NonNull Handler handler,
4480 @NonNull NetworkCallback networkCallback) {
4481 if (legacyType == TYPE_NONE) {
4482 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4483 }
4484 CallbackHandler cbHandler = new CallbackHandler(handler);
4485 NetworkCapabilities nc = request.networkCapabilities;
4486 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4487 }
4488
4489 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004490 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004491 *
4492 * <p>This method will attempt to find the best network that matches the passed
4493 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4494 * criteria. The platform will evaluate which network is the best at its own discretion.
4495 * Throughput, latency, cost per byte, policy, user preference and other considerations
4496 * may be factored in the decision of what is considered the best network.
4497 *
4498 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4499 * matching this request, while always attempting to match the request to a better network if
4500 * possible. If a better match is found, the platform will switch this request to the now-best
4501 * network and inform the app of the newly best network by invoking
4502 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4503 * will not try to maintain any other network than the best one currently matching the request:
4504 * a network not matching any network request may be disconnected at any time.
4505 *
4506 * <p>For example, an application could use this method to obtain a connected cellular network
4507 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4508 * radio to consume additional power. Or, an application could inform the system that it wants
4509 * a network supporting sending MMSes and have the system let it know about the currently best
4510 * MMS-supporting network through the provided {@link NetworkCallback}.
4511 *
4512 * <p>The status of the request can be followed by listening to the various callbacks described
4513 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4514 * used to direct traffic to the network (although accessing some networks may be subject to
4515 * holding specific permissions). Callers will learn about the specific characteristics of the
4516 * network through
4517 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4518 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4519 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4520 * matching the request at any given time; therefore when a better network matching the request
4521 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4522 * with the new network after which no further updates are given about the previously-best
4523 * network, unless it becomes the best again at some later time. All callbacks are invoked
4524 * in order on the same thread, which by default is a thread created by the framework running
4525 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004526 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004527 * callbacks are invoked.
4528 *
4529 * <p>This{@link NetworkRequest} will live until released via
4530 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4531 * which point the system may let go of the network at any time.
4532 *
4533 * <p>A version of this method which takes a timeout is
4534 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4535 * wait for a limited amount of time for the network to become unavailable.
4536 *
4537 * <p>It is presently unsupported to request a network with mutable
4538 * {@link NetworkCapabilities} such as
4539 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4540 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4541 * as these {@code NetworkCapabilities} represent states that a particular
4542 * network may never attain, and whether a network will attain these states
4543 * is unknown prior to bringing up the network so the framework does not
4544 * know how to go about satisfying a request with these capabilities.
4545 *
4546 * <p>This method requires the caller to hold either the
4547 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4548 * or the ability to modify system settings as determined by
4549 * {@link android.provider.Settings.System#canWrite}.</p>
4550 *
4551 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4552 * number of outstanding requests to 100 per app (identified by their UID), shared with
4553 * all variants of this method, of {@link #registerNetworkCallback} as well as
4554 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4555 * Requesting a network with this method will count toward this limit. If this limit is
4556 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4557 * make sure to unregister the callbacks with
4558 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4559 *
4560 * @param request {@link NetworkRequest} describing this request.
4561 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4562 * the callback must not be shared - it uniquely specifies this request.
4563 * The callback is invoked on the default internal Handler.
4564 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4565 * @throws SecurityException if missing the appropriate permissions.
4566 * @throws RuntimeException if the app already has too many callbacks registered.
4567 */
4568 public void requestNetwork(@NonNull NetworkRequest request,
4569 @NonNull NetworkCallback networkCallback) {
4570 requestNetwork(request, networkCallback, getDefaultHandler());
4571 }
4572
4573 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004574 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004575 *
4576 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4577 * but runs all the callbacks on the passed Handler.
4578 *
4579 * <p>This method has the same permission requirements as
4580 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4581 * and throws the same exceptions in the same conditions.
4582 *
4583 * @param request {@link NetworkRequest} describing this request.
4584 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4585 * the callback must not be shared - it uniquely specifies this request.
4586 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4587 */
4588 public void requestNetwork(@NonNull NetworkRequest request,
4589 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4590 CallbackHandler cbHandler = new CallbackHandler(handler);
4591 NetworkCapabilities nc = request.networkCapabilities;
4592 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4593 }
4594
4595 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004596 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004597 * by a timeout.
4598 *
4599 * This function behaves identically to the non-timed-out version
4600 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4601 * is not found within the given time (in milliseconds) the
4602 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4603 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4604 * not have to be released if timed-out (it is automatically released). Unregistering a
4605 * request that timed out is not an error.
4606 *
4607 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4608 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4609 * for that purpose. Calling this method will attempt to bring up the requested network.
4610 *
4611 * <p>This method has the same permission requirements as
4612 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4613 * and throws the same exceptions in the same conditions.
4614 *
4615 * @param request {@link NetworkRequest} describing this request.
4616 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4617 * the callback must not be shared - it uniquely specifies this request.
4618 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4619 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4620 * be a positive value (i.e. >0).
4621 */
4622 public void requestNetwork(@NonNull NetworkRequest request,
4623 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4624 checkTimeout(timeoutMs);
4625 NetworkCapabilities nc = request.networkCapabilities;
4626 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4627 getDefaultHandler());
4628 }
4629
4630 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004631 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004632 * by a timeout.
4633 *
4634 * This method behaves identically to
4635 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4636 * on the passed Handler.
4637 *
4638 * <p>This method has the same permission requirements as
4639 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4640 * and throws the same exceptions in the same conditions.
4641 *
4642 * @param request {@link NetworkRequest} describing this request.
4643 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4644 * the callback must not be shared - it uniquely specifies this request.
4645 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4646 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4647 * before {@link NetworkCallback#onUnavailable} is called.
4648 */
4649 public void requestNetwork(@NonNull NetworkRequest request,
4650 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4651 checkTimeout(timeoutMs);
4652 CallbackHandler cbHandler = new CallbackHandler(handler);
4653 NetworkCapabilities nc = request.networkCapabilities;
4654 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4655 }
4656
4657 /**
4658 * The lookup key for a {@link Network} object included with the intent after
4659 * successfully finding a network for the applications request. Retrieve it with
4660 * {@link android.content.Intent#getParcelableExtra(String)}.
4661 * <p>
4662 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4663 * then you must get a ConnectivityManager instance before doing so.
4664 */
4665 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4666
4667 /**
4668 * The lookup key for a {@link NetworkRequest} object included with the intent after
4669 * successfully finding a network for the applications request. Retrieve it with
4670 * {@link android.content.Intent#getParcelableExtra(String)}.
4671 */
4672 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4673
4674
4675 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004676 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004677 *
4678 * This function behaves identically to the version that takes a NetworkCallback, but instead
4679 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4680 * the request may outlive the calling application and get called back when a suitable
4681 * network is found.
4682 * <p>
4683 * The operation is an Intent broadcast that goes to a broadcast receiver that
4684 * you registered with {@link Context#registerReceiver} or through the
4685 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4686 * <p>
4687 * The operation Intent is delivered with two extras, a {@link Network} typed
4688 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4689 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4690 * the original requests parameters. It is important to create a new,
4691 * {@link NetworkCallback} based request before completing the processing of the
4692 * Intent to reserve the network or it will be released shortly after the Intent
4693 * is processed.
4694 * <p>
4695 * If there is already a request for this Intent registered (with the equality of
4696 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4697 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4698 * <p>
4699 * The request may be released normally by calling
4700 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4701 * <p>It is presently unsupported to request a network with either
4702 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4703 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4704 * as these {@code NetworkCapabilities} represent states that a particular
4705 * network may never attain, and whether a network will attain these states
4706 * is unknown prior to bringing up the network so the framework does not
4707 * know how to go about satisfying a request with these capabilities.
4708 *
4709 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4710 * number of outstanding requests to 100 per app (identified by their UID), shared with
4711 * all variants of this method, of {@link #registerNetworkCallback} as well as
4712 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4713 * Requesting a network with this method will count toward this limit. If this limit is
4714 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4715 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4716 * or {@link #releaseNetworkRequest(PendingIntent)}.
4717 *
4718 * <p>This method requires the caller to hold either the
4719 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4720 * or the ability to modify system settings as determined by
4721 * {@link android.provider.Settings.System#canWrite}.</p>
4722 *
4723 * @param request {@link NetworkRequest} describing this request.
4724 * @param operation Action to perform when the network is available (corresponds
4725 * to the {@link NetworkCallback#onAvailable} call. Typically
4726 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4727 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4728 * @throws SecurityException if missing the appropriate permissions.
4729 * @throws RuntimeException if the app already has too many callbacks registered.
4730 */
4731 public void requestNetwork(@NonNull NetworkRequest request,
4732 @NonNull PendingIntent operation) {
4733 printStackTrace();
4734 checkPendingIntentNotNull(operation);
4735 try {
4736 mService.pendingRequestForNetwork(
4737 request.networkCapabilities, operation, mContext.getOpPackageName(),
4738 getAttributionTag());
4739 } catch (RemoteException e) {
4740 throw e.rethrowFromSystemServer();
4741 } catch (ServiceSpecificException e) {
4742 throw convertServiceException(e);
4743 }
4744 }
4745
4746 /**
4747 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4748 * <p>
4749 * This method has the same behavior as
4750 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4751 * releasing network resources and disconnecting.
4752 *
4753 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4754 * PendingIntent passed to
4755 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4756 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4757 */
4758 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4759 printStackTrace();
4760 checkPendingIntentNotNull(operation);
4761 try {
4762 mService.releasePendingNetworkRequest(operation);
4763 } catch (RemoteException e) {
4764 throw e.rethrowFromSystemServer();
4765 }
4766 }
4767
4768 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004769 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004770 }
4771
4772 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004773 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004774 }
4775
4776 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004777 if (timeoutMs <= 0) {
4778 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4779 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004780 }
4781
4782 /**
4783 * Registers to receive notifications about all networks which satisfy the given
4784 * {@link NetworkRequest}. The callbacks will continue to be called until
4785 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4786 * called.
4787 *
4788 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4789 * number of outstanding requests to 100 per app (identified by their UID), shared with
4790 * all variants of this method, of {@link #requestNetwork} as well as
4791 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4792 * Requesting a network with this method will count toward this limit. If this limit is
4793 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4794 * make sure to unregister the callbacks with
4795 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4796 *
4797 * @param request {@link NetworkRequest} describing this request.
4798 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4799 * networks change state.
4800 * The callback is invoked on the default internal Handler.
4801 * @throws RuntimeException if the app already has too many callbacks registered.
4802 */
4803 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4804 public void registerNetworkCallback(@NonNull NetworkRequest request,
4805 @NonNull NetworkCallback networkCallback) {
4806 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4807 }
4808
4809 /**
4810 * Registers to receive notifications about all networks which satisfy the given
4811 * {@link NetworkRequest}. The callbacks will continue to be called until
4812 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4813 * called.
4814 *
4815 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4816 * number of outstanding requests to 100 per app (identified by their UID), shared with
4817 * all variants of this method, of {@link #requestNetwork} as well as
4818 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4819 * Requesting a network with this method will count toward this limit. If this limit is
4820 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4821 * make sure to unregister the callbacks with
4822 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4823 *
4824 *
4825 * @param request {@link NetworkRequest} describing this request.
4826 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4827 * networks change state.
4828 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4829 * @throws RuntimeException if the app already has too many callbacks registered.
4830 */
4831 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4832 public void registerNetworkCallback(@NonNull NetworkRequest request,
4833 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4834 CallbackHandler cbHandler = new CallbackHandler(handler);
4835 NetworkCapabilities nc = request.networkCapabilities;
4836 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4837 }
4838
4839 /**
4840 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4841 * {@link NetworkRequest}.
4842 *
4843 * This function behaves identically to the version that takes a NetworkCallback, but instead
4844 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4845 * the request may outlive the calling application and get called back when a suitable
4846 * network is found.
4847 * <p>
4848 * The operation is an Intent broadcast that goes to a broadcast receiver that
4849 * you registered with {@link Context#registerReceiver} or through the
4850 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4851 * <p>
4852 * The operation Intent is delivered with two extras, a {@link Network} typed
4853 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4854 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4855 * the original requests parameters.
4856 * <p>
4857 * If there is already a request for this Intent registered (with the equality of
4858 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4859 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4860 * <p>
4861 * The request may be released normally by calling
4862 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4863 *
4864 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4865 * number of outstanding requests to 100 per app (identified by their UID), shared with
4866 * all variants of this method, of {@link #requestNetwork} as well as
4867 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4868 * Requesting a network with this method will count toward this limit. If this limit is
4869 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4870 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4871 * or {@link #releaseNetworkRequest(PendingIntent)}.
4872 *
4873 * @param request {@link NetworkRequest} describing this request.
4874 * @param operation Action to perform when the network is available (corresponds
4875 * to the {@link NetworkCallback#onAvailable} call. Typically
4876 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4877 * @throws RuntimeException if the app already has too many callbacks registered.
4878 */
4879 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4880 public void registerNetworkCallback(@NonNull NetworkRequest request,
4881 @NonNull PendingIntent operation) {
4882 printStackTrace();
4883 checkPendingIntentNotNull(operation);
4884 try {
4885 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004886 request.networkCapabilities, operation, mContext.getOpPackageName(),
4887 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004888 } catch (RemoteException e) {
4889 throw e.rethrowFromSystemServer();
4890 } catch (ServiceSpecificException e) {
4891 throw convertServiceException(e);
4892 }
4893 }
4894
4895 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004896 * Registers to receive notifications about changes in the application's default network. This
4897 * may be a physical network or a virtual network, such as a VPN that applies to the
4898 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004899 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4900 *
4901 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4902 * number of outstanding requests to 100 per app (identified by their UID), shared with
4903 * all variants of this method, of {@link #requestNetwork} as well as
4904 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4905 * Requesting a network with this method will count toward this limit. If this limit is
4906 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4907 * make sure to unregister the callbacks with
4908 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4909 *
4910 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004911 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004912 * The callback is invoked on the default internal Handler.
4913 * @throws RuntimeException if the app already has too many callbacks registered.
4914 */
4915 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4916 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4917 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4918 }
4919
4920 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004921 * Registers to receive notifications about changes in the application's default network. This
4922 * may be a physical network or a virtual network, such as a VPN that applies to the
4923 * application. The callbacks will continue to be called until either the application exits or
4924 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4925 *
4926 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4927 * number of outstanding requests to 100 per app (identified by their UID), shared with
4928 * all variants of this method, of {@link #requestNetwork} as well as
4929 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4930 * Requesting a network with this method will count toward this limit. If this limit is
4931 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4932 * make sure to unregister the callbacks with
4933 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4934 *
4935 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4936 * application's default network changes.
4937 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4938 * @throws RuntimeException if the app already has too many callbacks registered.
4939 */
4940 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4941 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4942 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004943 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004944 }
4945
4946 /**
4947 * Registers to receive notifications about changes in the default network for the specified
4948 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4949 * UID. The callbacks will continue to be called until either the application exits or
4950 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4951 *
4952 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4953 * number of outstanding requests to 100 per app (identified by their UID), shared with
4954 * all variants of this method, of {@link #requestNetwork} as well as
4955 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4956 * Requesting a network with this method will count toward this limit. If this limit is
4957 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4958 * make sure to unregister the callbacks with
4959 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4960 *
4961 * @param uid the UID for which to track default network changes.
4962 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4963 * UID's default network changes.
4964 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4965 * @throws RuntimeException if the app already has too many callbacks registered.
4966 * @hide
4967 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004968 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004969 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4970 @RequiresPermission(anyOf = {
4971 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4972 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004973 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004974 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004975 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004976 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004977 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4978 }
4979
4980 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004981 * Registers to receive notifications about changes in the system default network. The callbacks
4982 * will continue to be called until either the application exits or
4983 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4984 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004985 * This method should not be used to determine networking state seen by applications, because in
4986 * many cases, most or even all application traffic may not use the default network directly,
4987 * and traffic from different applications may go on different networks by default. As an
4988 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4989 * and not onto the system default network. Applications or system components desiring to do
4990 * determine network state as seen by applications should use other methods such as
4991 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4992 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004993 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4994 * number of outstanding requests to 100 per app (identified by their UID), shared with
4995 * all variants of this method, of {@link #requestNetwork} as well as
4996 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4997 * Requesting a network with this method will count toward this limit. If this limit is
4998 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4999 * make sure to unregister the callbacks with
5000 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5001 *
5002 * @param networkCallback The {@link NetworkCallback} that the system will call as the
5003 * system default network changes.
5004 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5005 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09005006 *
5007 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005008 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09005009 @SystemApi(client = MODULE_LIBRARIES)
5010 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
5011 @RequiresPermission(anyOf = {
5012 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08005013 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00005014 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08005015 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09005016 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005017 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005018 CallbackHandler cbHandler = new CallbackHandler(handler);
5019 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09005020 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005021 }
5022
5023 /**
junyulaibd123062021-03-15 11:48:48 +08005024 * Registers to receive notifications about the best matching network which satisfy the given
5025 * {@link NetworkRequest}. The callbacks will continue to be called until
5026 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
5027 * called.
5028 *
5029 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5030 * number of outstanding requests to 100 per app (identified by their UID), shared with
5031 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
5032 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5033 * Requesting a network with this method will count toward this limit. If this limit is
5034 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5035 * make sure to unregister the callbacks with
5036 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5037 *
5038 *
5039 * @param request {@link NetworkRequest} describing this request.
5040 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
5041 * networks change state.
5042 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5043 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08005044 */
junyulai5a5c99b2021-03-05 15:51:17 +08005045 @SuppressLint("ExecutorRegistration")
5046 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
5047 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
5048 final NetworkCapabilities nc = request.networkCapabilities;
5049 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08005050 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08005051 }
5052
5053 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005054 * Requests bandwidth update for a given {@link Network} and returns whether the update request
5055 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
5056 * network connection for updated bandwidth information. The caller will be notified via
5057 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
5058 * method assumes that the caller has previously called
5059 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
5060 * changes.
5061 *
5062 * @param network {@link Network} specifying which network you're interested.
5063 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5064 */
5065 public boolean requestBandwidthUpdate(@NonNull Network network) {
5066 try {
5067 return mService.requestBandwidthUpdate(network);
5068 } catch (RemoteException e) {
5069 throw e.rethrowFromSystemServer();
5070 }
5071 }
5072
5073 /**
5074 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
5075 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
5076 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005077 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
5078 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005079 *
5080 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
5081 * triggering it as soon as this call returns.
5082 *
5083 * @param networkCallback The {@link NetworkCallback} used when making the request.
5084 */
5085 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
5086 printStackTrace();
5087 checkCallbackNotNull(networkCallback);
5088 final List<NetworkRequest> reqs = new ArrayList<>();
5089 // Find all requests associated to this callback and stop callback triggers immediately.
5090 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
5091 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00005092 if (networkCallback.networkRequest == null) {
5093 throw new IllegalArgumentException("NetworkCallback was not registered");
5094 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005095 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
5096 Log.d(TAG, "NetworkCallback was already unregistered");
5097 return;
5098 }
5099 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
5100 if (e.getValue() == networkCallback) {
5101 reqs.add(e.getKey());
5102 }
5103 }
5104 // TODO: throw exception if callback was registered more than once (http://b/20701525).
5105 for (NetworkRequest r : reqs) {
5106 try {
5107 mService.releaseNetworkRequest(r);
5108 } catch (RemoteException e) {
5109 throw e.rethrowFromSystemServer();
5110 }
5111 // Only remove mapping if rpc was successful.
5112 sCallbacks.remove(r);
5113 }
5114 networkCallback.networkRequest = ALREADY_UNREGISTERED;
5115 }
5116 }
5117
5118 /**
5119 * Unregisters a callback previously registered via
5120 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5121 *
5122 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
5123 * PendingIntent passed to
5124 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5125 * Cannot be null.
5126 */
5127 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
5128 releaseNetworkRequest(operation);
5129 }
5130
5131 /**
5132 * Informs the system whether it should switch to {@code network} regardless of whether it is
5133 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
5134 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
5135 * the system default network regardless of any other network that's currently connected. If
5136 * {@code always} is true, then the choice is remembered, so that the next time the user
5137 * connects to this network, the system will switch to it.
5138 *
5139 * @param network The network to accept.
5140 * @param accept Whether to accept the network even if unvalidated.
5141 * @param always Whether to remember this choice in the future.
5142 *
5143 * @hide
5144 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005145 @SystemApi(client = MODULE_LIBRARIES)
5146 @RequiresPermission(anyOf = {
5147 android.Manifest.permission.NETWORK_SETTINGS,
5148 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5149 android.Manifest.permission.NETWORK_STACK,
5150 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5151 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005152 try {
5153 mService.setAcceptUnvalidated(network, accept, always);
5154 } catch (RemoteException e) {
5155 throw e.rethrowFromSystemServer();
5156 }
5157 }
5158
5159 /**
5160 * Informs the system whether it should consider the network as validated even if it only has
5161 * partial connectivity. If {@code accept} is true, then the network will be considered as
5162 * validated even if connectivity is only partial. If {@code always} is true, then the choice
5163 * is remembered, so that the next time the user connects to this network, the system will
5164 * switch to it.
5165 *
5166 * @param network The network to accept.
5167 * @param accept Whether to consider the network as validated even if it has partial
5168 * connectivity.
5169 * @param always Whether to remember this choice in the future.
5170 *
5171 * @hide
5172 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005173 @SystemApi(client = MODULE_LIBRARIES)
5174 @RequiresPermission(anyOf = {
5175 android.Manifest.permission.NETWORK_SETTINGS,
5176 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5177 android.Manifest.permission.NETWORK_STACK,
5178 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5179 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5180 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005181 try {
5182 mService.setAcceptPartialConnectivity(network, accept, always);
5183 } catch (RemoteException e) {
5184 throw e.rethrowFromSystemServer();
5185 }
5186 }
5187
5188 /**
5189 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5190 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5191 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5192 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5193 *
5194 * @param network The network to accept.
5195 *
5196 * @hide
5197 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005198 @SystemApi(client = MODULE_LIBRARIES)
5199 @RequiresPermission(anyOf = {
5200 android.Manifest.permission.NETWORK_SETTINGS,
5201 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5202 android.Manifest.permission.NETWORK_STACK,
5203 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5204 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005205 try {
5206 mService.setAvoidUnvalidated(network);
5207 } catch (RemoteException e) {
5208 throw e.rethrowFromSystemServer();
5209 }
5210 }
5211
5212 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005213 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005214 *
5215 * @param timeMs The expired current time. The value should be set within a limited time from
5216 * now.
5217 *
5218 * @hide
5219 */
5220 public void setTestAllowBadWifiUntil(long timeMs) {
5221 try {
5222 mService.setTestAllowBadWifiUntil(timeMs);
5223 } catch (RemoteException e) {
5224 throw e.rethrowFromSystemServer();
5225 }
5226 }
5227
5228 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005229 * Requests that the system open the captive portal app on the specified network.
5230 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005231 * <p>This is to be used on networks where a captive portal was detected, as per
5232 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5233 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005234 * @param network The network to log into.
5235 *
5236 * @hide
5237 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005238 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5239 @RequiresPermission(anyOf = {
5240 android.Manifest.permission.NETWORK_SETTINGS,
5241 android.Manifest.permission.NETWORK_STACK,
5242 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5243 })
5244 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005245 try {
5246 mService.startCaptivePortalApp(network);
5247 } catch (RemoteException e) {
5248 throw e.rethrowFromSystemServer();
5249 }
5250 }
5251
5252 /**
5253 * Requests that the system open the captive portal app with the specified extras.
5254 *
5255 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5256 * corresponding permission.
5257 * @param network Network on which the captive portal was detected.
5258 * @param appExtras Extras to include in the app start intent.
5259 * @hide
5260 */
5261 @SystemApi
5262 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5263 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5264 try {
5265 mService.startCaptivePortalAppInternal(network, appExtras);
5266 } catch (RemoteException e) {
5267 throw e.rethrowFromSystemServer();
5268 }
5269 }
5270
5271 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005272 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005273 * @hide
5274 */
5275 @SystemApi
5276 @RequiresPermission(anyOf = {
5277 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5278 android.Manifest.permission.NETWORK_STACK})
5279 public boolean shouldAvoidBadWifi() {
5280 try {
5281 return mService.shouldAvoidBadWifi();
5282 } catch (RemoteException e) {
5283 throw e.rethrowFromSystemServer();
5284 }
5285 }
5286
5287 /**
5288 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5289 * time-sensitive user-facing operations when the system default network is temporarily
5290 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5291 * this method), and the operation should be infrequent to ensure that data usage is limited.
5292 *
5293 * An example of such an operation might be a time-sensitive foreground activity, such as a
5294 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5295 */
5296 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5297
5298 /**
5299 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5300 * a backup channel for traffic that is primarily going over another network.
5301 *
5302 * An example might be maintaining backup connections to peers or servers for the purpose of
5303 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5304 * on backup paths should be negligible compared to the traffic on the main path.
5305 */
5306 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5307
5308 /**
5309 * It is acceptable to use metered data to improve network latency and performance.
5310 */
5311 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5312
5313 /**
5314 * Return value to use for unmetered networks. On such networks we currently set all the flags
5315 * to true.
5316 * @hide
5317 */
5318 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5319 MULTIPATH_PREFERENCE_HANDOVER |
5320 MULTIPATH_PREFERENCE_RELIABILITY |
5321 MULTIPATH_PREFERENCE_PERFORMANCE;
5322
Aaron Huangcff22942021-05-27 16:31:26 +08005323 /** @hide */
5324 @Retention(RetentionPolicy.SOURCE)
5325 @IntDef(flag = true, value = {
5326 MULTIPATH_PREFERENCE_HANDOVER,
5327 MULTIPATH_PREFERENCE_RELIABILITY,
5328 MULTIPATH_PREFERENCE_PERFORMANCE,
5329 })
5330 public @interface MultipathPreference {
5331 }
5332
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005333 /**
5334 * Provides a hint to the calling application on whether it is desirable to use the
5335 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5336 * for multipath data transfer on this network when it is not the system default network.
5337 * Applications desiring to use multipath network protocols should call this method before
5338 * each such operation.
5339 *
5340 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005341 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005342 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005343 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005344 */
5345 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5346 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5347 try {
5348 return mService.getMultipathPreference(network);
5349 } catch (RemoteException e) {
5350 throw e.rethrowFromSystemServer();
5351 }
5352 }
5353
5354 /**
5355 * Resets all connectivity manager settings back to factory defaults.
5356 * @hide
5357 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005358 @SystemApi(client = MODULE_LIBRARIES)
5359 @RequiresPermission(anyOf = {
5360 android.Manifest.permission.NETWORK_SETTINGS,
5361 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005362 public void factoryReset() {
5363 try {
5364 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005365 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005366 } catch (RemoteException e) {
5367 throw e.rethrowFromSystemServer();
5368 }
5369 }
5370
5371 /**
5372 * Binds the current process to {@code network}. All Sockets created in the future
5373 * (and not explicitly bound via a bound SocketFactory from
5374 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5375 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5376 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5377 * work and all host name resolutions will fail. This is by design so an application doesn't
5378 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5379 * To clear binding pass {@code null} for {@code network}. Using individually bound
5380 * Sockets created by Network.getSocketFactory().createSocket() and
5381 * performing network-specific host name resolutions via
5382 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5383 * {@code bindProcessToNetwork}.
5384 *
5385 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5386 * the current binding.
5387 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5388 */
5389 public boolean bindProcessToNetwork(@Nullable Network network) {
5390 // Forcing callers to call through non-static function ensures ConnectivityManager
5391 // instantiated.
5392 return setProcessDefaultNetwork(network);
5393 }
5394
5395 /**
5396 * Binds the current process to {@code network}. All Sockets created in the future
5397 * (and not explicitly bound via a bound SocketFactory from
5398 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5399 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5400 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5401 * work and all host name resolutions will fail. This is by design so an application doesn't
5402 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5403 * To clear binding pass {@code null} for {@code network}. Using individually bound
5404 * Sockets created by Network.getSocketFactory().createSocket() and
5405 * performing network-specific host name resolutions via
5406 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5407 * {@code setProcessDefaultNetwork}.
5408 *
5409 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5410 * the current binding.
5411 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5412 * @deprecated This function can throw {@link IllegalStateException}. Use
5413 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5414 * is a direct replacement.
5415 */
5416 @Deprecated
5417 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5418 int netId = (network == null) ? NETID_UNSET : network.netId;
5419 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5420
5421 if (netId != NETID_UNSET) {
5422 netId = network.getNetIdForResolv();
5423 }
5424
5425 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5426 return false;
5427 }
5428
5429 if (!isSameNetId) {
5430 // Set HTTP proxy system properties to match network.
5431 // TODO: Deprecate this static method and replace it with a non-static version.
5432 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005433 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005434 } catch (SecurityException e) {
5435 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5436 Log.e(TAG, "Can't set proxy properties", e);
5437 }
5438 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005439 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005440 // Must flush socket pool as idle sockets will be bound to previous network and may
5441 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005442 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005443 }
5444
5445 return true;
5446 }
5447
5448 /**
5449 * Returns the {@link Network} currently bound to this process via
5450 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5451 *
5452 * @return {@code Network} to which this process is bound, or {@code null}.
5453 */
5454 @Nullable
5455 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005456 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005457 // instantiated.
5458 return getProcessDefaultNetwork();
5459 }
5460
5461 /**
5462 * Returns the {@link Network} currently bound to this process via
5463 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5464 *
5465 * @return {@code Network} to which this process is bound, or {@code null}.
5466 * @deprecated Using this function can lead to other functions throwing
5467 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5468 * {@code getBoundNetworkForProcess} is a direct replacement.
5469 */
5470 @Deprecated
5471 @Nullable
5472 public static Network getProcessDefaultNetwork() {
5473 int netId = NetworkUtils.getBoundNetworkForProcess();
5474 if (netId == NETID_UNSET) return null;
5475 return new Network(netId);
5476 }
5477
5478 private void unsupportedStartingFrom(int version) {
5479 if (Process.myUid() == Process.SYSTEM_UID) {
5480 // The getApplicationInfo() call we make below is not supported in system context. Let
5481 // the call through here, and rely on the fact that ConnectivityService will refuse to
5482 // allow the system to use these APIs anyway.
5483 return;
5484 }
5485
5486 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5487 throw new UnsupportedOperationException(
5488 "This method is not supported in target SDK version " + version + " and above");
5489 }
5490 }
5491
5492 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5493 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5494 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5495 // remove these exemptions. Note that this check is not secure, and apps can still access these
5496 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5497 // so is unsupported and may break in the future. http://b/22728205
5498 private void checkLegacyRoutingApiAccess() {
5499 unsupportedStartingFrom(VERSION_CODES.M);
5500 }
5501
5502 /**
5503 * Binds host resolutions performed by this process to {@code network}.
5504 * {@link #bindProcessToNetwork} takes precedence over this setting.
5505 *
5506 * @param network The {@link Network} to bind host resolutions from the current process to, or
5507 * {@code null} to clear the current binding.
5508 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5509 * @hide
5510 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5511 */
5512 @Deprecated
5513 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5514 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5515 return NetworkUtils.bindProcessToNetworkForHostResolution(
5516 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5517 }
5518
5519 /**
5520 * Device is not restricting metered network activity while application is running on
5521 * background.
5522 */
5523 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5524
5525 /**
5526 * Device is restricting metered network activity while application is running on background,
5527 * but application is allowed to bypass it.
5528 * <p>
5529 * In this state, application should take action to mitigate metered network access.
5530 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5531 */
5532 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5533
5534 /**
5535 * Device is restricting metered network activity while application is running on background.
5536 * <p>
5537 * In this state, application should not try to use the network while running on background,
5538 * because it would be denied.
5539 */
5540 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5541
5542 /**
5543 * A change in the background metered network activity restriction has occurred.
5544 * <p>
5545 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5546 * applies to them.
5547 * <p>
5548 * This is only sent to registered receivers, not manifest receivers.
5549 */
5550 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5551 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5552 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5553
Aaron Huangcff22942021-05-27 16:31:26 +08005554 /** @hide */
5555 @Retention(RetentionPolicy.SOURCE)
5556 @IntDef(flag = false, value = {
5557 RESTRICT_BACKGROUND_STATUS_DISABLED,
5558 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5559 RESTRICT_BACKGROUND_STATUS_ENABLED,
5560 })
5561 public @interface RestrictBackgroundStatus {
5562 }
5563
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005564 /**
5565 * Determines if the calling application is subject to metered network restrictions while
5566 * running on background.
5567 *
5568 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5569 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5570 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5571 */
5572 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5573 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005574 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005575 } catch (RemoteException e) {
5576 throw e.rethrowFromSystemServer();
5577 }
5578 }
5579
5580 /**
5581 * The network watchlist is a list of domains and IP addresses that are associated with
5582 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5583 * currently used by the system for validation purposes.
5584 *
5585 * @return Hash of network watchlist config file. Null if config does not exist.
5586 */
5587 @Nullable
5588 public byte[] getNetworkWatchlistConfigHash() {
5589 try {
5590 return mService.getNetworkWatchlistConfigHash();
5591 } catch (RemoteException e) {
5592 Log.e(TAG, "Unable to get watchlist config hash");
5593 throw e.rethrowFromSystemServer();
5594 }
5595 }
5596
5597 /**
5598 * Returns the {@code uid} of the owner of a network connection.
5599 *
5600 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5601 * IPPROTO_UDP} currently supported.
5602 * @param local The local {@link InetSocketAddress} of a connection.
5603 * @param remote The remote {@link InetSocketAddress} of a connection.
5604 * @return {@code uid} if the connection is found and the app has permission to observe it
5605 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5606 * android.os.Process#INVALID_UID} if the connection is not found.
Sherri Lin443b7182023-02-08 04:49:29 +01005607 * @throws SecurityException if the caller is not the active VpnService for the current
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005608 * user.
Sherri Lin443b7182023-02-08 04:49:29 +01005609 * @throws IllegalArgumentException if an unsupported protocol is requested.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005610 */
5611 public int getConnectionOwnerUid(
5612 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5613 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5614 try {
5615 return mService.getConnectionOwnerUid(connectionInfo);
5616 } catch (RemoteException e) {
5617 throw e.rethrowFromSystemServer();
5618 }
5619 }
5620
5621 private void printStackTrace() {
5622 if (DEBUG) {
5623 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5624 final StringBuffer sb = new StringBuffer();
5625 for (int i = 3; i < callStack.length; i++) {
5626 final String stackTrace = callStack[i].toString();
5627 if (stackTrace == null || stackTrace.contains("android.os")) {
5628 break;
5629 }
5630 sb.append(" [").append(stackTrace).append("]");
5631 }
5632 Log.d(TAG, "StackLog:" + sb.toString());
5633 }
5634 }
5635
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005636 /** @hide */
5637 public TestNetworkManager startOrGetTestNetworkManager() {
5638 final IBinder tnBinder;
5639 try {
5640 tnBinder = mService.startOrGetTestNetworkService();
5641 } catch (RemoteException e) {
5642 throw e.rethrowFromSystemServer();
5643 }
5644
5645 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5646 }
5647
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005648 /** @hide */
5649 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5650 return new ConnectivityDiagnosticsManager(mContext, mService);
5651 }
5652
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005653 /**
5654 * Simulates a Data Stall for the specified Network.
5655 *
5656 * <p>This method should only be used for tests.
5657 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005658 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5659 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005660 *
5661 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005662 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5663 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5664 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005665 * @param network The Network for which a Data Stall is being simluated.
5666 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5667 * @throws SecurityException if the caller is not the owner of the given network.
5668 * @hide
5669 */
5670 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5671 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5672 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005673 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005674 @NonNull Network network, @NonNull PersistableBundle extras) {
5675 try {
5676 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5677 } catch (RemoteException e) {
5678 e.rethrowFromSystemServer();
5679 }
5680 }
5681
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005682 @NonNull
5683 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5684
5685 /**
5686 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5687 * receive available QoS events related to the {@link Network} and local ip + port
5688 * specified within socketInfo.
5689 * <p/>
5690 * The same {@link QosCallback} must be unregistered before being registered a second time,
5691 * otherwise {@link QosCallbackRegistrationException} is thrown.
5692 * <p/>
5693 * This API does not, in itself, require any permission if called with a network that is not
5694 * restricted. However, the underlying implementation currently only supports the IMS network,
5695 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5696 * useful, because they'd never be called back on networks that they would have access to.
5697 *
5698 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5699 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5700 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5701 * @throws RuntimeException if the app already has too many callbacks registered.
5702 *
5703 * Exceptions after the time of registration is passed through
5704 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5705 *
5706 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005707 * @param executor The executor on which the callback will be invoked. The provided
5708 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005709 * callbacks cannot be guaranteed.onQosCallbackRegistered
5710 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005711 *
5712 * @hide
5713 */
5714 @SystemApi
5715 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005716 @CallbackExecutor @NonNull final Executor executor,
5717 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005718 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005719 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005720 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005721
5722 try {
5723 synchronized (mQosCallbackConnections) {
5724 if (getQosCallbackConnection(callback) == null) {
5725 final QosCallbackConnection connection =
5726 new QosCallbackConnection(this, callback, executor);
5727 mQosCallbackConnections.add(connection);
5728 mService.registerQosSocketCallback(socketInfo, connection);
5729 } else {
5730 Log.e(TAG, "registerQosCallback: Callback already registered");
5731 throw new QosCallbackRegistrationException();
5732 }
5733 }
5734 } catch (final RemoteException e) {
5735 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5736
5737 // The same unregister method method is called for consistency even though nothing
5738 // will be sent to the ConnectivityService since the callback was never successfully
5739 // registered.
5740 unregisterQosCallback(callback);
5741 e.rethrowFromSystemServer();
5742 } catch (final ServiceSpecificException e) {
5743 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5744 unregisterQosCallback(callback);
5745 throw convertServiceException(e);
5746 }
5747 }
5748
5749 /**
5750 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5751 * events once unregistered and can be registered a second time.
5752 * <p/>
5753 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5754 *
5755 * @param callback the callback being unregistered
5756 *
5757 * @hide
5758 */
5759 @SystemApi
5760 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5761 Objects.requireNonNull(callback, "The callback must be non-null");
5762 try {
5763 synchronized (mQosCallbackConnections) {
5764 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5765 if (connection != null) {
5766 connection.stopReceivingMessages();
5767 mService.unregisterQosCallback(connection);
5768 mQosCallbackConnections.remove(connection);
5769 } else {
5770 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5771 }
5772 }
5773 } catch (final RemoteException e) {
5774 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5775 e.rethrowFromSystemServer();
5776 }
5777 }
5778
5779 /**
5780 * Gets the connection related to the callback.
5781 *
5782 * @param callback the callback to look up
5783 * @return the related connection
5784 */
5785 @Nullable
5786 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5787 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5788 // Checking by reference here is intentional
5789 if (connection.getCallback() == callback) {
5790 return connection;
5791 }
5792 }
5793 return null;
5794 }
5795
5796 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005797 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005798 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5799 * be used to request that the system provide a network without causing the network to be
5800 * in the foreground.
5801 *
5802 * <p>This method will attempt to find the best network that matches the passed
5803 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5804 * criteria. The platform will evaluate which network is the best at its own discretion.
5805 * Throughput, latency, cost per byte, policy, user preference and other considerations
5806 * may be factored in the decision of what is considered the best network.
5807 *
5808 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5809 * matching this request, while always attempting to match the request to a better network if
5810 * possible. If a better match is found, the platform will switch this request to the now-best
5811 * network and inform the app of the newly best network by invoking
5812 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5813 * will not try to maintain any other network than the best one currently matching the request:
5814 * a network not matching any network request may be disconnected at any time.
5815 *
5816 * <p>For example, an application could use this method to obtain a connected cellular network
5817 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5818 * radio to consume additional power. Or, an application could inform the system that it wants
5819 * a network supporting sending MMSes and have the system let it know about the currently best
5820 * MMS-supporting network through the provided {@link NetworkCallback}.
5821 *
5822 * <p>The status of the request can be followed by listening to the various callbacks described
5823 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5824 * used to direct traffic to the network (although accessing some networks may be subject to
5825 * holding specific permissions). Callers will learn about the specific characteristics of the
5826 * network through
5827 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5828 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5829 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5830 * matching the request at any given time; therefore when a better network matching the request
5831 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5832 * with the new network after which no further updates are given about the previously-best
5833 * network, unless it becomes the best again at some later time. All callbacks are invoked
5834 * in order on the same thread, which by default is a thread created by the framework running
5835 * in the app.
5836 *
5837 * <p>This{@link NetworkRequest} will live until released via
5838 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5839 * which point the system may let go of the network at any time.
5840 *
5841 * <p>It is presently unsupported to request a network with mutable
5842 * {@link NetworkCapabilities} such as
5843 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5844 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5845 * as these {@code NetworkCapabilities} represent states that a particular
5846 * network may never attain, and whether a network will attain these states
5847 * is unknown prior to bringing up the network so the framework does not
5848 * know how to go about satisfying a request with these capabilities.
5849 *
5850 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5851 * number of outstanding requests to 100 per app (identified by their UID), shared with
5852 * all variants of this method, of {@link #registerNetworkCallback} as well as
5853 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5854 * Requesting a network with this method will count toward this limit. If this limit is
5855 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5856 * make sure to unregister the callbacks with
5857 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5858 *
5859 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005860 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5861 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005862 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5863 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005864 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5865 * @throws SecurityException if missing the appropriate permissions.
5866 * @throws RuntimeException if the app already has too many callbacks registered.
5867 *
5868 * @hide
5869 */
5870 @SystemApi(client = MODULE_LIBRARIES)
5871 @SuppressLint("ExecutorRegistration")
5872 @RequiresPermission(anyOf = {
5873 android.Manifest.permission.NETWORK_SETTINGS,
5874 android.Manifest.permission.NETWORK_STACK,
5875 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5876 })
5877 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005878 @NonNull NetworkCallback networkCallback,
5879 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005880 final NetworkCapabilities nc = request.networkCapabilities;
5881 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005882 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005883 }
James Mattis12aeab82021-01-10 14:24:24 -08005884
5885 /**
James Mattis12aeab82021-01-10 14:24:24 -08005886 * Used by automotive devices to set the network preferences used to direct traffic at an
5887 * application level as per the given OemNetworkPreferences. An example use-case would be an
5888 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5889 * vehicle via a particular network.
5890 *
5891 * Calling this will overwrite the existing preference.
5892 *
5893 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5894 * @param executor the executor on which listener will be invoked.
5895 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5896 * communicate completion of setOemNetworkPreference(). This will only be
5897 * called once upon successful completion of setOemNetworkPreference().
5898 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5899 * @throws SecurityException if missing the appropriate permissions.
5900 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005901 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005902 */
James Mattis6e2d7022021-01-26 16:23:52 -08005903 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005904 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005905 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005906 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005907 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005908 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5909 if (null != listener) {
5910 Objects.requireNonNull(executor, "Executor must be non-null");
5911 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005912 final IOnCompleteListener listenerInternal = listener == null ? null :
5913 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005914 @Override
5915 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005916 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005917 }
5918 };
5919
5920 try {
5921 mService.setOemNetworkPreference(preference, listenerInternal);
5922 } catch (RemoteException e) {
5923 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5924 throw e.rethrowFromSystemServer();
5925 }
5926 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005927
Chalard Jeanad565e22021-02-25 17:23:40 +09005928 /**
5929 * Request that a user profile is put by default on a network matching a given preference.
5930 *
5931 * See the documentation for the individual preferences for a description of the supported
5932 * behaviors.
5933 *
5934 * @param profile the profile concerned.
5935 * @param preference the preference for this profile.
5936 * @param executor an executor to execute the listener on. Optional if listener is null.
5937 * @param listener an optional listener to listen for completion of the operation.
5938 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5939 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005940 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5941 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005942 * @hide
5943 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005944 // This function is for establishing per-profile default networking and can only be called by
5945 // the device policy manager, running as the system server. It would make no sense to call it
5946 // on a context for a user because it does not establish a setting on behalf of a user, rather
5947 // it establishes a setting for a user on behalf of the DPM.
5948 @SuppressLint({"UserHandle"})
5949 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005950 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005951 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005952 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005953 @ProfileNetworkPreferencePolicy final int preference,
5954 @Nullable @CallbackExecutor final Executor executor,
5955 @Nullable final Runnable listener) {
5956
5957 ProfileNetworkPreference.Builder preferenceBuilder =
5958 new ProfileNetworkPreference.Builder();
5959 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005960 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5961 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5962 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005963 setProfileNetworkPreferences(profile,
5964 List.of(preferenceBuilder.build()), executor, listener);
5965 }
5966
5967 /**
5968 * Set a list of default network selection policies for a user profile.
5969 *
5970 * Calling this API with a user handle defines the entire policy for that user handle.
5971 * It will overwrite any setting previously set for the same user profile,
5972 * and not affect previously set settings for other handles.
5973 *
5974 * Call this API with an empty list to remove settings for this user profile.
5975 *
5976 * See {@link ProfileNetworkPreference} for more details on each preference
5977 * parameter.
5978 *
5979 * @param profile the user profile for which the preference is being set.
5980 * @param profileNetworkPreferences the list of profile network preferences for the
5981 * provided profile.
5982 * @param executor an executor to execute the listener on. Optional if listener is null.
5983 * @param listener an optional listener to listen for completion of the operation.
5984 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5985 * @throws SecurityException if missing the appropriate permissions.
5986 * @hide
5987 */
5988 @SystemApi(client = MODULE_LIBRARIES)
5989 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5990 public void setProfileNetworkPreferences(
5991 @NonNull final UserHandle profile,
5992 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005993 @Nullable @CallbackExecutor final Executor executor,
5994 @Nullable final Runnable listener) {
5995 if (null != listener) {
5996 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5997 }
5998 final IOnCompleteListener proxy;
5999 if (null == listener) {
6000 proxy = null;
6001 } else {
6002 proxy = new IOnCompleteListener.Stub() {
6003 @Override
6004 public void onComplete() {
6005 executor.execute(listener::run);
6006 }
6007 };
6008 }
6009 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006010 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09006011 } catch (RemoteException e) {
6012 throw e.rethrowFromSystemServer();
6013 }
6014 }
6015
lucaslin5cdbcfb2021-03-12 00:46:33 +08006016 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08006017 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08006018 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08006019 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08006020
6021 /**
6022 * Get the network ID range reserved for IPSec tunnel interfaces.
6023 *
6024 * @return A Range which indicates the network ID range of IPSec tunnel interface.
6025 * @hide
6026 */
6027 @SystemApi(client = MODULE_LIBRARIES)
6028 @NonNull
6029 public static Range<Integer> getIpSecNetIdRange() {
6030 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
6031 }
markchien738ad912021-12-09 18:15:45 +08006032
6033 /**
Junyu Laidf210362023-10-24 02:47:50 +00006034 * Sets data saver switch.
6035 *
6036 * @param enable True if enable.
6037 * @throws IllegalStateException if failed.
6038 * @hide
6039 */
6040 @FlaggedApi(Flags.SET_DATA_SAVER_VIA_CM)
6041 @SystemApi(client = MODULE_LIBRARIES)
6042 @RequiresPermission(anyOf = {
6043 android.Manifest.permission.NETWORK_SETTINGS,
6044 android.Manifest.permission.NETWORK_STACK,
6045 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6046 })
6047 public void setDataSaverEnabled(final boolean enable) {
6048 try {
6049 mService.setDataSaverEnabled(enable);
6050 } catch (RemoteException e) {
6051 throw e.rethrowFromSystemServer();
6052 }
6053 }
6054
6055 /**
markchiene46042b2022-03-02 18:07:35 +08006056 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
6057 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08006058 *
6059 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006060 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08006061 * @hide
6062 */
6063 @SystemApi(client = MODULE_LIBRARIES)
6064 @RequiresPermission(anyOf = {
6065 android.Manifest.permission.NETWORK_SETTINGS,
6066 android.Manifest.permission.NETWORK_STACK,
6067 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6068 })
markchiene46042b2022-03-02 18:07:35 +08006069 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006070 try {
markchiene46042b2022-03-02 18:07:35 +08006071 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08006072 } catch (RemoteException e) {
6073 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006074 }
6075 }
6076
6077 /**
markchiene46042b2022-03-02 18:07:35 +08006078 * Removes the specified UID from the list of UIDs that are allowed to use background data on
6079 * metered networks when background data is restricted. The deny list takes precedence over
6080 * the allow list.
6081 *
6082 * @param uid uid of target app
6083 * @throws IllegalStateException if updating allow list failed.
6084 * @hide
6085 */
6086 @SystemApi(client = MODULE_LIBRARIES)
6087 @RequiresPermission(anyOf = {
6088 android.Manifest.permission.NETWORK_SETTINGS,
6089 android.Manifest.permission.NETWORK_STACK,
6090 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6091 })
6092 public void removeUidFromMeteredNetworkAllowList(final int uid) {
6093 try {
6094 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
6095 } catch (RemoteException e) {
6096 throw e.rethrowFromSystemServer();
6097 }
6098 }
6099
6100 /**
6101 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
6102 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08006103 *
6104 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006105 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08006106 * @hide
6107 */
6108 @SystemApi(client = MODULE_LIBRARIES)
6109 @RequiresPermission(anyOf = {
6110 android.Manifest.permission.NETWORK_SETTINGS,
6111 android.Manifest.permission.NETWORK_STACK,
6112 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6113 })
markchiene46042b2022-03-02 18:07:35 +08006114 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006115 try {
markchiene46042b2022-03-02 18:07:35 +08006116 mService.updateMeteredNetworkDenyList(uid, true /* add */);
6117 } catch (RemoteException e) {
6118 throw e.rethrowFromSystemServer();
6119 }
6120 }
6121
6122 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09006123 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08006124 * networks if background data is not restricted. The deny list takes precedence over the
6125 * allow list.
6126 *
6127 * @param uid uid of target app
6128 * @throws IllegalStateException if updating deny list failed.
6129 * @hide
6130 */
6131 @SystemApi(client = MODULE_LIBRARIES)
6132 @RequiresPermission(anyOf = {
6133 android.Manifest.permission.NETWORK_SETTINGS,
6134 android.Manifest.permission.NETWORK_STACK,
6135 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6136 })
6137 public void removeUidFromMeteredNetworkDenyList(final int uid) {
6138 try {
6139 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08006140 } catch (RemoteException e) {
6141 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08006142 }
6143 }
6144
6145 /**
6146 * Sets a firewall rule for the specified UID on the specified chain.
6147 *
6148 * @param chain target chain.
6149 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08006150 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08006151 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08006152 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08006153 * @hide
6154 */
6155 @SystemApi(client = MODULE_LIBRARIES)
6156 @RequiresPermission(anyOf = {
6157 android.Manifest.permission.NETWORK_SETTINGS,
6158 android.Manifest.permission.NETWORK_STACK,
6159 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6160 })
markchien3c04e662022-03-22 16:29:56 +08006161 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
6162 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08006163 try {
markchien3c04e662022-03-22 16:29:56 +08006164 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08006165 } catch (RemoteException e) {
6166 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006167 }
6168 }
markchien98a6f952022-01-13 23:43:53 +08006169
6170 /**
Motomu Utsumi900b8062023-01-19 16:16:49 +09006171 * Get firewall rule of specified firewall chain on specified uid.
6172 *
6173 * @param chain target chain.
6174 * @param uid target uid
6175 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
6176 * @throws UnsupportedOperationException if called on pre-T devices.
6177 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6178 * cause of the failure.
6179 * @hide
6180 */
6181 @RequiresPermission(anyOf = {
6182 android.Manifest.permission.NETWORK_SETTINGS,
6183 android.Manifest.permission.NETWORK_STACK,
6184 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6185 })
6186 public int getUidFirewallRule(@FirewallChain final int chain, final int uid) {
6187 try {
6188 return mService.getUidFirewallRule(chain, uid);
6189 } catch (RemoteException e) {
6190 throw e.rethrowFromSystemServer();
6191 }
6192 }
6193
6194 /**
markchien98a6f952022-01-13 23:43:53 +08006195 * Enables or disables the specified firewall chain.
6196 *
6197 * @param chain target chain.
6198 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00006199 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08006200 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08006201 * @hide
6202 */
6203 @SystemApi(client = MODULE_LIBRARIES)
6204 @RequiresPermission(anyOf = {
6205 android.Manifest.permission.NETWORK_SETTINGS,
6206 android.Manifest.permission.NETWORK_STACK,
6207 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6208 })
6209 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
6210 try {
6211 mService.setFirewallChainEnabled(chain, enable);
6212 } catch (RemoteException e) {
6213 throw e.rethrowFromSystemServer();
6214 }
6215 }
markchien00a0bed2022-01-13 23:46:13 +08006216
6217 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00006218 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006219 *
6220 * @param chain target chain.
6221 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6222 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006223 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6224 * cause of the failure.
6225 * @hide
6226 */
6227 @RequiresPermission(anyOf = {
6228 android.Manifest.permission.NETWORK_SETTINGS,
6229 android.Manifest.permission.NETWORK_STACK,
6230 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6231 })
6232 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6233 try {
6234 return mService.getFirewallChainEnabled(chain);
6235 } catch (RemoteException e) {
6236 throw e.rethrowFromSystemServer();
6237 }
6238 }
6239
6240 /**
markchien00a0bed2022-01-13 23:46:13 +08006241 * Replaces the contents of the specified UID-based firewall chain.
6242 *
6243 * @param chain target chain to replace.
6244 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006245 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006246 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6247 * @hide
6248 */
6249 @SystemApi(client = MODULE_LIBRARIES)
6250 @RequiresPermission(anyOf = {
6251 android.Manifest.permission.NETWORK_SETTINGS,
6252 android.Manifest.permission.NETWORK_STACK,
6253 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6254 })
6255 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6256 Objects.requireNonNull(uids);
6257 try {
6258 mService.replaceFirewallChain(chain, uids);
6259 } catch (RemoteException e) {
6260 throw e.rethrowFromSystemServer();
6261 }
6262 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006263
Junyu Laie0031522023-08-29 18:32:57 +08006264 /**
Junyu Laic3dc5b62023-09-06 19:10:02 +08006265 * Helper class to track data saver status.
6266 *
6267 * The class will fetch current data saver status from {@link NetworkPolicyManager} when
6268 * initialized, and listening for status changed intent to cache the latest status.
6269 *
6270 * @hide
6271 */
6272 @TargetApi(Build.VERSION_CODES.TIRAMISU) // RECEIVER_NOT_EXPORTED requires T.
6273 @VisibleForTesting(visibility = PRIVATE)
6274 public static class DataSaverStatusTracker extends BroadcastReceiver {
6275 private static final Object sDataSaverStatusTrackerLock = new Object();
6276
6277 private static volatile DataSaverStatusTracker sInstance;
6278
6279 /**
6280 * Gets a static instance of the class.
6281 *
6282 * @param context A {@link Context} for initialization. Note that since the data saver
6283 * status is global on a device, passing any context is equivalent.
6284 * @return The static instance of a {@link DataSaverStatusTracker}.
6285 */
6286 public static DataSaverStatusTracker getInstance(@NonNull Context context) {
6287 if (sInstance == null) {
6288 synchronized (sDataSaverStatusTrackerLock) {
6289 if (sInstance == null) {
6290 sInstance = new DataSaverStatusTracker(context);
6291 }
6292 }
6293 }
6294 return sInstance;
6295 }
6296
6297 private final NetworkPolicyManager mNpm;
6298 // The value updates on the caller's binder thread or UI thread.
6299 private final AtomicBoolean mIsDataSaverEnabled;
6300
6301 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6302 public DataSaverStatusTracker(final Context context) {
6303 // To avoid leaks, take the application context.
6304 final Context appContext;
6305 if (context instanceof Application) {
6306 appContext = context;
6307 } else {
6308 appContext = context.getApplicationContext();
6309 }
6310
6311 if ((appContext.getApplicationInfo().flags & FLAG_PERSISTENT) == 0
6312 && (appContext.getApplicationInfo().flags & FLAG_SYSTEM) == 0) {
6313 throw new IllegalStateException("Unexpected caller: "
6314 + appContext.getApplicationInfo().packageName);
6315 }
6316
6317 mNpm = appContext.getSystemService(NetworkPolicyManager.class);
6318 final IntentFilter filter = new IntentFilter(
6319 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
6320 // The receiver should not receive broadcasts from other Apps.
6321 appContext.registerReceiver(this, filter, Context.RECEIVER_NOT_EXPORTED);
6322 mIsDataSaverEnabled = new AtomicBoolean();
6323 updateDataSaverEnabled();
6324 }
6325
6326 // Runs on caller's UI thread.
6327 @Override
6328 public void onReceive(Context context, Intent intent) {
6329 if (intent.getAction().equals(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED)) {
6330 updateDataSaverEnabled();
6331 } else {
6332 throw new IllegalStateException("Unexpected intent " + intent);
6333 }
6334 }
6335
6336 public boolean getDataSaverEnabled() {
6337 return mIsDataSaverEnabled.get();
6338 }
6339
6340 private void updateDataSaverEnabled() {
6341 // Uid doesn't really matter, but use a fixed UID to make things clearer.
6342 final int dataSaverForCallerUid = mNpm.getRestrictBackgroundStatus(Process.SYSTEM_UID);
6343 mIsDataSaverEnabled.set(dataSaverForCallerUid
6344 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
6345 }
6346 }
6347
6348 /**
6349 * Return whether the network is blocked for the given uid and metered condition.
Junyu Laie0031522023-08-29 18:32:57 +08006350 *
6351 * Similar to {@link NetworkPolicyManager#isUidNetworkingBlocked}, but directly reads the BPF
6352 * maps and therefore considerably faster. For use by the NetworkStack process only.
6353 *
6354 * @param uid The target uid.
Junyu Laic3dc5b62023-09-06 19:10:02 +08006355 * @param isNetworkMetered Whether the target network is metered.
6356 *
6357 * @return True if all networking with the given condition is blocked. Otherwise, false.
Junyu Laie0031522023-08-29 18:32:57 +08006358 * @throws IllegalStateException if the map cannot be opened.
6359 * @throws ServiceSpecificException if the read fails.
6360 * @hide
6361 */
6362 // This isn't protected by a standard Android permission since it can't
6363 // afford to do IPC for performance reasons. Instead, the access control
6364 // is provided by linux file group permission AID_NET_BW_ACCT and the
6365 // selinux context fs_bpf_net*.
6366 // Only the system server process and the network stack have access.
Junyu Laibb594802023-09-04 11:37:03 +08006367 @FlaggedApi(Flags.SUPPORT_IS_UID_NETWORKING_BLOCKED)
6368 @SystemApi(client = MODULE_LIBRARIES)
Junyu Laie0031522023-08-29 18:32:57 +08006369 @RequiresApi(Build.VERSION_CODES.TIRAMISU) // BPF maps were only mainlined in T
6370 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Junyu Laic3dc5b62023-09-06 19:10:02 +08006371 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Junyu Laie0031522023-08-29 18:32:57 +08006372 final BpfNetMapsReader reader = BpfNetMapsReader.getInstance();
6373
Junyu Laic3dc5b62023-09-06 19:10:02 +08006374 final boolean isDataSaverEnabled;
Junyu Lai9e880522023-11-14 15:44:37 +08006375 if (SdkLevel.isAtLeastV()) {
6376 isDataSaverEnabled = reader.getDataSaverEnabled();
6377 } else {
6378 final DataSaverStatusTracker dataSaverStatusTracker =
6379 DataSaverStatusTracker.getInstance(mContext);
6380 isDataSaverEnabled = dataSaverStatusTracker.getDataSaverEnabled();
6381 }
Junyu Laie0031522023-08-29 18:32:57 +08006382
Junyu Laic3dc5b62023-09-06 19:10:02 +08006383 return reader.isUidNetworkingBlocked(uid, isNetworkMetered, isDataSaverEnabled);
Junyu Laie0031522023-08-29 18:32:57 +08006384 }
6385
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006386 /** @hide */
6387 public IBinder getCompanionDeviceManagerProxyService() {
6388 try {
6389 return mService.getCompanionDeviceManagerProxyService();
6390 } catch (RemoteException e) {
6391 throw e.rethrowFromSystemServer();
6392 }
6393 }
Chalard Jean2fb66f12023-08-25 12:50:37 +09006394
6395 private static final Object sRoutingCoordinatorManagerLock = new Object();
6396 @GuardedBy("sRoutingCoordinatorManagerLock")
6397 private static RoutingCoordinatorManager sRoutingCoordinatorManager = null;
6398 /** @hide */
6399 @RequiresApi(Build.VERSION_CODES.S)
6400 public RoutingCoordinatorManager getRoutingCoordinatorManager() {
6401 try {
6402 synchronized (sRoutingCoordinatorManagerLock) {
6403 if (null == sRoutingCoordinatorManager) {
6404 sRoutingCoordinatorManager = new RoutingCoordinatorManager(mContext,
6405 IRoutingCoordinator.Stub.asInterface(
6406 mService.getRoutingCoordinatorService()));
6407 }
6408 return sRoutingCoordinatorManager;
6409 }
6410 } catch (RemoteException e) {
6411 throw e.rethrowFromSystemServer();
6412 }
6413 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006414}