blob: 586e4b0d6bd4bd460382ec6946f2c399867d410f [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;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090086
87import libcore.net.event.NetworkEventDispatcher;
88
89import java.io.IOException;
90import java.io.UncheckedIOException;
91import java.lang.annotation.Retention;
92import java.lang.annotation.RetentionPolicy;
93import java.net.DatagramSocket;
94import java.net.InetAddress;
95import java.net.InetSocketAddress;
96import java.net.Socket;
97import java.util.ArrayList;
98import java.util.Collection;
99import java.util.HashMap;
100import java.util.List;
101import java.util.Map;
102import java.util.Objects;
103import java.util.concurrent.Executor;
104import java.util.concurrent.ExecutorService;
105import java.util.concurrent.Executors;
106import java.util.concurrent.RejectedExecutionException;
Junyu Laic3dc5b62023-09-06 19:10:02 +0800107import java.util.concurrent.atomic.AtomicBoolean;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900108
109/**
110 * Class that answers queries about the state of network connectivity. It also
111 * notifies applications when network connectivity changes.
112 * <p>
113 * The primary responsibilities of this class are to:
114 * <ol>
115 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
116 * <li>Send broadcast intents when network connectivity changes</li>
117 * <li>Attempt to "fail over" to another network when connectivity to a network
118 * is lost</li>
119 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
120 * state of the available networks</li>
121 * <li>Provide an API that allows applications to request and select networks for their data
122 * traffic</li>
123 * </ol>
124 */
125@SystemService(Context.CONNECTIVITY_SERVICE)
126public class ConnectivityManager {
127 private static final String TAG = "ConnectivityManager";
128 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
129
Junyu Laidf210362023-10-24 02:47:50 +0000130 // TODO : remove this class when udc-mainline-prod is abandoned and android.net.flags.Flags is
131 // available here
132 /** @hide */
133 public static class Flags {
134 static final String SET_DATA_SAVER_VIA_CM =
135 "com.android.net.flags.set_data_saver_via_cm";
Junyu Laibb594802023-09-04 11:37:03 +0800136 static final String SUPPORT_IS_UID_NETWORKING_BLOCKED =
137 "com.android.net.flags.support_is_uid_networking_blocked";
Junyu Laidf210362023-10-24 02:47:50 +0000138 }
139
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900140 /**
141 * A change in network connectivity has occurred. A default connection has either
142 * been established or lost. The NetworkInfo for the affected network is
143 * sent as an extra; it should be consulted to see what kind of
144 * connectivity event occurred.
145 * <p/>
146 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
147 * broadcast if they declare the broadcast receiver in their manifest. Apps
148 * will still receive broadcasts if they register their
149 * {@link android.content.BroadcastReceiver} with
150 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
151 * and that context is still valid.
152 * <p/>
153 * If this is a connection that was the result of failing over from a
154 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
155 * set to true.
156 * <p/>
157 * For a loss of connectivity, if the connectivity manager is attempting
158 * to connect (or has already connected) to another network, the
159 * NetworkInfo for the new network is also passed as an extra. This lets
160 * any receivers of the broadcast know that they should not necessarily
161 * tell the user that no data traffic will be possible. Instead, the
162 * receiver should expect another broadcast soon, indicating either that
163 * the failover attempt succeeded (and so there is still overall data
164 * connectivity), or that the failover attempt failed, meaning that all
165 * connectivity has been lost.
166 * <p/>
167 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
168 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900169 * <p />
170 * Note that this broadcast is deprecated and generally tries to implement backwards
171 * compatibility with older versions of Android. As such, it may not reflect new
172 * capabilities of the system, like multiple networks being connected at the same
173 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900174 *
175 * @deprecated apps should use the more versatile {@link #requestNetwork},
176 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
177 * functions instead for faster and more detailed updates about the network
178 * changes they care about.
179 */
180 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
181 @Deprecated
182 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
183
184 /**
185 * The device has connected to a network that has presented a captive
186 * portal, which is blocking Internet connectivity. The user was presented
187 * with a notification that network sign in is required,
188 * and the user invoked the notification's action indicating they
189 * desire to sign in to the network. Apps handling this activity should
190 * facilitate signing in to the network. This action includes a
191 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
192 * the network presenting the captive portal; all communication with the
193 * captive portal must be done using this {@code Network} object.
194 * <p/>
195 * This activity includes a {@link CaptivePortal} extra named
196 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
197 * outcomes of the captive portal sign in to the system:
198 * <ul>
199 * <li> When the app handling this action believes the user has signed in to
200 * the network and the captive portal has been dismissed, the app should
201 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
202 * reevaluate the network. If reevaluation finds the network no longer
203 * subject to a captive portal, the network may become the default active
204 * data network.</li>
205 * <li> When the app handling this action believes the user explicitly wants
206 * to ignore the captive portal and the network, the app should call
207 * {@link CaptivePortal#ignoreNetwork}. </li>
208 * </ul>
209 */
210 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
211 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
212
213 /**
214 * The lookup key for a {@link NetworkInfo} object. Retrieve with
215 * {@link android.content.Intent#getParcelableExtra(String)}.
216 *
217 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
218 * can't accurately represent modern network characteristics.
219 * Please obtain information about networks from the {@link NetworkCapabilities}
220 * or {@link LinkProperties} objects instead.
221 */
222 @Deprecated
223 public static final String EXTRA_NETWORK_INFO = "networkInfo";
224
225 /**
226 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
227 *
228 * @see android.content.Intent#getIntExtra(String, int)
229 * @deprecated The network type is not rich enough to represent the characteristics
230 * of modern networks. Please use {@link NetworkCapabilities} instead,
231 * in particular the transports.
232 */
233 @Deprecated
234 public static final String EXTRA_NETWORK_TYPE = "networkType";
235
236 /**
237 * The lookup key for a boolean that indicates whether a connect event
238 * is for a network to which the connectivity manager was failing over
239 * following a disconnect on another network.
240 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
241 *
242 * @deprecated See {@link NetworkInfo}.
243 */
244 @Deprecated
245 public static final String EXTRA_IS_FAILOVER = "isFailover";
246 /**
247 * The lookup key for a {@link NetworkInfo} object. This is supplied when
248 * there is another network that it may be possible to connect to. Retrieve with
249 * {@link android.content.Intent#getParcelableExtra(String)}.
250 *
251 * @deprecated See {@link NetworkInfo}.
252 */
253 @Deprecated
254 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
255 /**
256 * The lookup key for a boolean that indicates whether there is a
257 * complete lack of connectivity, i.e., no network is available.
258 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
259 */
260 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
261 /**
262 * The lookup key for a string that indicates why an attempt to connect
263 * to a network failed. The string has no particular structure. It is
264 * intended to be used in notifications presented to users. Retrieve
265 * it with {@link android.content.Intent#getStringExtra(String)}.
266 */
267 public static final String EXTRA_REASON = "reason";
268 /**
269 * The lookup key for a string that provides optionally supplied
270 * extra information about the network state. The information
271 * may be passed up from the lower networking layers, and its
272 * meaning may be specific to a particular network type. Retrieve
273 * it with {@link android.content.Intent#getStringExtra(String)}.
274 *
275 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
276 */
277 @Deprecated
278 public static final String EXTRA_EXTRA_INFO = "extraInfo";
279 /**
280 * The lookup key for an int that provides information about
281 * our connection to the internet at large. 0 indicates no connection,
282 * 100 indicates a great connection. Retrieve it with
283 * {@link android.content.Intent#getIntExtra(String, int)}.
284 * {@hide}
285 */
286 public static final String EXTRA_INET_CONDITION = "inetCondition";
287 /**
288 * The lookup key for a {@link CaptivePortal} object included with the
289 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
290 * object can be used to either indicate to the system that the captive
291 * portal has been dismissed or that the user does not want to pursue
292 * signing in to captive portal. Retrieve it with
293 * {@link android.content.Intent#getParcelableExtra(String)}.
294 */
295 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
296
297 /**
298 * Key for passing a URL to the captive portal login activity.
299 */
300 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
301
302 /**
303 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
304 * portal login activity.
305 * {@hide}
306 */
307 @SystemApi
308 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
309 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
310
311 /**
312 * Key for passing a user agent string to the captive portal login activity.
313 * {@hide}
314 */
315 @SystemApi
316 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
317 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
318
319 /**
320 * Broadcast action to indicate the change of data activity status
321 * (idle or active) on a network in a recent period.
322 * The network becomes active when data transmission is started, or
323 * idle if there is no data transmission for a period of time.
324 * {@hide}
325 */
326 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
327 public static final String ACTION_DATA_ACTIVITY_CHANGE =
328 "android.net.conn.DATA_ACTIVITY_CHANGE";
329 /**
330 * The lookup key for an enum that indicates the network device type on which this data activity
331 * change happens.
332 * {@hide}
333 */
334 public static final String EXTRA_DEVICE_TYPE = "deviceType";
335 /**
336 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
337 * it is actively sending or receiving data and {@code false} means it is idle.
338 * {@hide}
339 */
340 public static final String EXTRA_IS_ACTIVE = "isActive";
341 /**
342 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
343 * {@hide}
344 */
345 public static final String EXTRA_REALTIME_NS = "tsNanos";
346
347 /**
348 * Broadcast Action: The setting for background data usage has changed
349 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
350 * <p>
351 * If an application uses the network in the background, it should listen
352 * for this broadcast and stop using the background data if the value is
353 * {@code false}.
354 * <p>
355 *
356 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
357 * of background data depends on several combined factors, and
358 * this broadcast is no longer sent. Instead, when background
359 * data is unavailable, {@link #getActiveNetworkInfo()} will now
360 * appear disconnected. During first boot after a platform
361 * upgrade, this broadcast will be sent once if
362 * {@link #getBackgroundDataSetting()} was {@code false} before
363 * the upgrade.
364 */
365 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
366 @Deprecated
367 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
368 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
369
370 /**
371 * Broadcast Action: The network connection may not be good
372 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
373 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
374 * the network and it's condition.
375 * @hide
376 */
377 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
378 @UnsupportedAppUsage
379 public static final String INET_CONDITION_ACTION =
380 "android.net.conn.INET_CONDITION_ACTION";
381
382 /**
383 * Broadcast Action: A tetherable connection has come or gone.
384 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
385 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
386 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
387 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
388 * the current state of tethering. Each include a list of
389 * interface names in that state (may be empty).
390 * @hide
391 */
392 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
393 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
394 public static final String ACTION_TETHER_STATE_CHANGED =
395 TetheringManager.ACTION_TETHER_STATE_CHANGED;
396
397 /**
398 * @hide
399 * gives a String[] listing all the interfaces configured for
400 * tethering and currently available for tethering.
401 */
402 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
403 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
404
405 /**
406 * @hide
407 * gives a String[] listing all the interfaces currently in local-only
408 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
409 */
410 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
411
412 /**
413 * @hide
414 * gives a String[] listing all the interfaces currently tethered
415 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
416 */
417 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
418 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
419
420 /**
421 * @hide
422 * gives a String[] listing all the interfaces we tried to tether and
423 * failed. Use {@link #getLastTetherError} to find the error code
424 * for any interfaces listed here.
425 */
426 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
427 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
428
429 /**
430 * Broadcast Action: The captive portal tracker has finished its test.
431 * Sent only while running Setup Wizard, in lieu of showing a user
432 * notification.
433 * @hide
434 */
435 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
436 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
437 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
438 /**
439 * The lookup key for a boolean that indicates whether a captive portal was detected.
440 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
441 * @hide
442 */
443 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
444
445 /**
446 * Action used to display a dialog that asks the user whether to connect to a network that is
447 * not validated. This intent is used to start the dialog in settings via startActivity.
448 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800449 * This action includes a {@link Network} typed extra which is called
450 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
451 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900452 * @hide
453 */
lucaslincf6d4502021-03-04 17:09:51 +0800454 @SystemApi(client = MODULE_LIBRARIES)
455 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900456
457 /**
458 * Action used to display a dialog that asks the user whether to avoid a network that is no
459 * longer validated. This intent is used to start the dialog in settings via startActivity.
460 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800461 * This action includes a {@link Network} typed extra which is called
462 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
463 * validated.
464 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900465 * @hide
466 */
lucaslincf6d4502021-03-04 17:09:51 +0800467 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900468 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800469 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900470
471 /**
472 * Action used to display a dialog that asks the user whether to stay connected to a network
473 * that has not validated. This intent is used to start the dialog in settings via
474 * startActivity.
475 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800476 * This action includes a {@link Network} typed extra which is called
477 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
478 * connectivity.
479 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900480 * @hide
481 */
lucaslincf6d4502021-03-04 17:09:51 +0800482 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900483 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800484 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900485
486 /**
paulhub49c8422021-04-07 16:18:13 +0800487 * Clear DNS Cache Action: This is broadcast when networks have changed and old
488 * DNS entries should be cleared.
489 * @hide
490 */
491 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
492 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
493 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
494
495 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900496 * Invalid tethering type.
497 * @see #startTethering(int, boolean, OnStartTetheringCallback)
498 * @hide
499 */
500 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
501
502 /**
503 * Wifi tethering type.
504 * @see #startTethering(int, boolean, OnStartTetheringCallback)
505 * @hide
506 */
507 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900508 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900509
510 /**
511 * USB tethering type.
512 * @see #startTethering(int, boolean, OnStartTetheringCallback)
513 * @hide
514 */
515 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900516 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900517
518 /**
519 * Bluetooth tethering type.
520 * @see #startTethering(int, boolean, OnStartTetheringCallback)
521 * @hide
522 */
523 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900524 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900525
526 /**
527 * Wifi P2p tethering type.
528 * Wifi P2p tethering is set through events automatically, and don't
529 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
530 * @hide
531 */
532 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
533
534 /**
535 * Extra used for communicating with the TetherService. Includes the type of tethering to
536 * enable if any.
537 * @hide
538 */
539 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
540
541 /**
542 * Extra used for communicating with the TetherService. Includes the type of tethering for
543 * which to cancel provisioning.
544 * @hide
545 */
546 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
547
548 /**
549 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
550 * provisioning.
551 * @hide
552 */
553 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
554
555 /**
556 * Tells the TetherService to run a provision check now.
557 * @hide
558 */
559 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
560
561 /**
562 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
563 * which will receive provisioning results. Can be left empty.
564 * @hide
565 */
566 public static final String EXTRA_PROVISION_CALLBACK =
567 TetheringConstants.EXTRA_PROVISION_CALLBACK;
568
569 /**
570 * The absence of a connection type.
571 * @hide
572 */
573 @SystemApi
574 public static final int TYPE_NONE = -1;
575
576 /**
577 * A Mobile data connection. Devices may support more than one.
578 *
579 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
580 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000581 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900582 */
583 @Deprecated
584 public static final int TYPE_MOBILE = 0;
585
586 /**
587 * A WIFI data connection. Devices may support more than one.
588 *
589 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
590 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000591 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900592 */
593 @Deprecated
594 public static final int TYPE_WIFI = 1;
595
596 /**
597 * An MMS-specific Mobile data connection. This network type may use the
598 * same network interface as {@link #TYPE_MOBILE} or it may use a different
599 * one. This is used by applications needing to talk to the carrier's
600 * Multimedia Messaging Service servers.
601 *
602 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
603 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
604 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
605 */
606 @Deprecated
607 public static final int TYPE_MOBILE_MMS = 2;
608
609 /**
610 * A SUPL-specific Mobile data connection. This network type may use the
611 * same network interface as {@link #TYPE_MOBILE} or it may use a different
612 * one. This is used by applications needing to talk to the carrier's
613 * Secure User Plane Location servers for help locating the device.
614 *
615 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
616 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
617 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
618 */
619 @Deprecated
620 public static final int TYPE_MOBILE_SUPL = 3;
621
622 /**
623 * A DUN-specific Mobile data connection. This network type may use the
624 * same network interface as {@link #TYPE_MOBILE} or it may use a different
625 * one. This is sometimes by the system when setting up an upstream connection
626 * for tethering so that the carrier is aware of DUN traffic.
627 *
628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
630 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
631 */
632 @Deprecated
633 public static final int TYPE_MOBILE_DUN = 4;
634
635 /**
636 * A High Priority Mobile data connection. This network type uses the
637 * same network interface as {@link #TYPE_MOBILE} but the routing setup
638 * is different.
639 *
640 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
641 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000642 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900643 */
644 @Deprecated
645 public static final int TYPE_MOBILE_HIPRI = 5;
646
647 /**
648 * A WiMAX data connection.
649 *
650 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
651 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000652 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900653 */
654 @Deprecated
655 public static final int TYPE_WIMAX = 6;
656
657 /**
658 * A Bluetooth data connection.
659 *
660 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
661 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000662 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900663 */
664 @Deprecated
665 public static final int TYPE_BLUETOOTH = 7;
666
667 /**
668 * Fake data connection. This should not be used on shipping devices.
669 * @deprecated This is not used any more.
670 */
671 @Deprecated
672 public static final int TYPE_DUMMY = 8;
673
674 /**
675 * An Ethernet data connection.
676 *
677 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
678 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000679 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900680 */
681 @Deprecated
682 public static final int TYPE_ETHERNET = 9;
683
684 /**
685 * Over the air Administration.
686 * @deprecated Use {@link NetworkCapabilities} instead.
687 * {@hide}
688 */
689 @Deprecated
690 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
691 public static final int TYPE_MOBILE_FOTA = 10;
692
693 /**
694 * IP Multimedia Subsystem.
695 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
696 * {@hide}
697 */
698 @Deprecated
699 @UnsupportedAppUsage
700 public static final int TYPE_MOBILE_IMS = 11;
701
702 /**
703 * Carrier Branded Services.
704 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
705 * {@hide}
706 */
707 @Deprecated
708 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
709 public static final int TYPE_MOBILE_CBS = 12;
710
711 /**
712 * A Wi-Fi p2p connection. Only requesting processes will have access to
713 * the peers connected.
714 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
715 * {@hide}
716 */
717 @Deprecated
718 @SystemApi
719 public static final int TYPE_WIFI_P2P = 13;
720
721 /**
722 * The network to use for initially attaching to the network
723 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
724 * {@hide}
725 */
726 @Deprecated
727 @UnsupportedAppUsage
728 public static final int TYPE_MOBILE_IA = 14;
729
730 /**
731 * Emergency PDN connection for emergency services. This
732 * may include IMS and MMS in emergency situations.
733 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
734 * {@hide}
735 */
736 @Deprecated
737 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
738 public static final int TYPE_MOBILE_EMERGENCY = 15;
739
740 /**
741 * The network that uses proxy to achieve connectivity.
742 * @deprecated Use {@link NetworkCapabilities} instead.
743 * {@hide}
744 */
745 @Deprecated
746 @SystemApi
747 public static final int TYPE_PROXY = 16;
748
749 /**
750 * A virtual network using one or more native bearers.
751 * It may or may not be providing security services.
752 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
753 */
754 @Deprecated
755 public static final int TYPE_VPN = 17;
756
757 /**
758 * A network that is exclusively meant to be used for testing
759 *
760 * @deprecated Use {@link NetworkCapabilities} instead.
761 * @hide
762 */
763 @Deprecated
764 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
765
766 /**
767 * @deprecated Use {@link NetworkCapabilities} instead.
768 * @hide
769 */
770 @Deprecated
771 @Retention(RetentionPolicy.SOURCE)
772 @IntDef(prefix = { "TYPE_" }, value = {
773 TYPE_NONE,
774 TYPE_MOBILE,
775 TYPE_WIFI,
776 TYPE_MOBILE_MMS,
777 TYPE_MOBILE_SUPL,
778 TYPE_MOBILE_DUN,
779 TYPE_MOBILE_HIPRI,
780 TYPE_WIMAX,
781 TYPE_BLUETOOTH,
782 TYPE_DUMMY,
783 TYPE_ETHERNET,
784 TYPE_MOBILE_FOTA,
785 TYPE_MOBILE_IMS,
786 TYPE_MOBILE_CBS,
787 TYPE_WIFI_P2P,
788 TYPE_MOBILE_IA,
789 TYPE_MOBILE_EMERGENCY,
790 TYPE_PROXY,
791 TYPE_VPN,
792 TYPE_TEST
793 })
794 public @interface LegacyNetworkType {}
795
796 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
797 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
798 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
799 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
800 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
801
802 /** {@hide} */
803 public static final int MAX_RADIO_TYPE = TYPE_TEST;
804
805 /** {@hide} */
806 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
807
808 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
809
810 /**
811 * If you want to set the default network preference,you can directly
812 * change the networkAttributes array in framework's config.xml.
813 *
814 * @deprecated Since we support so many more networks now, the single
815 * network default network preference can't really express
816 * the hierarchy. Instead, the default is defined by the
817 * networkAttributes in config.xml. You can determine
818 * the current value by calling {@link #getNetworkPreference()}
819 * from an App.
820 */
821 @Deprecated
822 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
823
824 /**
825 * @hide
826 */
827 public static final int REQUEST_ID_UNSET = 0;
828
829 /**
830 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
831 * This allows to distinguish when unregistering NetworkCallbacks those that were never
832 * registered from those that were already unregistered.
833 * @hide
834 */
835 private static final NetworkRequest ALREADY_UNREGISTERED =
836 new NetworkRequest.Builder().clearCapabilities().build();
837
838 /**
839 * A NetID indicating no Network is selected.
840 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
841 * @hide
842 */
843 public static final int NETID_UNSET = 0;
844
845 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000846 * Flag to indicate that an app is not subject to any restrictions that could result in its
847 * network access blocked.
848 *
849 * @hide
850 */
851 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
852 public static final int BLOCKED_REASON_NONE = 0;
853
854 /**
855 * Flag to indicate that an app is subject to Battery saver restrictions that would
856 * result in its network access being blocked.
857 *
858 * @hide
859 */
860 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
861 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
862
863 /**
864 * Flag to indicate that an app is subject to Doze restrictions that would
865 * result in its network access being blocked.
866 *
867 * @hide
868 */
869 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
870 public static final int BLOCKED_REASON_DOZE = 1 << 1;
871
872 /**
873 * Flag to indicate that an app is subject to App Standby restrictions that would
874 * result in its network access being blocked.
875 *
876 * @hide
877 */
878 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
879 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
880
881 /**
882 * Flag to indicate that an app is subject to Restricted mode restrictions that would
883 * result in its network access being blocked.
884 *
885 * @hide
886 */
887 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
888 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
889
890 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900891 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
892 * is not currently connected.
893 *
894 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
895 *
896 * @hide
897 */
898 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
899 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
900
901 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100902 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
903 * result in its network access being blocked.
904 *
905 * @hide
906 */
907 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
908 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
909
910 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000911 * Flag to indicate that an app is subject to Data saver restrictions that would
912 * result in its metered network access being blocked.
913 *
914 * @hide
915 */
916 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
917 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
918
919 /**
920 * Flag to indicate that an app is subject to user restrictions that would
921 * result in its metered network access being blocked.
922 *
923 * @hide
924 */
925 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
926 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
927
928 /**
929 * Flag to indicate that an app is subject to Device admin restrictions that would
930 * result in its metered network access being blocked.
931 *
932 * @hide
933 */
934 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
935 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
936
937 /**
938 * @hide
939 */
940 @Retention(RetentionPolicy.SOURCE)
941 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
942 BLOCKED_REASON_NONE,
943 BLOCKED_REASON_BATTERY_SAVER,
944 BLOCKED_REASON_DOZE,
945 BLOCKED_REASON_APP_STANDBY,
946 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900947 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100948 BLOCKED_REASON_LOW_POWER_STANDBY,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000949 BLOCKED_METERED_REASON_DATA_SAVER,
950 BLOCKED_METERED_REASON_USER_RESTRICTED,
951 BLOCKED_METERED_REASON_ADMIN_DISABLED,
952 })
953 public @interface BlockedReason {}
954
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900955 /**
956 * Set of blocked reasons that are only applicable on metered networks.
957 *
958 * @hide
959 */
960 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
961 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
962
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900963 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
964 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900965
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900966 /**
markchiene1561fa2021-12-09 22:00:56 +0800967 * Firewall chain for device idle (doze mode).
968 * Allowlist of apps that have network access in device idle.
969 * @hide
970 */
971 @SystemApi(client = MODULE_LIBRARIES)
972 public static final int FIREWALL_CHAIN_DOZABLE = 1;
973
974 /**
975 * Firewall chain used for app standby.
976 * Denylist of apps that do not have network access.
977 * @hide
978 */
979 @SystemApi(client = MODULE_LIBRARIES)
980 public static final int FIREWALL_CHAIN_STANDBY = 2;
981
982 /**
983 * Firewall chain used for battery saver.
984 * Allowlist of apps that have network access when battery saver is on.
985 * @hide
986 */
987 @SystemApi(client = MODULE_LIBRARIES)
988 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
989
990 /**
991 * Firewall chain used for restricted networking mode.
992 * Allowlist of apps that have access in restricted networking mode.
993 * @hide
994 */
995 @SystemApi(client = MODULE_LIBRARIES)
996 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
997
Robert Horvath34cba142022-01-27 19:52:43 +0100998 /**
999 * Firewall chain used for low power standby.
1000 * Allowlist of apps that have access in low power standby.
1001 * @hide
1002 */
1003 @SystemApi(client = MODULE_LIBRARIES)
1004 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
1005
Motomu Utsumib08654c2022-05-11 05:56:26 +00001006 /**
Motomu Utsumid9801492022-06-01 13:57:27 +00001007 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001008 *
1009 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1010 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1011 *
1012 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1013 * independent of the others. The chains can be enabled and disabled independently, and apps can
1014 * be added and removed from each chain independently.
1015 *
1016 * @see #FIREWALL_CHAIN_OEM_DENY_2
1017 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001018 * @hide
1019 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001020 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001021 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1022
1023 /**
1024 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001025 *
1026 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1027 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1028 *
1029 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1030 * independent of the others. The chains can be enabled and disabled independently, and apps can
1031 * be added and removed from each chain independently.
1032 *
1033 * @see #FIREWALL_CHAIN_OEM_DENY_1
1034 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001035 * @hide
1036 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001037 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001038 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1039
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001040 /**
1041 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001042 *
1043 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1044 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1045 *
1046 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1047 * independent of the others. The chains can be enabled and disabled independently, and apps can
1048 * be added and removed from each chain independently.
1049 *
1050 * @see #FIREWALL_CHAIN_OEM_DENY_1
1051 * @see #FIREWALL_CHAIN_OEM_DENY_2
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001052 * @hide
1053 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001054 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001055 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1056
markchiene1561fa2021-12-09 22:00:56 +08001057 /** @hide */
1058 @Retention(RetentionPolicy.SOURCE)
1059 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1060 FIREWALL_CHAIN_DOZABLE,
1061 FIREWALL_CHAIN_STANDBY,
1062 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001063 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001064 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Motomu Utsumid9801492022-06-01 13:57:27 +00001065 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001066 FIREWALL_CHAIN_OEM_DENY_2,
1067 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001068 })
1069 public @interface FirewallChain {}
1070
1071 /**
markchien011a7f52022-03-29 01:07:22 +08001072 * A firewall rule which allows or drops packets depending on existing policy.
1073 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1074 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001075 * @hide
1076 */
1077 @SystemApi(client = MODULE_LIBRARIES)
1078 public static final int FIREWALL_RULE_DEFAULT = 0;
1079
1080 /**
markchien011a7f52022-03-29 01:07:22 +08001081 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1082 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001083 * @hide
1084 */
1085 @SystemApi(client = MODULE_LIBRARIES)
1086 public static final int FIREWALL_RULE_ALLOW = 1;
1087
1088 /**
markchien011a7f52022-03-29 01:07:22 +08001089 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1090 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001091 * @hide
1092 */
1093 @SystemApi(client = MODULE_LIBRARIES)
1094 public static final int FIREWALL_RULE_DENY = 2;
1095
1096 /** @hide */
1097 @Retention(RetentionPolicy.SOURCE)
1098 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1099 FIREWALL_RULE_DEFAULT,
1100 FIREWALL_RULE_ALLOW,
1101 FIREWALL_RULE_DENY
1102 })
1103 public @interface FirewallRule {}
1104
1105 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001106 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1107 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1108 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1109 * methods that take a Context argument.
1110 */
1111 private static ConnectivityManager sInstance;
1112
1113 private final Context mContext;
1114
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001115 @GuardedBy("mTetheringEventCallbacks")
1116 private TetheringManager mTetheringManager;
1117
1118 private TetheringManager getTetheringManager() {
1119 synchronized (mTetheringEventCallbacks) {
1120 if (mTetheringManager == null) {
1121 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1122 }
1123 return mTetheringManager;
1124 }
1125 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001126
1127 /**
1128 * Tests if a given integer represents a valid network type.
1129 * @param networkType the type to be tested
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001130 * @return {@code true} if the type is valid, else {@code false}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001131 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1132 * validate a network type.
1133 */
1134 @Deprecated
1135 public static boolean isNetworkTypeValid(int networkType) {
1136 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1137 }
1138
1139 /**
1140 * Returns a non-localized string representing a given network type.
1141 * ONLY used for debugging output.
1142 * @param type the type needing naming
1143 * @return a String for the given type, or a string version of the type ("87")
1144 * if no name is known.
1145 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1146 * {@hide}
1147 */
1148 @Deprecated
1149 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1150 public static String getNetworkTypeName(int type) {
1151 switch (type) {
1152 case TYPE_NONE:
1153 return "NONE";
1154 case TYPE_MOBILE:
1155 return "MOBILE";
1156 case TYPE_WIFI:
1157 return "WIFI";
1158 case TYPE_MOBILE_MMS:
1159 return "MOBILE_MMS";
1160 case TYPE_MOBILE_SUPL:
1161 return "MOBILE_SUPL";
1162 case TYPE_MOBILE_DUN:
1163 return "MOBILE_DUN";
1164 case TYPE_MOBILE_HIPRI:
1165 return "MOBILE_HIPRI";
1166 case TYPE_WIMAX:
1167 return "WIMAX";
1168 case TYPE_BLUETOOTH:
1169 return "BLUETOOTH";
1170 case TYPE_DUMMY:
1171 return "DUMMY";
1172 case TYPE_ETHERNET:
1173 return "ETHERNET";
1174 case TYPE_MOBILE_FOTA:
1175 return "MOBILE_FOTA";
1176 case TYPE_MOBILE_IMS:
1177 return "MOBILE_IMS";
1178 case TYPE_MOBILE_CBS:
1179 return "MOBILE_CBS";
1180 case TYPE_WIFI_P2P:
1181 return "WIFI_P2P";
1182 case TYPE_MOBILE_IA:
1183 return "MOBILE_IA";
1184 case TYPE_MOBILE_EMERGENCY:
1185 return "MOBILE_EMERGENCY";
1186 case TYPE_PROXY:
1187 return "PROXY";
1188 case TYPE_VPN:
1189 return "VPN";
Junyu Laic9f1ca62022-07-25 16:31:59 +08001190 case TYPE_TEST:
1191 return "TEST";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001192 default:
1193 return Integer.toString(type);
1194 }
1195 }
1196
1197 /**
1198 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001199 */
lucaslin10774b72021-03-17 14:16:01 +08001200 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001201 public void systemReady() {
1202 try {
1203 mService.systemReady();
1204 } catch (RemoteException e) {
1205 throw e.rethrowFromSystemServer();
1206 }
1207 }
1208
1209 /**
1210 * Checks if a given type uses the cellular data connection.
1211 * This should be replaced in the future by a network property.
1212 * @param networkType the type to check
1213 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1214 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1215 * {@hide}
1216 */
1217 @Deprecated
1218 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1219 public static boolean isNetworkTypeMobile(int networkType) {
1220 switch (networkType) {
1221 case TYPE_MOBILE:
1222 case TYPE_MOBILE_MMS:
1223 case TYPE_MOBILE_SUPL:
1224 case TYPE_MOBILE_DUN:
1225 case TYPE_MOBILE_HIPRI:
1226 case TYPE_MOBILE_FOTA:
1227 case TYPE_MOBILE_IMS:
1228 case TYPE_MOBILE_CBS:
1229 case TYPE_MOBILE_IA:
1230 case TYPE_MOBILE_EMERGENCY:
1231 return true;
1232 default:
1233 return false;
1234 }
1235 }
1236
1237 /**
1238 * Checks if the given network type is backed by a Wi-Fi radio.
1239 *
1240 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1241 * @hide
1242 */
1243 @Deprecated
1244 public static boolean isNetworkTypeWifi(int networkType) {
1245 switch (networkType) {
1246 case TYPE_WIFI:
1247 case TYPE_WIFI_P2P:
1248 return true;
1249 default:
1250 return false;
1251 }
1252 }
1253
1254 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001255 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001256 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Junyu Lai35665cc2022-12-19 17:37:48 +08001257 * Specify that the traffic for this user should by follow the default rules:
1258 * applications in the profile designated by the UserHandle behave like any
1259 * other application and use the system default network as their default
1260 * network. Compare other PROFILE_NETWORK_PREFERENCE_* settings.
Chalard Jeanad565e22021-02-25 17:23:40 +09001261 * @hide
1262 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001263 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001264 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1265
1266 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001267 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001268 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001269 * Specify that the traffic for this user should by default go on a network with
1270 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1271 * if no such network is available.
1272 * @hide
1273 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001274 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001275 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1276
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001277 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001278 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001279 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001280 * Specify that the traffic for this user should by default go on a network with
1281 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
Junyu Lai35665cc2022-12-19 17:37:48 +08001282 * should not have a default network at all (that is, network accesses that
1283 * do not specify a network explicitly terminate with an error), even if there
1284 * is a system default network available to apps outside this preference.
1285 * The apps can still use a non-enterprise network if they request it explicitly
1286 * provided that specific network doesn't require any specific permission they
1287 * do not hold.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001288 * @hide
1289 */
1290 @SystemApi(client = MODULE_LIBRARIES)
1291 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1292
Junyu Lai35665cc2022-12-19 17:37:48 +08001293 /**
1294 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
1295 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1296 * Specify that the traffic for this user should by default go on a network with
1297 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}.
1298 * If there is no such network, the apps will have no default
1299 * network at all, even if there are available non-enterprise networks on the
1300 * device (that is, network accesses that do not specify a network explicitly
1301 * terminate with an error). Additionally, the designated apps should be
1302 * blocked from using any non-enterprise network even if they specify it
1303 * explicitly, unless they hold specific privilege overriding this (see
1304 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS}).
1305 * @hide
1306 */
1307 @SystemApi(client = MODULE_LIBRARIES)
1308 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING = 3;
1309
Chalard Jeanad565e22021-02-25 17:23:40 +09001310 /** @hide */
1311 @Retention(RetentionPolicy.SOURCE)
1312 @IntDef(value = {
1313 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001314 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1315 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001316 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001317 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001318 }
1319
1320 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001321 * Specifies the preferred network type. When the device has more
1322 * than one type available the preferred network type will be used.
1323 *
1324 * @param preference the network type to prefer over all others. It is
1325 * unspecified what happens to the old preferred network in the
1326 * overall ordering.
1327 * @deprecated Functionality has been removed as it no longer makes sense,
1328 * with many more than two networks - we'd need an array to express
1329 * preference. Instead we use dynamic network properties of
1330 * the networks to describe their precedence.
1331 */
1332 @Deprecated
1333 public void setNetworkPreference(int preference) {
1334 }
1335
1336 /**
1337 * Retrieves the current preferred network type.
1338 *
1339 * @return an integer representing the preferred network type
1340 *
1341 * @deprecated Functionality has been removed as it no longer makes sense,
1342 * with many more than two networks - we'd need an array to express
1343 * preference. Instead we use dynamic network properties of
1344 * the networks to describe their precedence.
1345 */
1346 @Deprecated
1347 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1348 public int getNetworkPreference() {
1349 return TYPE_NONE;
1350 }
1351
1352 /**
1353 * Returns details about the currently active default data network. When
1354 * connected, this network is the default route for outgoing connections.
1355 * You should always check {@link NetworkInfo#isConnected()} before initiating
1356 * network traffic. This may return {@code null} when there is no default
1357 * network.
1358 * Note that if the default network is a VPN, this method will return the
1359 * NetworkInfo for one of its underlying networks instead, or null if the
1360 * VPN agent did not specify any. Apps interested in learning about VPNs
1361 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1362 *
1363 * @return a {@link NetworkInfo} object for the current default network
1364 * or {@code null} if no default network is currently active
1365 * @deprecated See {@link NetworkInfo}.
1366 */
1367 @Deprecated
1368 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1369 @Nullable
1370 public NetworkInfo getActiveNetworkInfo() {
1371 try {
1372 return mService.getActiveNetworkInfo();
1373 } catch (RemoteException e) {
1374 throw e.rethrowFromSystemServer();
1375 }
1376 }
1377
1378 /**
1379 * Returns a {@link Network} object corresponding to the currently active
1380 * default data network. In the event that the current active default data
1381 * network disconnects, the returned {@code Network} object will no longer
1382 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001383 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001384 *
1385 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001386 * {@code null} if no default network is currently active or if
1387 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001388 */
1389 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1390 @Nullable
1391 public Network getActiveNetwork() {
1392 try {
1393 return mService.getActiveNetwork();
1394 } catch (RemoteException e) {
1395 throw e.rethrowFromSystemServer();
1396 }
1397 }
1398
1399 /**
1400 * Returns a {@link Network} object corresponding to the currently active
1401 * default data network for a specific UID. In the event that the default data
1402 * network disconnects, the returned {@code Network} object will no longer
1403 * be usable. This will return {@code null} when there is no default
1404 * network for the UID.
1405 *
1406 * @return a {@link Network} object for the current default network for the
1407 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001408 *
1409 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001410 */
1411 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1412 @Nullable
1413 public Network getActiveNetworkForUid(int uid) {
1414 return getActiveNetworkForUid(uid, false);
1415 }
1416
1417 /** {@hide} */
1418 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1419 try {
1420 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1421 } catch (RemoteException e) {
1422 throw e.rethrowFromSystemServer();
1423 }
1424 }
1425
lucaslin3ba7cc22022-12-19 02:35:33 +00001426 private static UidRange[] getUidRangeArray(@NonNull Collection<Range<Integer>> ranges) {
1427 Objects.requireNonNull(ranges);
1428 final UidRange[] rangesArray = new UidRange[ranges.size()];
1429 int index = 0;
1430 for (Range<Integer> range : ranges) {
1431 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1432 }
1433
1434 return rangesArray;
1435 }
1436
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001437 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001438 * Adds or removes a requirement for given UID ranges to use the VPN.
1439 *
1440 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1441 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1442 * otherwise have permission to bypass the VPN (e.g., because they have the
1443 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1444 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1445 * set to {@code false}, a previously-added restriction is removed.
1446 * <p>
1447 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1448 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1449 * remove a previously-added range, the exact range must be removed as is.
1450 * <p>
1451 * The changes are applied asynchronously and may not have been applied by the time the method
1452 * returns. Apps will be notified about any changes that apply to them via
1453 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1454 * effect.
1455 * <p>
lucaslin3ba7cc22022-12-19 02:35:33 +00001456 * This method will block the specified UIDs from accessing non-VPN networks, but does not
1457 * affect what the UIDs get as their default network.
1458 * Compare {@link #setVpnDefaultForUids(String, Collection)}, which declares that the UIDs
1459 * should only have a VPN as their default network, but does not block them from accessing other
1460 * networks if they request them explicitly with the {@link Network} API.
1461 * <p>
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001462 * This method should be called only by the VPN code.
1463 *
1464 * @param ranges the UID ranges to restrict
1465 * @param requireVpn whether the specified UID ranges must use a VPN
1466 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001467 * @hide
1468 */
1469 @RequiresPermission(anyOf = {
1470 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001471 android.Manifest.permission.NETWORK_STACK,
1472 android.Manifest.permission.NETWORK_SETTINGS})
1473 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001474 public void setRequireVpnForUids(boolean requireVpn,
1475 @NonNull Collection<Range<Integer>> ranges) {
1476 Objects.requireNonNull(ranges);
1477 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1478 // This method is not necessarily expected to be used outside the system server, so
1479 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1480 // stack process, or by tests.
lucaslin3ba7cc22022-12-19 02:35:33 +00001481 final UidRange[] rangesArray = getUidRangeArray(ranges);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001482 try {
1483 mService.setRequireVpnForUids(requireVpn, rangesArray);
1484 } catch (RemoteException e) {
1485 throw e.rethrowFromSystemServer();
1486 }
1487 }
1488
1489 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001490 * Inform the system that this VPN session should manage the passed UIDs.
1491 *
1492 * A VPN with the specified session ID may call this method to inform the system that the UIDs
1493 * in the specified range are subject to a VPN.
1494 * When this is called, the system will only choose a VPN for the default network of the UIDs in
1495 * the specified ranges.
1496 *
1497 * This method declares that the UIDs in the range will only have a VPN for their default
1498 * network, but does not block the UIDs from accessing other networks (permissions allowing) by
1499 * explicitly requesting it with the {@link Network} API.
1500 * Compare {@link #setRequireVpnForUids(boolean, Collection)}, which does not affect what
1501 * network the UIDs get as default, but will block them from accessing non-VPN networks.
1502 *
1503 * @param session The VPN session which manages the passed UIDs.
1504 * @param ranges The uid ranges which will treat VPN as their only default network.
1505 *
1506 * @hide
1507 */
1508 @RequiresPermission(anyOf = {
1509 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1510 android.Manifest.permission.NETWORK_STACK,
1511 android.Manifest.permission.NETWORK_SETTINGS})
1512 @SystemApi(client = MODULE_LIBRARIES)
1513 public void setVpnDefaultForUids(@NonNull String session,
1514 @NonNull Collection<Range<Integer>> ranges) {
1515 Objects.requireNonNull(ranges);
1516 final UidRange[] rangesArray = getUidRangeArray(ranges);
1517 try {
1518 mService.setVpnNetworkPreference(session, rangesArray);
1519 } catch (RemoteException e) {
1520 throw e.rethrowFromSystemServer();
1521 }
1522 }
1523
1524 /**
chiachangwange0192a72023-02-06 13:25:01 +00001525 * Temporarily set automaticOnOff keeplaive TCP polling alarm timer to 1 second.
1526 *
1527 * TODO: Remove this when the TCP polling design is replaced with callback.
Jean Chalard17cbf062023-02-13 05:07:48 +00001528 * @param timeMs The time of expiry, with System.currentTimeMillis() base. The value should be
1529 * set no more than 5 minutes in the future.
chiachangwange0192a72023-02-06 13:25:01 +00001530 * @hide
1531 */
1532 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
1533 try {
1534 mService.setTestLowTcpPollingTimerForKeepalive(timeMs);
1535 } catch (RemoteException e) {
1536 throw e.rethrowFromSystemServer();
1537 }
1538 }
1539
1540 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001541 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1542 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1543 * but is still supported for backwards compatibility.
1544 * <p>
1545 * This type of VPN is assumed always to use the system default network, and must always declare
1546 * exactly one underlying network, which is the network that was the default when the VPN
1547 * connected.
1548 * <p>
1549 * Calling this method with {@code true} enables legacy behaviour, specifically:
1550 * <ul>
1551 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1552 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1553 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1554 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1555 * underlying the VPN.</li>
1556 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1557 * similarly replaced by the VPN network state.</li>
1558 * <li>Information on current network interfaces passed to NetworkStatsService will not
1559 * include any VPN interfaces.</li>
1560 * </ul>
1561 *
1562 * @param enabled whether legacy lockdown VPN is enabled or disabled
1563 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001564 * @hide
1565 */
1566 @RequiresPermission(anyOf = {
1567 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001568 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001569 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001570 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001571 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1572 try {
1573 mService.setLegacyLockdownVpnEnabled(enabled);
1574 } catch (RemoteException e) {
1575 throw e.rethrowFromSystemServer();
1576 }
1577 }
1578
1579 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001580 * Returns details about the currently active default data network for a given uid.
1581 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001582 *
1583 * @return a {@link NetworkInfo} object for the current default network
1584 * for the given uid or {@code null} if no default network is
1585 * available for the specified uid.
1586 *
1587 * {@hide}
1588 */
1589 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1590 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1591 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1592 return getActiveNetworkInfoForUid(uid, false);
1593 }
1594
1595 /** {@hide} */
1596 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1597 try {
1598 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1599 } catch (RemoteException e) {
1600 throw e.rethrowFromSystemServer();
1601 }
1602 }
1603
1604 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001605 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001606 *
1607 * @param networkType integer specifying which networkType in
1608 * which you're interested.
1609 * @return a {@link NetworkInfo} object for the requested
1610 * network type or {@code null} if the type is not
1611 * supported by the device. If {@code networkType} is
1612 * TYPE_VPN and a VPN is active for the calling app,
1613 * then this method will try to return one of the
1614 * underlying networks for the VPN or null if the
1615 * VPN agent didn't specify any.
1616 *
1617 * @deprecated This method does not support multiple connected networks
1618 * of the same type. Use {@link #getAllNetworks} and
1619 * {@link #getNetworkInfo(android.net.Network)} instead.
1620 */
1621 @Deprecated
1622 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1623 @Nullable
1624 public NetworkInfo getNetworkInfo(int networkType) {
1625 try {
1626 return mService.getNetworkInfo(networkType);
1627 } catch (RemoteException e) {
1628 throw e.rethrowFromSystemServer();
1629 }
1630 }
1631
1632 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001633 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001634 *
1635 * @param network {@link Network} specifying which network
1636 * in which you're interested.
1637 * @return a {@link NetworkInfo} object for the requested
1638 * network or {@code null} if the {@code Network}
1639 * is not valid.
1640 * @deprecated See {@link NetworkInfo}.
1641 */
1642 @Deprecated
1643 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1644 @Nullable
1645 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1646 return getNetworkInfoForUid(network, Process.myUid(), false);
1647 }
1648
1649 /** {@hide} */
1650 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1651 try {
1652 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1653 } catch (RemoteException e) {
1654 throw e.rethrowFromSystemServer();
1655 }
1656 }
1657
1658 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001659 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001660 *
1661 * @return an array of {@link NetworkInfo} objects. Check each
1662 * {@link NetworkInfo#getType} for which type each applies.
1663 *
1664 * @deprecated This method does not support multiple connected networks
1665 * of the same type. Use {@link #getAllNetworks} and
1666 * {@link #getNetworkInfo(android.net.Network)} instead.
1667 */
1668 @Deprecated
1669 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1670 @NonNull
1671 public NetworkInfo[] getAllNetworkInfo() {
1672 try {
1673 return mService.getAllNetworkInfo();
1674 } catch (RemoteException e) {
1675 throw e.rethrowFromSystemServer();
1676 }
1677 }
1678
1679 /**
junyulaib1211372021-03-03 12:09:05 +08001680 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1681 * connected.
1682 * @hide
1683 */
1684 @SystemApi(client = MODULE_LIBRARIES)
1685 @RequiresPermission(anyOf = {
1686 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1687 android.Manifest.permission.NETWORK_STACK,
1688 android.Manifest.permission.NETWORK_SETTINGS})
1689 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001690 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001691 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001692 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001693 } catch (RemoteException e) {
1694 throw e.rethrowFromSystemServer();
1695 }
1696 }
1697
1698 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001699 * Returns the {@link Network} object currently serving a given type, or
1700 * null if the given type is not connected.
1701 *
1702 * @hide
1703 * @deprecated This method does not support multiple connected networks
1704 * of the same type. Use {@link #getAllNetworks} and
1705 * {@link #getNetworkInfo(android.net.Network)} instead.
1706 */
1707 @Deprecated
1708 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1709 @UnsupportedAppUsage
1710 public Network getNetworkForType(int networkType) {
1711 try {
1712 return mService.getNetworkForType(networkType);
1713 } catch (RemoteException e) {
1714 throw e.rethrowFromSystemServer();
1715 }
1716 }
1717
1718 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001719 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001720 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001721 * @deprecated This method does not provide any notification of network state changes, forcing
1722 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1723 * Apps should use methods such as
1724 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1725 * Apps that desire to obtain information about networks that do not apply to them
1726 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1727 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001728 * @return an array of {@link Network} objects.
1729 */
1730 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1731 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001732 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001733 public Network[] getAllNetworks() {
1734 try {
1735 return mService.getAllNetworks();
1736 } catch (RemoteException e) {
1737 throw e.rethrowFromSystemServer();
1738 }
1739 }
1740
1741 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001742 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001743 * the Networks that applications run by the given user will use by default.
1744 * @hide
1745 */
1746 @UnsupportedAppUsage
1747 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1748 try {
1749 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001750 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001751 } catch (RemoteException e) {
1752 throw e.rethrowFromSystemServer();
1753 }
1754 }
1755
1756 /**
1757 * Returns the IP information for the current default network.
1758 *
1759 * @return a {@link LinkProperties} object describing the IP info
1760 * for the current default network, or {@code null} if there
1761 * is no current default network.
1762 *
1763 * {@hide}
1764 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1765 * value of {@link #getActiveNetwork()} instead. In particular,
1766 * this method will return non-null LinkProperties even if the
1767 * app is blocked by policy from using this network.
1768 */
1769 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1770 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1771 public LinkProperties getActiveLinkProperties() {
1772 try {
1773 return mService.getActiveLinkProperties();
1774 } catch (RemoteException e) {
1775 throw e.rethrowFromSystemServer();
1776 }
1777 }
1778
1779 /**
1780 * Returns the IP information for a given network type.
1781 *
1782 * @param networkType the network type of interest.
1783 * @return a {@link LinkProperties} object describing the IP info
1784 * for the given networkType, or {@code null} if there is
1785 * no current default network.
1786 *
1787 * {@hide}
1788 * @deprecated This method does not support multiple connected networks
1789 * of the same type. Use {@link #getAllNetworks},
1790 * {@link #getNetworkInfo(android.net.Network)}, and
1791 * {@link #getLinkProperties(android.net.Network)} instead.
1792 */
1793 @Deprecated
1794 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1795 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1796 public LinkProperties getLinkProperties(int networkType) {
1797 try {
1798 return mService.getLinkPropertiesForType(networkType);
1799 } catch (RemoteException e) {
1800 throw e.rethrowFromSystemServer();
1801 }
1802 }
1803
1804 /**
1805 * Get the {@link LinkProperties} for the given {@link Network}. This
1806 * will return {@code null} if the network is unknown.
1807 *
1808 * @param network The {@link Network} object identifying the network in question.
1809 * @return The {@link LinkProperties} for the network, or {@code null}.
1810 */
1811 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1812 @Nullable
1813 public LinkProperties getLinkProperties(@Nullable Network network) {
1814 try {
1815 return mService.getLinkProperties(network);
1816 } catch (RemoteException e) {
1817 throw e.rethrowFromSystemServer();
1818 }
1819 }
1820
1821 /**
lucaslinc582d502022-01-27 09:07:00 +08001822 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001823 *
lucaslinc582d502022-01-27 09:07:00 +08001824 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1825 * given package, considering its permissions.
1826 *
1827 * @param lp A {@link LinkProperties} which will be redacted.
1828 * @param uid The target uid.
1829 * @param packageName The name of the package, for appops logging.
1830 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1831 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1832 * @hide
1833 */
1834 @RequiresPermission(anyOf = {
1835 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1836 android.Manifest.permission.NETWORK_STACK,
1837 android.Manifest.permission.NETWORK_SETTINGS})
1838 @SystemApi(client = MODULE_LIBRARIES)
1839 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001840 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001841 @NonNull String packageName) {
1842 try {
lucaslind2b06132022-03-02 10:56:57 +08001843 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001844 lp, uid, packageName, getAttributionTag());
1845 } catch (RemoteException e) {
1846 throw e.rethrowFromSystemServer();
1847 }
1848 }
1849
1850 /**
1851 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1852 *
1853 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1854 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1855 * sensitive information. To retrieve this location sensitive information (subject to
1856 * the caller's location permissions), use a {@link NetworkCallback} with the
1857 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1858 *
1859 * This method returns {@code null} if the network is unknown or if the |network| argument
1860 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001861 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001862 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001863 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001864 */
1865 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1866 @Nullable
1867 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1868 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001869 return mService.getNetworkCapabilities(
1870 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001871 } catch (RemoteException e) {
1872 throw e.rethrowFromSystemServer();
1873 }
1874 }
1875
1876 /**
lucaslinc582d502022-01-27 09:07:00 +08001877 * Redact {@link NetworkCapabilities} for a given package.
1878 *
1879 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001880 * to the given package, considering its permissions. If the passed capabilities contain
1881 * location-sensitive information, they will be redacted to the correct degree for the location
1882 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1883 * that level of location. If the UID holds no location permission, the returned object will
1884 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001885 *
1886 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1887 * @param uid The target uid.
1888 * @param packageName The name of the package, for appops logging.
1889 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1890 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1891 * @hide
1892 */
1893 @RequiresPermission(anyOf = {
1894 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1895 android.Manifest.permission.NETWORK_STACK,
1896 android.Manifest.permission.NETWORK_SETTINGS})
1897 @SystemApi(client = MODULE_LIBRARIES)
1898 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001899 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001900 @NonNull NetworkCapabilities nc,
1901 int uid, @NonNull String packageName) {
1902 try {
lucaslind2b06132022-03-02 10:56:57 +08001903 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001904 getAttributionTag());
1905 } catch (RemoteException e) {
1906 throw e.rethrowFromSystemServer();
1907 }
1908 }
1909
1910 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001911 * Gets a URL that can be used for resolving whether a captive portal is present.
1912 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1913 * portal is present.
1914 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1915 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1916 *
1917 * The system network validation may be using different strategies to detect captive portals,
1918 * so this method does not necessarily return a URL used by the system. It only returns a URL
1919 * that may be relevant for other components trying to detect captive portals.
1920 *
1921 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001922 * @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 +09001923 * system.
1924 */
1925 @Deprecated
1926 @SystemApi
1927 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1928 public String getCaptivePortalServerUrl() {
1929 try {
1930 return mService.getCaptivePortalServerUrl();
1931 } catch (RemoteException e) {
1932 throw e.rethrowFromSystemServer();
1933 }
1934 }
1935
1936 /**
1937 * Tells the underlying networking system that the caller wants to
1938 * begin using the named feature. The interpretation of {@code feature}
1939 * is completely up to each networking implementation.
1940 *
1941 * <p>This method requires the caller to hold either the
1942 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1943 * or the ability to modify system settings as determined by
1944 * {@link android.provider.Settings.System#canWrite}.</p>
1945 *
1946 * @param networkType specifies which network the request pertains to
1947 * @param feature the name of the feature to be used
1948 * @return an integer value representing the outcome of the request.
1949 * The interpretation of this value is specific to each networking
1950 * implementation+feature combination, except that the value {@code -1}
1951 * always indicates failure.
1952 *
1953 * @deprecated Deprecated in favor of the cleaner
1954 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1955 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1956 * throw {@code UnsupportedOperationException} if called.
1957 * @removed
1958 */
1959 @Deprecated
1960 public int startUsingNetworkFeature(int networkType, String feature) {
1961 checkLegacyRoutingApiAccess();
1962 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1963 if (netCap == null) {
1964 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1965 feature);
1966 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1967 }
1968
1969 NetworkRequest request = null;
1970 synchronized (sLegacyRequests) {
1971 LegacyRequest l = sLegacyRequests.get(netCap);
1972 if (l != null) {
1973 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1974 renewRequestLocked(l);
1975 if (l.currentNetwork != null) {
1976 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1977 } else {
1978 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1979 }
1980 }
1981
1982 request = requestNetworkForFeatureLocked(netCap);
1983 }
1984 if (request != null) {
1985 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1986 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1987 } else {
1988 Log.d(TAG, " request Failed");
1989 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1990 }
1991 }
1992
1993 /**
1994 * Tells the underlying networking system that the caller is finished
1995 * using the named feature. The interpretation of {@code feature}
1996 * is completely up to each networking implementation.
1997 *
1998 * <p>This method requires the caller to hold either the
1999 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2000 * or the ability to modify system settings as determined by
2001 * {@link android.provider.Settings.System#canWrite}.</p>
2002 *
2003 * @param networkType specifies which network the request pertains to
2004 * @param feature the name of the feature that is no longer needed
2005 * @return an integer value representing the outcome of the request.
2006 * The interpretation of this value is specific to each networking
2007 * implementation+feature combination, except that the value {@code -1}
2008 * always indicates failure.
2009 *
2010 * @deprecated Deprecated in favor of the cleaner
2011 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
2012 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2013 * throw {@code UnsupportedOperationException} if called.
2014 * @removed
2015 */
2016 @Deprecated
2017 public int stopUsingNetworkFeature(int networkType, String feature) {
2018 checkLegacyRoutingApiAccess();
2019 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
2020 if (netCap == null) {
2021 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
2022 feature);
2023 return -1;
2024 }
2025
2026 if (removeRequestForFeature(netCap)) {
2027 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
2028 }
2029 return 1;
2030 }
2031
2032 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2033 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
2034 if (networkType == TYPE_MOBILE) {
2035 switch (feature) {
2036 case "enableCBS":
2037 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
2038 case "enableDUN":
2039 case "enableDUNAlways":
2040 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
2041 case "enableFOTA":
2042 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
2043 case "enableHIPRI":
2044 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
2045 case "enableIMS":
2046 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
2047 case "enableMMS":
2048 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
2049 case "enableSUPL":
2050 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
2051 default:
2052 return null;
2053 }
2054 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
2055 return networkCapabilitiesForType(TYPE_WIFI_P2P);
2056 }
2057 return null;
2058 }
2059
2060 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
2061 if (netCap == null) return TYPE_NONE;
2062 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
2063 return TYPE_MOBILE_CBS;
2064 }
2065 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2066 return TYPE_MOBILE_IMS;
2067 }
2068 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
2069 return TYPE_MOBILE_FOTA;
2070 }
2071 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
2072 return TYPE_MOBILE_DUN;
2073 }
2074 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
2075 return TYPE_MOBILE_SUPL;
2076 }
2077 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2078 return TYPE_MOBILE_MMS;
2079 }
2080 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
2081 return TYPE_MOBILE_HIPRI;
2082 }
2083 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
2084 return TYPE_WIFI_P2P;
2085 }
2086 return TYPE_NONE;
2087 }
2088
2089 private static class LegacyRequest {
2090 NetworkCapabilities networkCapabilities;
2091 NetworkRequest networkRequest;
2092 int expireSequenceNumber;
2093 Network currentNetwork;
2094 int delay = -1;
2095
2096 private void clearDnsBinding() {
2097 if (currentNetwork != null) {
2098 currentNetwork = null;
2099 setProcessDefaultNetworkForHostResolution(null);
2100 }
2101 }
2102
2103 NetworkCallback networkCallback = new NetworkCallback() {
2104 @Override
2105 public void onAvailable(Network network) {
2106 currentNetwork = network;
2107 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
2108 setProcessDefaultNetworkForHostResolution(network);
2109 }
2110 @Override
2111 public void onLost(Network network) {
2112 if (network.equals(currentNetwork)) clearDnsBinding();
2113 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2114 }
2115 };
2116 }
2117
2118 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2119 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2120 new HashMap<>();
2121
2122 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2123 synchronized (sLegacyRequests) {
2124 LegacyRequest l = sLegacyRequests.get(netCap);
2125 if (l != null) return l.networkRequest;
2126 }
2127 return null;
2128 }
2129
2130 private void renewRequestLocked(LegacyRequest l) {
2131 l.expireSequenceNumber++;
2132 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2133 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2134 }
2135
2136 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2137 int ourSeqNum = -1;
2138 synchronized (sLegacyRequests) {
2139 LegacyRequest l = sLegacyRequests.get(netCap);
2140 if (l == null) return;
2141 ourSeqNum = l.expireSequenceNumber;
2142 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2143 }
2144 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2145 }
2146
2147 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2148 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2149 int delay = -1;
2150 int type = legacyTypeForNetworkCapabilities(netCap);
2151 try {
2152 delay = mService.getRestoreDefaultNetworkDelay(type);
2153 } catch (RemoteException e) {
2154 throw e.rethrowFromSystemServer();
2155 }
2156 LegacyRequest l = new LegacyRequest();
2157 l.networkCapabilities = netCap;
2158 l.delay = delay;
2159 l.expireSequenceNumber = 0;
2160 l.networkRequest = sendRequestForNetwork(
2161 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2162 if (l.networkRequest == null) return null;
2163 sLegacyRequests.put(netCap, l);
2164 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2165 return l.networkRequest;
2166 }
2167
2168 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2169 if (delay >= 0) {
2170 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2171 CallbackHandler handler = getDefaultHandler();
2172 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2173 handler.sendMessageDelayed(msg, delay);
2174 }
2175 }
2176
2177 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2178 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2179 final LegacyRequest l;
2180 synchronized (sLegacyRequests) {
2181 l = sLegacyRequests.remove(netCap);
2182 }
2183 if (l == null) return false;
2184 unregisterNetworkCallback(l.networkCallback);
2185 l.clearDnsBinding();
2186 return true;
2187 }
2188
2189 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2190 static {
2191 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2192 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2193 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2194 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2195 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2196 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2197 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2198 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2199 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2200 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2201 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2202 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2203 }
2204
2205 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2206 static {
2207 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2208 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2209 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2210 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2211 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2212 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2213 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2214 }
2215
2216 /**
2217 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2218 * instance suitable for registering a request or callback. Throws an
2219 * IllegalArgumentException if no mapping from the legacy type to
2220 * NetworkCapabilities is known.
2221 *
2222 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2223 * to find the network instead.
2224 * @hide
2225 */
2226 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2227 final NetworkCapabilities nc = new NetworkCapabilities();
2228
2229 // Map from type to transports.
2230 final int NOT_FOUND = -1;
2231 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002232 if (transport == NOT_FOUND) {
2233 throw new IllegalArgumentException("unknown legacy type: " + type);
2234 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002235 nc.addTransportType(transport);
2236
2237 // Map from type to capabilities.
2238 nc.addCapability(sLegacyTypeToCapability.get(
2239 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2240 nc.maybeMarkCapabilitiesRestricted();
2241 return nc;
2242 }
2243
2244 /** @hide */
2245 public static class PacketKeepaliveCallback {
2246 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2247 public PacketKeepaliveCallback() {
2248 }
2249 /** The requested keepalive was successfully started. */
2250 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2251 public void onStarted() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002252 /** The keepalive was resumed after being paused by the system. */
2253 public void onResumed() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002254 /** The keepalive was successfully stopped. */
2255 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2256 public void onStopped() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002257 /** The keepalive was paused automatically by the system. */
2258 public void onPaused() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002259 /** An error occurred. */
2260 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2261 public void onError(int error) {}
2262 }
2263
2264 /**
2265 * Allows applications to request that the system periodically send specific packets on their
2266 * behalf, using hardware offload to save battery power.
2267 *
2268 * To request that the system send keepalives, call one of the methods that return a
2269 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2270 * passing in a non-null callback. If the callback is successfully started, the callback's
2271 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2272 * specifying one of the {@code ERROR_*} constants in this class.
2273 *
2274 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2275 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2276 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2277 *
2278 * @deprecated Use {@link SocketKeepalive} instead.
2279 *
2280 * @hide
2281 */
2282 public class PacketKeepalive {
2283
2284 private static final String TAG = "PacketKeepalive";
2285
2286 /** @hide */
2287 public static final int SUCCESS = 0;
2288
2289 /** @hide */
2290 public static final int NO_KEEPALIVE = -1;
2291
2292 /** @hide */
2293 public static final int BINDER_DIED = -10;
2294
2295 /** The specified {@code Network} is not connected. */
2296 public static final int ERROR_INVALID_NETWORK = -20;
2297 /** The specified IP addresses are invalid. For example, the specified source IP address is
2298 * not configured on the specified {@code Network}. */
2299 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2300 /** The requested port is invalid. */
2301 public static final int ERROR_INVALID_PORT = -22;
2302 /** The packet length is invalid (e.g., too long). */
2303 public static final int ERROR_INVALID_LENGTH = -23;
2304 /** The packet transmission interval is invalid (e.g., too short). */
2305 public static final int ERROR_INVALID_INTERVAL = -24;
2306
2307 /** The hardware does not support this request. */
2308 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2309 /** The hardware returned an error. */
2310 public static final int ERROR_HARDWARE_ERROR = -31;
2311
2312 /** The NAT-T destination port for IPsec */
2313 public static final int NATT_PORT = 4500;
2314
2315 /** The minimum interval in seconds between keepalive packet transmissions */
2316 public static final int MIN_INTERVAL = 10;
2317
2318 private final Network mNetwork;
2319 private final ISocketKeepaliveCallback mCallback;
2320 private final ExecutorService mExecutor;
2321
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002322 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2323 public void stop() {
2324 try {
2325 mExecutor.execute(() -> {
2326 try {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002327 mService.stopKeepalive(mCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002328 } catch (RemoteException e) {
2329 Log.e(TAG, "Error stopping packet keepalive: ", e);
2330 throw e.rethrowFromSystemServer();
2331 }
2332 });
2333 } catch (RejectedExecutionException e) {
2334 // The internal executor has already stopped due to previous event.
2335 }
2336 }
2337
2338 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002339 Objects.requireNonNull(network, "network cannot be null");
2340 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002341 mNetwork = network;
2342 mExecutor = Executors.newSingleThreadExecutor();
2343 mCallback = new ISocketKeepaliveCallback.Stub() {
2344 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002345 public void onStarted() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002346 final long token = Binder.clearCallingIdentity();
2347 try {
2348 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002349 callback.onStarted();
2350 });
2351 } finally {
2352 Binder.restoreCallingIdentity(token);
2353 }
2354 }
2355
2356 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002357 public void onResumed() {
2358 final long token = Binder.clearCallingIdentity();
2359 try {
2360 mExecutor.execute(() -> {
2361 callback.onResumed();
2362 });
2363 } finally {
2364 Binder.restoreCallingIdentity(token);
2365 }
2366 }
2367
2368 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002369 public void onStopped() {
2370 final long token = Binder.clearCallingIdentity();
2371 try {
2372 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002373 callback.onStopped();
2374 });
2375 } finally {
2376 Binder.restoreCallingIdentity(token);
2377 }
2378 mExecutor.shutdown();
2379 }
2380
2381 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002382 public void onPaused() {
2383 final long token = Binder.clearCallingIdentity();
2384 try {
2385 mExecutor.execute(() -> {
2386 callback.onPaused();
2387 });
2388 } finally {
2389 Binder.restoreCallingIdentity(token);
2390 }
2391 mExecutor.shutdown();
2392 }
2393
2394 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002395 public void onError(int error) {
2396 final long token = Binder.clearCallingIdentity();
2397 try {
2398 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002399 callback.onError(error);
2400 });
2401 } finally {
2402 Binder.restoreCallingIdentity(token);
2403 }
2404 mExecutor.shutdown();
2405 }
2406
2407 @Override
2408 public void onDataReceived() {
2409 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2410 // this callback when data is received.
2411 }
2412 };
2413 }
2414 }
2415
2416 /**
2417 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2418 *
2419 * @deprecated Use {@link #createSocketKeepalive} instead.
2420 *
2421 * @hide
2422 */
2423 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2424 public PacketKeepalive startNattKeepalive(
2425 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2426 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2427 final PacketKeepalive k = new PacketKeepalive(network, callback);
2428 try {
2429 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2430 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2431 } catch (RemoteException e) {
2432 Log.e(TAG, "Error starting packet keepalive: ", e);
2433 throw e.rethrowFromSystemServer();
2434 }
2435 return k;
2436 }
2437
2438 // Construct an invalid fd.
2439 private ParcelFileDescriptor createInvalidFd() {
2440 final int invalidFd = -1;
2441 return ParcelFileDescriptor.adoptFd(invalidFd);
2442 }
2443
2444 /**
2445 * Request that keepalives be started on a IPsec NAT-T socket.
2446 *
2447 * @param network The {@link Network} the socket is on.
2448 * @param socket The socket that needs to be kept alive.
2449 * @param source The source address of the {@link UdpEncapsulationSocket}.
2450 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2451 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2452 * must run callback sequentially, otherwise the order of callbacks cannot be
2453 * guaranteed.
2454 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2455 * changes. Must be extended by applications that use this API.
2456 *
2457 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2458 * given socket.
2459 **/
2460 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2461 @NonNull UdpEncapsulationSocket socket,
2462 @NonNull InetAddress source,
2463 @NonNull InetAddress destination,
2464 @NonNull @CallbackExecutor Executor executor,
2465 @NonNull Callback callback) {
2466 ParcelFileDescriptor dup;
2467 try {
2468 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2469 // which cannot be obtained by the app process.
2470 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2471 } catch (IOException ignored) {
2472 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2473 // ERROR_INVALID_SOCKET.
2474 dup = createInvalidFd();
2475 }
2476 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2477 destination, executor, callback);
2478 }
2479
2480 /**
2481 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2482 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2483 *
2484 * @param network The {@link Network} the socket is on.
2485 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2486 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2487 * from that port.
2488 * @param source The source address of the {@link UdpEncapsulationSocket}.
2489 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2490 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2491 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2492 * must run callback sequentially, otherwise the order of callbacks cannot be
2493 * guaranteed.
2494 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2495 * changes. Must be extended by applications that use this API.
2496 *
2497 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2498 * given socket.
2499 * @hide
2500 */
2501 @SystemApi
2502 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2503 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2504 @NonNull ParcelFileDescriptor pfd,
2505 @NonNull InetAddress source,
2506 @NonNull InetAddress destination,
2507 @NonNull @CallbackExecutor Executor executor,
2508 @NonNull Callback callback) {
2509 ParcelFileDescriptor dup;
2510 try {
2511 // TODO: Consider remove unnecessary dup.
2512 dup = pfd.dup();
2513 } catch (IOException ignored) {
2514 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2515 // ERROR_INVALID_SOCKET.
2516 dup = createInvalidFd();
2517 }
2518 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002519 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002520 }
2521
2522 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002523 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002524 *
2525 * @param network The {@link Network} the socket is on.
2526 * @param socket The socket that needs to be kept alive.
2527 * @param executor The executor on which callback will be invoked. This implementation assumes
2528 * the provided {@link Executor} runs the callbacks in sequence with no
2529 * concurrency. Failing this, no guarantee of correctness can be made. It is
2530 * the responsibility of the caller to ensure the executor provides this
2531 * guarantee. A simple way of creating such an executor is with the standard
2532 * tool {@code Executors.newSingleThreadExecutor}.
2533 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2534 * changes. Must be extended by applications that use this API.
2535 *
2536 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2537 * given socket.
2538 * @hide
2539 */
2540 @SystemApi
2541 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2542 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2543 @NonNull Socket socket,
Sherri Lin443b7182023-02-08 04:49:29 +01002544 @NonNull @CallbackExecutor Executor executor,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002545 @NonNull Callback callback) {
2546 ParcelFileDescriptor dup;
2547 try {
2548 dup = ParcelFileDescriptor.fromSocket(socket);
2549 } catch (UncheckedIOException ignored) {
2550 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2551 // ERROR_INVALID_SOCKET.
2552 dup = createInvalidFd();
2553 }
2554 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2555 }
2556
2557 /**
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +09002558 * Get the supported keepalive count for each transport configured in resource overlays.
2559 *
2560 * @return An array of supported keepalive count for each transport type.
2561 * @hide
2562 */
2563 @RequiresPermission(anyOf = { android.Manifest.permission.NETWORK_SETTINGS,
2564 // CTS 13 used QUERY_ALL_PACKAGES to get the resource value, which was implemented
2565 // as below in KeepaliveUtils. Also allow that permission so that KeepaliveUtils can
2566 // use this method and avoid breaking released CTS. Apps that have this permission
2567 // can query the resource themselves anyway.
2568 android.Manifest.permission.QUERY_ALL_PACKAGES })
2569 public int[] getSupportedKeepalives() {
2570 try {
2571 return mService.getSupportedKeepalives();
2572 } catch (RemoteException e) {
2573 throw e.rethrowFromSystemServer();
2574 }
2575 }
2576
2577 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002578 * Ensure that a network route exists to deliver traffic to the specified
2579 * host via the specified network interface. An attempt to add a route that
2580 * already exists is ignored, but treated as successful.
2581 *
2582 * <p>This method requires the caller to hold either the
2583 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2584 * or the ability to modify system settings as determined by
2585 * {@link android.provider.Settings.System#canWrite}.</p>
2586 *
2587 * @param networkType the type of the network over which traffic to the specified
2588 * host is to be routed
2589 * @param hostAddress the IP address of the host to which the route is desired
2590 * @return {@code true} on success, {@code false} on failure
2591 *
2592 * @deprecated Deprecated in favor of the
2593 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2594 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2595 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2596 * throw {@code UnsupportedOperationException} if called.
2597 * @removed
2598 */
2599 @Deprecated
2600 public boolean requestRouteToHost(int networkType, int hostAddress) {
2601 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2602 }
2603
2604 /**
2605 * Ensure that a network route exists to deliver traffic to the specified
2606 * host via the specified network interface. An attempt to add a route that
2607 * already exists is ignored, but treated as successful.
2608 *
2609 * <p>This method requires the caller to hold either the
2610 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2611 * or the ability to modify system settings as determined by
2612 * {@link android.provider.Settings.System#canWrite}.</p>
2613 *
2614 * @param networkType the type of the network over which traffic to the specified
2615 * host is to be routed
2616 * @param hostAddress the IP address of the host to which the route is desired
2617 * @return {@code true} on success, {@code false} on failure
2618 * @hide
2619 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2620 * {@link #bindProcessToNetwork} API.
2621 */
2622 @Deprecated
2623 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002624 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002625 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2626 checkLegacyRoutingApiAccess();
2627 try {
2628 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2629 mContext.getOpPackageName(), getAttributionTag());
2630 } catch (RemoteException e) {
2631 throw e.rethrowFromSystemServer();
2632 }
2633 }
2634
2635 /**
2636 * @return the context's attribution tag
2637 */
2638 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2639 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002640 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002641 }
2642
2643 /**
2644 * Returns the value of the setting for background data usage. If false,
2645 * applications should not use the network if the application is not in the
2646 * foreground. Developers should respect this setting, and check the value
2647 * of this before performing any background data operations.
2648 * <p>
2649 * All applications that have background services that use the network
2650 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2651 * <p>
2652 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2653 * background data depends on several combined factors, and this method will
2654 * always return {@code true}. Instead, when background data is unavailable,
2655 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2656 *
2657 * @return Whether background data usage is allowed.
2658 */
2659 @Deprecated
2660 public boolean getBackgroundDataSetting() {
2661 // assume that background data is allowed; final authority is
2662 // NetworkInfo which may be blocked.
2663 return true;
2664 }
2665
2666 /**
2667 * Sets the value of the setting for background data usage.
2668 *
2669 * @param allowBackgroundData Whether an application should use data while
2670 * it is in the background.
2671 *
2672 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2673 * @see #getBackgroundDataSetting()
2674 * @hide
2675 */
2676 @Deprecated
2677 @UnsupportedAppUsage
2678 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2679 // ignored
2680 }
2681
2682 /**
2683 * @hide
2684 * @deprecated Talk to TelephonyManager directly
2685 */
2686 @Deprecated
2687 @UnsupportedAppUsage
2688 public boolean getMobileDataEnabled() {
2689 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2690 if (tm != null) {
2691 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2692 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2693 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2694 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2695 + " retVal=" + retVal);
2696 return retVal;
2697 }
2698 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2699 return false;
2700 }
2701
2702 /**
2703 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2704 * to find out when the system default network has gone in to a high power state.
2705 */
2706 public interface OnNetworkActiveListener {
2707 /**
2708 * Called on the main thread of the process to report that the current data network
2709 * has become active, and it is now a good time to perform any pending network
2710 * operations. Note that this listener only tells you when the network becomes
2711 * active; if at any other time you want to know whether it is active (and thus okay
2712 * to initiate network traffic), you can retrieve its instantaneous state with
2713 * {@link ConnectivityManager#isDefaultNetworkActive}.
2714 */
2715 void onNetworkActive();
2716 }
2717
Chiachang Wang2de41682021-09-23 10:46:03 +08002718 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002719 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2720 mNetworkActivityListeners = new ArrayMap<>();
2721
2722 /**
2723 * Start listening to reports when the system's default data network is active, meaning it is
2724 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2725 * to determine the current state of the system's default network after registering the
2726 * listener.
2727 * <p>
2728 * If the process default network has been set with
2729 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2730 * reflect the process's default, but the system default.
2731 *
2732 * @param l The listener to be told when the network is active.
2733 */
2734 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002735 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002736 @Override
2737 public void onNetworkActive() throws RemoteException {
2738 l.onNetworkActive();
2739 }
2740 };
2741
Chiachang Wang2de41682021-09-23 10:46:03 +08002742 synchronized (mNetworkActivityListeners) {
2743 try {
2744 mService.registerNetworkActivityListener(rl);
2745 mNetworkActivityListeners.put(l, rl);
2746 } catch (RemoteException e) {
2747 throw e.rethrowFromSystemServer();
2748 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002749 }
2750 }
2751
2752 /**
2753 * Remove network active listener previously registered with
2754 * {@link #addDefaultNetworkActiveListener}.
2755 *
2756 * @param l Previously registered listener.
2757 */
2758 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002759 synchronized (mNetworkActivityListeners) {
2760 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2761 if (rl == null) {
2762 throw new IllegalArgumentException("Listener was not registered.");
2763 }
2764 try {
2765 mService.unregisterNetworkActivityListener(rl);
2766 mNetworkActivityListeners.remove(l);
2767 } catch (RemoteException e) {
2768 throw e.rethrowFromSystemServer();
2769 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002770 }
2771 }
2772
2773 /**
2774 * Return whether the data network is currently active. An active network means that
2775 * it is currently in a high power state for performing data transmission. On some
2776 * types of networks, it may be expensive to move and stay in such a state, so it is
2777 * more power efficient to batch network traffic together when the radio is already in
2778 * this state. This method tells you whether right now is currently a good time to
2779 * initiate network traffic, as the network is already active.
2780 */
2781 public boolean isDefaultNetworkActive() {
2782 try {
lucaslin709eb842021-01-21 02:04:15 +08002783 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002784 } catch (RemoteException e) {
2785 throw e.rethrowFromSystemServer();
2786 }
2787 }
2788
2789 /**
2790 * {@hide}
2791 */
2792 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002793 this(context, service, true /* newStatic */);
2794 }
2795
2796 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002797 mContext = Objects.requireNonNull(context, "missing context");
2798 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002799 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2800 // different ConnectivityManager, but that's still OK considering its usage.
2801 if (sInstance == null && newStatic) {
2802 final Context appContext = mContext.getApplicationContext();
2803 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2804 // If the application context is null, we're either in the system process or
2805 // it's the application context very early in app initialization. In both these
2806 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2807 // service. http://b/27532714 .
2808 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2809 false /* newStatic */);
2810 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002811 }
2812
2813 /** {@hide} */
2814 @UnsupportedAppUsage
2815 public static ConnectivityManager from(Context context) {
2816 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2817 }
2818
2819 /** @hide */
2820 public NetworkRequest getDefaultRequest() {
2821 try {
2822 // This is not racy as the default request is final in ConnectivityService.
2823 return mService.getDefaultRequest();
2824 } catch (RemoteException e) {
2825 throw e.rethrowFromSystemServer();
2826 }
2827 }
2828
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002829 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002830 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002831 * happened.
2832 *
2833 * @return {@code true} iff the package is allowed to write settings.
2834 */
2835 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2836 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2837 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2838 boolean throwException) {
2839 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002840 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002841 }
2842
2843 /**
2844 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2845 * situations where a Context pointer is unavailable.
2846 * @hide
2847 */
2848 @Deprecated
2849 static ConnectivityManager getInstanceOrNull() {
2850 return sInstance;
2851 }
2852
2853 /**
2854 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2855 * situations where a Context pointer is unavailable.
2856 * @hide
2857 */
2858 @Deprecated
2859 @UnsupportedAppUsage
2860 private static ConnectivityManager getInstance() {
2861 if (getInstanceOrNull() == null) {
2862 throw new IllegalStateException("No ConnectivityManager yet constructed");
2863 }
2864 return getInstanceOrNull();
2865 }
2866
2867 /**
2868 * Get the set of tetherable, available interfaces. This list is limited by
2869 * device configuration and current interface existence.
2870 *
2871 * @return an array of 0 or more Strings of tetherable interface names.
2872 *
2873 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2874 * {@hide}
2875 */
2876 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2877 @UnsupportedAppUsage
2878 @Deprecated
2879 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002880 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002881 }
2882
2883 /**
2884 * Get the set of tethered interfaces.
2885 *
2886 * @return an array of 0 or more String of currently tethered interface names.
2887 *
2888 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2889 * {@hide}
2890 */
2891 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2892 @UnsupportedAppUsage
2893 @Deprecated
2894 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002895 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002896 }
2897
2898 /**
2899 * Get the set of interface names which attempted to tether but
2900 * failed. Re-attempting to tether may cause them to reset to the Tethered
2901 * state. Alternatively, causing the interface to be destroyed and recreated
2902 * may cause them to reset to the available state.
2903 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2904 * information on the cause of the errors.
2905 *
2906 * @return an array of 0 or more String indicating the interface names
2907 * which failed to tether.
2908 *
2909 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2910 * {@hide}
2911 */
2912 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2913 @UnsupportedAppUsage
2914 @Deprecated
2915 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002916 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002917 }
2918
2919 /**
2920 * Get the set of tethered dhcp ranges.
2921 *
2922 * @deprecated This method is not supported.
2923 * TODO: remove this function when all of clients are removed.
2924 * {@hide}
2925 */
2926 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2927 @Deprecated
2928 public String[] getTetheredDhcpRanges() {
2929 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2930 }
2931
2932 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002933 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002934 * on the interface, forward and NAT IP packets and forward DNS requests
2935 * to the best active upstream network interface. Note that if no upstream
2936 * IP network interface is available, dhcp will still run and traffic will be
2937 * allowed between the tethered devices and this device, though upstream net
2938 * access will of course fail until an upstream network interface becomes
2939 * active.
2940 *
2941 * <p>This method requires the caller to hold either the
2942 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2943 * or the ability to modify system settings as determined by
2944 * {@link android.provider.Settings.System#canWrite}.</p>
2945 *
2946 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2947 * and WifiStateMachine which need direct access. All other clients should use
2948 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2949 * logic.</p>
2950 *
2951 * @param iface the interface name to tether.
2952 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2953 * @deprecated Use {@link TetheringManager#startTethering} instead
2954 *
2955 * {@hide}
2956 */
2957 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2958 @Deprecated
2959 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002960 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002961 }
2962
2963 /**
2964 * Stop tethering the named interface.
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 untether.
2977 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2978 *
2979 * {@hide}
2980 */
2981 @UnsupportedAppUsage
2982 @Deprecated
2983 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002984 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002985 }
2986
2987 /**
2988 * Check if the device allows for tethering. It may be disabled via
2989 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2990 * due to device configuration.
2991 *
2992 * <p>If this app does not have permission to use this API, it will always
2993 * return false rather than throw an exception.</p>
2994 *
2995 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2996 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2997 *
2998 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2999 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
3000 *
3001 * @return a boolean - {@code true} indicating Tethering is supported.
3002 *
3003 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
3004 * {@hide}
3005 */
3006 @SystemApi
3007 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
3008 android.Manifest.permission.WRITE_SETTINGS})
3009 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003010 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003011 }
3012
3013 /**
3014 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
3015 *
3016 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
3017 * @hide
3018 */
3019 @SystemApi
3020 @Deprecated
3021 public static abstract class OnStartTetheringCallback {
3022 /**
3023 * Called when tethering has been successfully started.
3024 */
3025 public void onTetheringStarted() {}
3026
3027 /**
3028 * Called when starting tethering failed.
3029 */
3030 public void onTetheringFailed() {}
3031 }
3032
3033 /**
3034 * Convenient overload for
3035 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
3036 * handler to run on the current thread's {@link Looper}.
3037 *
3038 * @deprecated Use {@link TetheringManager#startTethering} instead.
3039 * @hide
3040 */
3041 @SystemApi
3042 @Deprecated
3043 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3044 public void startTethering(int type, boolean showProvisioningUi,
3045 final OnStartTetheringCallback callback) {
3046 startTethering(type, showProvisioningUi, callback, null);
3047 }
3048
3049 /**
3050 * Runs tether provisioning for the given type if needed and then starts tethering if
3051 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
3052 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
3053 * schedules tether provisioning re-checks if appropriate.
3054 *
3055 * @param type The type of tethering to start. Must be one of
3056 * {@link ConnectivityManager.TETHERING_WIFI},
3057 * {@link ConnectivityManager.TETHERING_USB}, or
3058 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3059 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
3060 * is one. This should be true the first time this function is called and also any time
3061 * the user can see this UI. It gives users information from their carrier about the
3062 * check failing and how they can sign up for tethering if possible.
3063 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
3064 * of the result of trying to tether.
3065 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3066 *
3067 * @deprecated Use {@link TetheringManager#startTethering} instead.
3068 * @hide
3069 */
3070 @SystemApi
3071 @Deprecated
3072 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3073 public void startTethering(int type, boolean showProvisioningUi,
3074 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003075 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003076
3077 final Executor executor = new Executor() {
3078 @Override
3079 public void execute(Runnable command) {
3080 if (handler == null) {
3081 command.run();
3082 } else {
3083 handler.post(command);
3084 }
3085 }
3086 };
3087
3088 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
3089 @Override
3090 public void onTetheringStarted() {
3091 callback.onTetheringStarted();
3092 }
3093
3094 @Override
3095 public void onTetheringFailed(final int error) {
3096 callback.onTetheringFailed();
3097 }
3098 };
3099
3100 final TetheringRequest request = new TetheringRequest.Builder(type)
3101 .setShouldShowEntitlementUi(showProvisioningUi).build();
3102
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003103 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003104 }
3105
3106 /**
3107 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
3108 * applicable.
3109 *
3110 * @param type The type of tethering to stop. Must be one of
3111 * {@link ConnectivityManager.TETHERING_WIFI},
3112 * {@link ConnectivityManager.TETHERING_USB}, or
3113 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3114 *
3115 * @deprecated Use {@link TetheringManager#stopTethering} instead.
3116 * @hide
3117 */
3118 @SystemApi
3119 @Deprecated
3120 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3121 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003122 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003123 }
3124
3125 /**
3126 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
3127 * upstream status.
3128 *
3129 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
3130 * @hide
3131 */
3132 @SystemApi
3133 @Deprecated
3134 public abstract static class OnTetheringEventCallback {
3135
3136 /**
3137 * Called when tethering upstream changed. This can be called multiple times and can be
3138 * called any time.
3139 *
3140 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
3141 * have any upstream.
3142 */
3143 public void onUpstreamChanged(@Nullable Network network) {}
3144 }
3145
3146 @GuardedBy("mTetheringEventCallbacks")
3147 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
3148 mTetheringEventCallbacks = new ArrayMap<>();
3149
3150 /**
3151 * Start listening to tethering change events. Any new added callback will receive the last
3152 * tethering status right away. If callback is registered when tethering has no upstream or
3153 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3154 * with a null argument. The same callback object cannot be registered twice.
3155 *
3156 * @param executor the executor on which callback will be invoked.
3157 * @param callback the callback to be called when tethering has change events.
3158 *
3159 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3160 * @hide
3161 */
3162 @SystemApi
3163 @Deprecated
3164 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3165 public void registerTetheringEventCallback(
3166 @NonNull @CallbackExecutor Executor executor,
3167 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003168 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003169
3170 final TetheringEventCallback tetherCallback =
3171 new TetheringEventCallback() {
3172 @Override
3173 public void onUpstreamChanged(@Nullable Network network) {
3174 callback.onUpstreamChanged(network);
3175 }
3176 };
3177
3178 synchronized (mTetheringEventCallbacks) {
3179 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003180 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003181 }
3182 }
3183
3184 /**
3185 * Remove tethering event callback previously registered with
3186 * {@link #registerTetheringEventCallback}.
3187 *
3188 * @param callback previously registered callback.
3189 *
3190 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3191 * @hide
3192 */
3193 @SystemApi
3194 @Deprecated
3195 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3196 public void unregisterTetheringEventCallback(
3197 @NonNull final OnTetheringEventCallback callback) {
3198 Objects.requireNonNull(callback, "The callback must be non-null");
3199 synchronized (mTetheringEventCallbacks) {
3200 final TetheringEventCallback tetherCallback =
3201 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003202 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003203 }
3204 }
3205
3206
3207 /**
3208 * Get the list of regular expressions that define any tetherable
3209 * USB network interfaces. If USB tethering is not supported by the
3210 * device, this list should be empty.
3211 *
3212 * @return an array of 0 or more regular expression Strings defining
3213 * what interfaces are considered tetherable usb interfaces.
3214 *
3215 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3216 * {@hide}
3217 */
3218 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3219 @UnsupportedAppUsage
3220 @Deprecated
3221 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003222 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003223 }
3224
3225 /**
3226 * Get the list of regular expressions that define any tetherable
3227 * Wifi network interfaces. If Wifi tethering is not supported by the
3228 * device, this list should be empty.
3229 *
3230 * @return an array of 0 or more regular expression Strings defining
3231 * what interfaces are considered tetherable wifi interfaces.
3232 *
3233 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3234 * {@hide}
3235 */
3236 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3237 @UnsupportedAppUsage
3238 @Deprecated
3239 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003240 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003241 }
3242
3243 /**
3244 * Get the list of regular expressions that define any tetherable
3245 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3246 * device, this list should be empty.
3247 *
3248 * @return an array of 0 or more regular expression Strings defining
3249 * what interfaces are considered tetherable bluetooth interfaces.
3250 *
3251 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3252 *TetheringManager.TetheringInterfaceRegexps)} instead.
3253 * {@hide}
3254 */
3255 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3256 @UnsupportedAppUsage
3257 @Deprecated
3258 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003259 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003260 }
3261
3262 /**
3263 * Attempt to both alter the mode of USB and Tethering of USB. A
3264 * utility method to deal with some of the complexity of USB - will
3265 * attempt to switch to Rndis and subsequently tether the resulting
3266 * interface on {@code true} or turn off tethering and switch off
3267 * Rndis on {@code false}.
3268 *
3269 * <p>This method requires the caller to hold either the
3270 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3271 * or the ability to modify system settings as determined by
3272 * {@link android.provider.Settings.System#canWrite}.</p>
3273 *
3274 * @param enable a boolean - {@code true} to enable tethering
3275 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3276 * @deprecated Use {@link TetheringManager#startTethering} instead
3277 *
3278 * {@hide}
3279 */
3280 @UnsupportedAppUsage
3281 @Deprecated
3282 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003283 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003284 }
3285
3286 /**
3287 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3288 * {@hide}
3289 */
3290 @SystemApi
3291 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003292 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003293 /**
3294 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3295 * {@hide}
3296 */
3297 @Deprecated
3298 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3299 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3300 /**
3301 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3302 * {@hide}
3303 */
3304 @Deprecated
3305 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3306 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3307 /**
3308 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3309 * {@hide}
3310 */
3311 @Deprecated
3312 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3313 /**
3314 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3315 * {@hide}
3316 */
3317 @Deprecated
3318 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3319 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3320 /**
3321 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3322 * {@hide}
3323 */
3324 @Deprecated
3325 public static final int TETHER_ERROR_MASTER_ERROR =
3326 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3327 /**
3328 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3329 * {@hide}
3330 */
3331 @Deprecated
3332 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3333 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3334 /**
3335 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3336 * {@hide}
3337 */
3338 @Deprecated
3339 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3340 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3341 /**
3342 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3343 * {@hide}
3344 */
3345 @Deprecated
3346 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3347 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3348 /**
3349 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3350 * {@hide}
3351 */
3352 @Deprecated
3353 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3354 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3355 /**
3356 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3357 * {@hide}
3358 */
3359 @Deprecated
3360 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3361 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3362 /**
3363 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3364 * {@hide}
3365 */
3366 @SystemApi
3367 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003368 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003369 /**
3370 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3371 * {@hide}
3372 */
3373 @Deprecated
3374 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3375 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3376 /**
3377 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3378 * {@hide}
3379 */
3380 @SystemApi
3381 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003382 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003383
3384 /**
3385 * Get a more detailed error code after a Tethering or Untethering
3386 * request asynchronously failed.
3387 *
3388 * @param iface The name of the interface of interest
3389 * @return error The error code of the last error tethering or untethering the named
3390 * interface
3391 *
3392 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3393 * {@hide}
3394 */
3395 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3396 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3397 @Deprecated
3398 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003399 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003400 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3401 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3402 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3403 // instead.
3404 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3405 }
3406 return error;
3407 }
3408
3409 /** @hide */
3410 @Retention(RetentionPolicy.SOURCE)
3411 @IntDef(value = {
3412 TETHER_ERROR_NO_ERROR,
3413 TETHER_ERROR_PROVISION_FAILED,
3414 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3415 })
3416 public @interface EntitlementResultCode {
3417 }
3418
3419 /**
3420 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3421 * entitlement succeeded.
3422 *
3423 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3424 * @hide
3425 */
3426 @SystemApi
3427 @Deprecated
3428 public interface OnTetheringEntitlementResultListener {
3429 /**
3430 * Called to notify entitlement result.
3431 *
3432 * @param resultCode an int value of entitlement result. It may be one of
3433 * {@link #TETHER_ERROR_NO_ERROR},
3434 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3435 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3436 */
3437 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3438 }
3439
3440 /**
3441 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003442 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3443 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003444 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003445 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003446 * any reason will update the cached value.
3447 *
3448 * @param type the downstream type of tethering. Must be one of
3449 * {@link #TETHERING_WIFI},
3450 * {@link #TETHERING_USB}, or
3451 * {@link #TETHERING_BLUETOOTH}.
3452 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3453 * @param executor the executor on which callback will be invoked.
3454 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3455 * notify the caller of the result of entitlement check. The listener may be called zero
3456 * or one time.
3457 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3458 * {@hide}
3459 */
3460 @SystemApi
3461 @Deprecated
3462 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3463 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3464 @NonNull @CallbackExecutor Executor executor,
3465 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003466 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003467 ResultReceiver wrappedListener = new ResultReceiver(null) {
3468 @Override
3469 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003470 final long token = Binder.clearCallingIdentity();
3471 try {
3472 executor.execute(() -> {
3473 listener.onTetheringEntitlementResult(resultCode);
3474 });
3475 } finally {
3476 Binder.restoreCallingIdentity(token);
3477 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003478 }
3479 };
3480
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003481 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003482 showEntitlementUi);
3483 }
3484
3485 /**
3486 * Report network connectivity status. This is currently used only
3487 * to alter status bar UI.
3488 * <p>This method requires the caller to hold the permission
3489 * {@link android.Manifest.permission#STATUS_BAR}.
3490 *
3491 * @param networkType The type of network you want to report on
3492 * @param percentage The quality of the connection 0 is bad, 100 is good
3493 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3494 * {@hide}
3495 */
3496 public void reportInetCondition(int networkType, int percentage) {
3497 printStackTrace();
3498 try {
3499 mService.reportInetCondition(networkType, percentage);
3500 } catch (RemoteException e) {
3501 throw e.rethrowFromSystemServer();
3502 }
3503 }
3504
3505 /**
3506 * Report a problem network to the framework. This provides a hint to the system
3507 * that there might be connectivity problems on this network and may cause
3508 * the framework to re-evaluate network connectivity and/or switch to another
3509 * network.
3510 *
3511 * @param network The {@link Network} the application was attempting to use
3512 * or {@code null} to indicate the current default network.
3513 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3514 * working and non-working connectivity.
3515 */
3516 @Deprecated
3517 public void reportBadNetwork(@Nullable Network network) {
3518 printStackTrace();
3519 try {
3520 // One of these will be ignored because it matches system's current state.
3521 // The other will trigger the necessary reevaluation.
3522 mService.reportNetworkConnectivity(network, true);
3523 mService.reportNetworkConnectivity(network, false);
3524 } catch (RemoteException e) {
3525 throw e.rethrowFromSystemServer();
3526 }
3527 }
3528
3529 /**
3530 * Report to the framework whether a network has working connectivity.
3531 * This provides a hint to the system that a particular network is providing
3532 * working connectivity or not. In response the framework may re-evaluate
3533 * the network's connectivity and might take further action thereafter.
3534 *
3535 * @param network The {@link Network} the application was attempting to use
3536 * or {@code null} to indicate the current default network.
3537 * @param hasConnectivity {@code true} if the application was able to successfully access the
3538 * Internet using {@code network} or {@code false} if not.
3539 */
3540 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3541 printStackTrace();
3542 try {
3543 mService.reportNetworkConnectivity(network, hasConnectivity);
3544 } catch (RemoteException e) {
3545 throw e.rethrowFromSystemServer();
3546 }
3547 }
3548
3549 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003550 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003551 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003552 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3553 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3554 * accessing any network, regardless of what the settings for that network are.
3555 *
3556 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3557 * proxy is likely to break networking on multiple networks. This method is only meant
3558 * for device policy clients looking to do general internal filtering or similar use cases.
3559 *
chiachangwang9473c592022-07-15 02:25:52 +00003560 * @see #getGlobalProxy
3561 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003562 *
3563 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3564 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003565 * @hide
3566 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003567 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003568 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003569 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003570 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003571 try {
3572 mService.setGlobalProxy(p);
3573 } catch (RemoteException e) {
3574 throw e.rethrowFromSystemServer();
3575 }
3576 }
3577
3578 /**
3579 * Retrieve any network-independent global HTTP proxy.
3580 *
3581 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3582 * if no global HTTP proxy is set.
3583 * @hide
3584 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003585 @SystemApi(client = MODULE_LIBRARIES)
3586 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003587 public ProxyInfo getGlobalProxy() {
3588 try {
3589 return mService.getGlobalProxy();
3590 } catch (RemoteException e) {
3591 throw e.rethrowFromSystemServer();
3592 }
3593 }
3594
3595 /**
3596 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3597 * network-specific HTTP proxy. If {@code network} is null, the
3598 * network-specific proxy returned is the proxy of the default active
3599 * network.
3600 *
3601 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3602 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3603 * or when {@code network} is {@code null},
3604 * the {@code ProxyInfo} for the default active network. Returns
3605 * {@code null} when no proxy applies or the caller doesn't have
3606 * permission to use {@code network}.
3607 * @hide
3608 */
3609 public ProxyInfo getProxyForNetwork(Network network) {
3610 try {
3611 return mService.getProxyForNetwork(network);
3612 } catch (RemoteException e) {
3613 throw e.rethrowFromSystemServer();
3614 }
3615 }
3616
3617 /**
3618 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3619 * otherwise if this process is bound to a {@link Network} using
3620 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3621 * the default network's proxy is returned.
3622 *
3623 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3624 * HTTP proxy is active.
3625 */
3626 @Nullable
3627 public ProxyInfo getDefaultProxy() {
3628 return getProxyForNetwork(getBoundNetworkForProcess());
3629 }
3630
3631 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003632 * Returns whether the hardware supports the given network type.
3633 *
3634 * This doesn't indicate there is coverage or such a network is available, just whether the
3635 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3636 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003637 *
3638 * @param networkType The network type we'd like to check
3639 * @return {@code true} if supported, else {@code false}
3640 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3641 * @hide
3642 */
3643 @Deprecated
3644 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3645 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3646 public boolean isNetworkSupported(int networkType) {
3647 try {
3648 return mService.isNetworkSupported(networkType);
3649 } catch (RemoteException e) {
3650 throw e.rethrowFromSystemServer();
3651 }
3652 }
3653
3654 /**
3655 * Returns if the currently active data network is metered. A network is
3656 * classified as metered when the user is sensitive to heavy data usage on
3657 * that connection due to monetary costs, data limitations or
3658 * battery/performance issues. You should check this before doing large
3659 * data transfers, and warn the user or delay the operation until another
3660 * network is available.
3661 *
3662 * @return {@code true} if large transfers should be avoided, otherwise
3663 * {@code false}.
3664 */
3665 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3666 public boolean isActiveNetworkMetered() {
3667 try {
3668 return mService.isActiveNetworkMetered();
3669 } catch (RemoteException e) {
3670 throw e.rethrowFromSystemServer();
3671 }
3672 }
3673
3674 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003675 * Set sign in error notification to visible or invisible
3676 *
3677 * @hide
3678 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3679 */
3680 @Deprecated
3681 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3682 String action) {
3683 try {
3684 mService.setProvisioningNotificationVisible(visible, networkType, action);
3685 } catch (RemoteException e) {
3686 throw e.rethrowFromSystemServer();
3687 }
3688 }
3689
3690 /**
3691 * Set the value for enabling/disabling airplane mode
3692 *
3693 * @param enable whether to enable airplane mode or not
3694 *
3695 * @hide
3696 */
3697 @RequiresPermission(anyOf = {
3698 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3699 android.Manifest.permission.NETWORK_SETTINGS,
3700 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3701 android.Manifest.permission.NETWORK_STACK})
3702 @SystemApi
3703 public void setAirplaneMode(boolean enable) {
3704 try {
3705 mService.setAirplaneMode(enable);
3706 } catch (RemoteException e) {
3707 throw e.rethrowFromSystemServer();
3708 }
3709 }
3710
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003711 /**
3712 * Registers the specified {@link NetworkProvider}.
3713 * Each listener must only be registered once. The listener can be unregistered with
3714 * {@link #unregisterNetworkProvider}.
3715 *
3716 * @param provider the provider to register
3717 * @return the ID of the provider. This ID must be used by the provider when registering
3718 * {@link android.net.NetworkAgent}s.
3719 * @hide
3720 */
3721 @SystemApi
3722 @RequiresPermission(anyOf = {
3723 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3724 android.Manifest.permission.NETWORK_FACTORY})
3725 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3726 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3727 throw new IllegalStateException("NetworkProviders can only be registered once");
3728 }
3729
3730 try {
3731 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3732 provider.getName());
3733 provider.setProviderId(providerId);
3734 } catch (RemoteException e) {
3735 throw e.rethrowFromSystemServer();
3736 }
3737 return provider.getProviderId();
3738 }
3739
3740 /**
3741 * Unregisters the specified NetworkProvider.
3742 *
3743 * @param provider the provider to unregister
3744 * @hide
3745 */
3746 @SystemApi
3747 @RequiresPermission(anyOf = {
3748 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3749 android.Manifest.permission.NETWORK_FACTORY})
3750 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3751 try {
3752 mService.unregisterNetworkProvider(provider.getMessenger());
3753 } catch (RemoteException e) {
3754 throw e.rethrowFromSystemServer();
3755 }
3756 provider.setProviderId(NetworkProvider.ID_NONE);
3757 }
3758
Chalard Jeand1b498b2021-01-05 08:40:09 +09003759 /**
3760 * Register or update a network offer with ConnectivityService.
3761 *
3762 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003763 * them to networking requests made by apps or the system. A callback identifies an offer
3764 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3765 * score and the capabilities of the network it might be able to bring up ; these act as
3766 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003767 * provider.
3768 *
3769 * The provider is under no obligation to be able to bring up the network it offers at any
3770 * given time. Instead, this mechanism is meant to limit requests received by providers
3771 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3772 * the quality of the network satisfying a given request to their own offer.
3773 *
3774 * An offer can be updated by calling this again with the same callback object. This is
3775 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3776 * provider with the changes caused by the changes in the offer.
3777 *
3778 * @param provider The provider making this offer.
3779 * @param score The prospective score of the network.
3780 * @param caps The prospective capabilities of the network.
3781 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003782 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003783 */
3784 @RequiresPermission(anyOf = {
3785 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3786 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003787 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003788 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3789 @NonNull final INetworkOfferCallback callback) {
3790 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003791 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003792 Objects.requireNonNull(score, "null score"),
3793 Objects.requireNonNull(caps, "null caps"),
3794 Objects.requireNonNull(callback, "null callback"));
3795 } catch (RemoteException e) {
3796 throw e.rethrowFromSystemServer();
3797 }
3798 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003799
Chalard Jeand1b498b2021-01-05 08:40:09 +09003800 /**
3801 * Withdraw a network offer made with {@link #offerNetwork}.
3802 *
3803 * @param callback The callback passed at registration time. This must be the same object
3804 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003805 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003806 */
3807 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3808 try {
3809 mService.unofferNetwork(Objects.requireNonNull(callback));
3810 } catch (RemoteException e) {
3811 throw e.rethrowFromSystemServer();
3812 }
3813 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003814 /** @hide exposed via the NetworkProvider class. */
3815 @RequiresPermission(anyOf = {
3816 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3817 android.Manifest.permission.NETWORK_FACTORY})
3818 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3819 try {
3820 mService.declareNetworkRequestUnfulfillable(request);
3821 } catch (RemoteException e) {
3822 throw e.rethrowFromSystemServer();
3823 }
3824 }
3825
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003826 /**
3827 * @hide
3828 * Register a NetworkAgent with ConnectivityService.
3829 * @return Network corresponding to NetworkAgent.
3830 */
3831 @RequiresPermission(anyOf = {
3832 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3833 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003834 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3835 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3836 @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId) {
3837 return registerNetworkAgent(na, ni, lp, nc, null /* localNetworkConfig */, score, config,
3838 providerId);
3839 }
3840
3841 /**
3842 * @hide
3843 * Register a NetworkAgent with ConnectivityService.
3844 * @return Network corresponding to NetworkAgent.
3845 */
3846 @RequiresPermission(anyOf = {
3847 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3848 android.Manifest.permission.NETWORK_FACTORY})
3849 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3850 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3851 @Nullable LocalNetworkConfig localNetworkConfig, @NonNull NetworkScore score,
3852 @NonNull NetworkAgentConfig config, int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003853 try {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003854 return mService.registerNetworkAgent(na, ni, lp, nc, score, localNetworkConfig, config,
3855 providerId);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003856 } catch (RemoteException e) {
3857 throw e.rethrowFromSystemServer();
3858 }
3859 }
3860
3861 /**
3862 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3863 * changes. Should be extended by applications wanting notifications.
3864 *
3865 * A {@code NetworkCallback} is registered by calling
3866 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3867 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3868 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3869 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3870 * A {@code NetworkCallback} should be registered at most once at any time.
3871 * A {@code NetworkCallback} that has been unregistered can be registered again.
3872 */
3873 public static class NetworkCallback {
3874 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003875 * No flags associated with this callback.
3876 * @hide
3877 */
3878 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003879
Roshan Piuse08bc182020-12-22 15:10:42 -08003880 /**
lucaslinc582d502022-01-27 09:07:00 +08003881 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3882 *
3883 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3884 * Prior to Android 12, this information is always returned to apps holding the appropriate
3885 * permission, possibly noting that the app has used location.
3886 * <p>In Android 12 and above, by default the sent objects do not contain any location
3887 * information, even if the app holds the necessary permissions, and the system does not
3888 * take note of location usage by the app. Apps can request that location information is
3889 * included, in which case the system will check location permission and the location
3890 * toggle state, and take note of location usage by the app if any such information is
3891 * returned.
3892 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003893 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3894 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3895 * <p>
3896 * These include:
3897 * <li> Some transport info instances (retrieved via
3898 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3899 * contain location sensitive information.
3900 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003901 * sensitive for wifi suggestor apps (i.e using
3902 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003903 * </p>
3904 * <p>
3905 * Note:
3906 * <li> Retrieving this location sensitive information (subject to app's location
3907 * permissions) will be noted by system. </li>
3908 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003909 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003910 */
Roshan Pius189d0092021-03-11 21:16:44 -08003911 // Note: Some existing fields which are location sensitive may still be included without
3912 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003913 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3914
3915 /** @hide */
3916 @Retention(RetentionPolicy.SOURCE)
3917 @IntDef(flag = true, prefix = "FLAG_", value = {
3918 FLAG_NONE,
3919 FLAG_INCLUDE_LOCATION_INFO
3920 })
3921 public @interface Flag { }
3922
3923 /**
3924 * All the valid flags for error checking.
3925 */
3926 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3927
3928 public NetworkCallback() {
3929 this(FLAG_NONE);
3930 }
3931
3932 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003933 if ((flags & VALID_FLAGS) != flags) {
3934 throw new IllegalArgumentException("Invalid flags");
3935 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003936 mFlags = flags;
3937 }
3938
3939 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003940 * Called when the framework connects to a new network to evaluate whether it satisfies this
3941 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3942 * callback. There is no guarantee that this new network will satisfy any requests, or that
3943 * the network will stay connected for longer than the time necessary to evaluate it.
3944 * <p>
3945 * Most applications <b>should not</b> act on this callback, and should instead use
3946 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3947 * the framework in properly evaluating the network &mdash; for example, an application that
3948 * can automatically log in to a captive portal without user intervention.
3949 *
3950 * @param network The {@link Network} of the network that is being evaluated.
3951 *
3952 * @hide
3953 */
3954 public void onPreCheck(@NonNull Network network) {}
3955
3956 /**
3957 * Called when the framework connects and has declared a new network ready for use.
3958 * This callback may be called more than once if the {@link Network} that is
3959 * satisfying the request changes.
3960 *
3961 * @param network The {@link Network} of the satisfying network.
3962 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3963 * @param linkProperties The {@link LinkProperties} of the satisfying network.
Chalard Jean22350c92023-10-07 19:21:45 +09003964 * @param localInfo The {@link LocalNetworkInfo} of the satisfying network, or null
3965 * if this network is not a local network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003966 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3967 * @hide
3968 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003969 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003970 @NonNull NetworkCapabilities networkCapabilities,
Chalard Jean22350c92023-10-07 19:21:45 +09003971 @NonNull LinkProperties linkProperties,
3972 @Nullable LocalNetworkInfo localInfo,
3973 @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003974 // Internally only this method is called when a new network is available, and
3975 // it calls the callback in the same way and order that older versions used
3976 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003977 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
Chalard Jean22350c92023-10-07 19:21:45 +09003978 if (null != localInfo) onLocalNetworkInfoChanged(network, localInfo);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003979 onBlockedStatusChanged(network, blocked);
3980 }
3981
3982 /**
3983 * Legacy variant of onAvailable that takes a boolean blocked reason.
3984 *
3985 * This method has never been public API, but it's not final, so there may be apps that
3986 * implemented it and rely on it being called. Do our best not to break them.
3987 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3988 * this method is called. There does not seem to be a way to avoid this.
3989 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3990 *
3991 * @hide
3992 */
3993 public void onAvailable(@NonNull Network network,
3994 @NonNull NetworkCapabilities networkCapabilities,
Chalard Jean22350c92023-10-07 19:21:45 +09003995 @NonNull LinkProperties linkProperties,
3996 boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003997 onAvailable(network);
3998 if (!networkCapabilities.hasCapability(
3999 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
4000 onNetworkSuspended(network);
4001 }
4002 onCapabilitiesChanged(network, networkCapabilities);
4003 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004004 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004005 }
4006
4007 /**
4008 * Called when the framework connects and has declared a new network ready for use.
4009 *
4010 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
4011 * be available at the same time, and onAvailable will be called for each of these as they
4012 * appear.
4013 *
4014 * <p>For callbacks registered with {@link #requestNetwork} and
4015 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
4016 * is the new best network for this request and is now tracked by this callback ; this
4017 * callback will no longer receive method calls about other networks that may have been
4018 * passed to this method previously. The previously-best network may have disconnected, or
4019 * it may still be around and the newly-best network may simply be better.
4020 *
4021 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
4022 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
4023 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
4024 * to {@link #onBlockedStatusChanged(Network, boolean)}.
4025 *
4026 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4027 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4028 * this callback as this is prone to race conditions (there is no guarantee the objects
4029 * returned by these methods will be current). Instead, wait for a call to
4030 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
4031 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
4032 * to be well-ordered with respect to other callbacks.
4033 *
4034 * @param network The {@link Network} of the satisfying network.
4035 */
4036 public void onAvailable(@NonNull Network network) {}
4037
4038 /**
4039 * Called when the network is about to be lost, typically because there are no outstanding
4040 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
4041 * with the new replacement network for graceful handover. This method is not guaranteed
4042 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
4043 * network is suddenly disconnected.
4044 *
4045 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4046 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4047 * this callback as this is prone to race conditions ; calling these methods while in a
4048 * callback may return an outdated or even a null object.
4049 *
4050 * @param network The {@link Network} that is about to be lost.
4051 * @param maxMsToLive The time in milliseconds the system intends to keep the network
4052 * connected for graceful handover; note that the network may still
4053 * suffer a hard loss at any time.
4054 */
4055 public void onLosing(@NonNull Network network, int maxMsToLive) {}
4056
4057 /**
4058 * Called when a network disconnects or otherwise no longer satisfies this request or
4059 * callback.
4060 *
4061 * <p>If the callback was registered with requestNetwork() or
4062 * registerDefaultNetworkCallback(), it will only be invoked against the last network
4063 * returned by onAvailable() when that network is lost and no other network satisfies
4064 * the criteria of the request.
4065 *
4066 * <p>If the callback was registered with registerNetworkCallback() it will be called for
4067 * each network which no longer satisfies the criteria of the callback.
4068 *
4069 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4070 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4071 * this callback as this is prone to race conditions ; calling these methods while in a
4072 * callback may return an outdated or even a null object.
4073 *
4074 * @param network The {@link Network} lost.
4075 */
4076 public void onLost(@NonNull Network network) {}
4077
4078 /**
4079 * Called if no network is found within the timeout time specified in
4080 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
4081 * requested network request cannot be fulfilled (whether or not a timeout was
4082 * specified). When this callback is invoked the associated
4083 * {@link NetworkRequest} will have already been removed and released, as if
4084 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
4085 */
4086 public void onUnavailable() {}
4087
4088 /**
4089 * Called when the network corresponding to this request changes capabilities but still
4090 * satisfies the requested criteria.
4091 *
4092 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4093 * to be called immediately after {@link #onAvailable}.
4094 *
4095 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
4096 * ConnectivityManager methods in this callback as this is prone to race conditions :
4097 * calling these methods while in a callback may return an outdated or even a null object.
4098 *
4099 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08004100 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004101 * network.
4102 */
4103 public void onCapabilitiesChanged(@NonNull Network network,
4104 @NonNull NetworkCapabilities networkCapabilities) {}
4105
4106 /**
4107 * Called when the network corresponding to this request changes {@link LinkProperties}.
4108 *
4109 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4110 * to be called immediately after {@link #onAvailable}.
4111 *
4112 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
4113 * ConnectivityManager methods in this callback as this is prone to race conditions :
4114 * calling these methods while in a callback may return an outdated or even a null object.
4115 *
4116 * @param network The {@link Network} whose link properties have changed.
4117 * @param linkProperties The new {@link LinkProperties} for this network.
4118 */
4119 public void onLinkPropertiesChanged(@NonNull Network network,
4120 @NonNull LinkProperties linkProperties) {}
4121
4122 /**
Chalard Jean22350c92023-10-07 19:21:45 +09004123 * Called when there is a change in the {@link LocalNetworkInfo} for this network.
4124 *
4125 * This is only called for local networks, that is those with the
4126 * NET_CAPABILITY_LOCAL_NETWORK network capability.
4127 *
4128 * @param network the {@link Network} whose local network info has changed.
4129 * @param localNetworkInfo the new {@link LocalNetworkInfo} for this network.
4130 * @hide
4131 */
4132 public void onLocalNetworkInfoChanged(@NonNull Network network,
4133 @NonNull LocalNetworkInfo localNetworkInfo) {}
4134
4135 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004136 * Called when the network the framework connected to for this request suspends data
4137 * transmission temporarily.
4138 *
4139 * <p>This generally means that while the TCP connections are still live temporarily
4140 * network data fails to transfer. To give a specific example, this is used on cellular
4141 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4142 * means read operations on sockets on this network will block once the buffers are
4143 * drained, and write operations will block once the buffers are full.
4144 *
4145 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4146 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4147 * this callback as this is prone to race conditions (there is no guarantee the objects
4148 * returned by these methods will be current).
4149 *
4150 * @hide
4151 */
4152 public void onNetworkSuspended(@NonNull Network network) {}
4153
4154 /**
4155 * Called when the network the framework connected to for this request
4156 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4157 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4158
4159 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4160 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4161 * this callback as this is prone to race conditions : calling these methods while in a
4162 * callback may return an outdated or even a null object.
4163 *
4164 * @hide
4165 */
4166 public void onNetworkResumed(@NonNull Network network) {}
4167
4168 /**
4169 * Called when access to the specified network is blocked or unblocked.
4170 *
4171 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4172 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4173 * this callback as this is prone to race conditions : calling these methods while in a
4174 * callback may return an outdated or even a null object.
4175 *
4176 * @param network The {@link Network} whose blocked status has changed.
4177 * @param blocked The blocked status of this {@link Network}.
4178 */
4179 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4180
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004181 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004182 * Called when access to the specified network is blocked or unblocked, or the reason for
4183 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004184 *
4185 * If a NetworkCallback object implements this method,
4186 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4187 *
4188 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4189 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4190 * this callback as this is prone to race conditions : calling these methods while in a
4191 * callback may return an outdated or even a null object.
4192 *
4193 * @param network The {@link Network} whose blocked status has changed.
4194 * @param blocked The blocked status of this {@link Network}.
4195 * @hide
4196 */
4197 @SystemApi(client = MODULE_LIBRARIES)
4198 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4199 onBlockedStatusChanged(network, blocked != 0);
4200 }
4201
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004202 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004203 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004204 }
4205
4206 /**
4207 * Constant error codes used by ConnectivityService to communicate about failures and errors
4208 * across a Binder boundary.
4209 * @hide
4210 */
4211 public interface Errors {
4212 int TOO_MANY_REQUESTS = 1;
4213 }
4214
4215 /** @hide */
4216 public static class TooManyRequestsException extends RuntimeException {}
4217
4218 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4219 switch (e.errorCode) {
4220 case Errors.TOO_MANY_REQUESTS:
4221 return new TooManyRequestsException();
4222 default:
4223 Log.w(TAG, "Unknown service error code " + e.errorCode);
4224 return new RuntimeException(e);
4225 }
4226 }
4227
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004228 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004229 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004230 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004231 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004232 /** @hide arg1 = TTL */
Chalard Jean22350c92023-10-07 19:21:45 +09004233 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004234 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004235 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004236 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004237 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004238 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004239 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004240 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004241 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004242 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Chalard Jean22350c92023-10-07 19:21:45 +09004243 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004244 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004245 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004246 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004247 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004248 /** @hide */
Chalard Jean22350c92023-10-07 19:21:45 +09004249 public static final int CALLBACK_BLK_CHANGED = 11;
4250 /** @hide */
4251 public static final int CALLBACK_LOCAL_NETWORK_INFO_CHANGED = 12;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004252
4253 /** @hide */
4254 public static String getCallbackName(int whichCallback) {
4255 switch (whichCallback) {
4256 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4257 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4258 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4259 case CALLBACK_LOST: return "CALLBACK_LOST";
4260 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4261 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4262 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4263 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4264 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4265 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4266 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Chalard Jean22350c92023-10-07 19:21:45 +09004267 case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: return "CALLBACK_LOCAL_NETWORK_INFO_CHANGED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004268 default:
4269 return Integer.toString(whichCallback);
4270 }
4271 }
4272
zhujiatai79b0de92022-09-22 15:44:02 +08004273 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004274 private static final String TAG = "ConnectivityManager.CallbackHandler";
4275 private static final boolean DBG = false;
4276
4277 CallbackHandler(Looper looper) {
4278 super(looper);
4279 }
4280
4281 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004282 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004283 }
4284
4285 @Override
4286 public void handleMessage(Message message) {
4287 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004288 // the sInstance can't be null because to send this message a ConnectivityManager
4289 // instance must have been created prior to creating the thread on which this
4290 // Handler is running.
4291 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004292 return;
4293 }
4294
4295 final NetworkRequest request = getObject(message, NetworkRequest.class);
4296 final Network network = getObject(message, Network.class);
4297 final NetworkCallback callback;
4298 synchronized (sCallbacks) {
4299 callback = sCallbacks.get(request);
4300 if (callback == null) {
4301 Log.w(TAG,
4302 "callback not found for " + getCallbackName(message.what) + " message");
4303 return;
4304 }
4305 if (message.what == CALLBACK_UNAVAIL) {
4306 sCallbacks.remove(request);
4307 callback.networkRequest = ALREADY_UNREGISTERED;
4308 }
4309 }
4310 if (DBG) {
4311 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4312 }
4313
4314 switch (message.what) {
4315 case CALLBACK_PRECHECK: {
4316 callback.onPreCheck(network);
4317 break;
4318 }
4319 case CALLBACK_AVAILABLE: {
4320 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4321 LinkProperties lp = getObject(message, LinkProperties.class);
Chalard Jean22350c92023-10-07 19:21:45 +09004322 LocalNetworkInfo lni = getObject(message, LocalNetworkInfo.class);
4323 callback.onAvailable(network, cap, lp, lni, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004324 break;
4325 }
4326 case CALLBACK_LOSING: {
4327 callback.onLosing(network, message.arg1);
4328 break;
4329 }
4330 case CALLBACK_LOST: {
4331 callback.onLost(network);
4332 break;
4333 }
4334 case CALLBACK_UNAVAIL: {
4335 callback.onUnavailable();
4336 break;
4337 }
4338 case CALLBACK_CAP_CHANGED: {
4339 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4340 callback.onCapabilitiesChanged(network, cap);
4341 break;
4342 }
4343 case CALLBACK_IP_CHANGED: {
4344 LinkProperties lp = getObject(message, LinkProperties.class);
4345 callback.onLinkPropertiesChanged(network, lp);
4346 break;
4347 }
Chalard Jean22350c92023-10-07 19:21:45 +09004348 case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
4349 final LocalNetworkInfo info = getObject(message, LocalNetworkInfo.class);
4350 callback.onLocalNetworkInfoChanged(network, info);
4351 break;
4352 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004353 case CALLBACK_SUSPENDED: {
4354 callback.onNetworkSuspended(network);
4355 break;
4356 }
4357 case CALLBACK_RESUMED: {
4358 callback.onNetworkResumed(network);
4359 break;
4360 }
4361 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004362 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004363 }
4364 }
4365 }
4366
4367 private <T> T getObject(Message msg, Class<T> c) {
4368 return (T) msg.getData().getParcelable(c.getSimpleName());
4369 }
4370 }
4371
4372 private CallbackHandler getDefaultHandler() {
4373 synchronized (sCallbacks) {
4374 if (sCallbackHandler == null) {
4375 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4376 }
4377 return sCallbackHandler;
4378 }
4379 }
4380
4381 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4382 private static CallbackHandler sCallbackHandler;
4383
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004384 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4385 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4386 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004387 printStackTrace();
4388 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004389 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4390 throw new IllegalArgumentException("null NetworkCapabilities");
4391 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004392 final NetworkRequest request;
4393 final String callingPackageName = mContext.getOpPackageName();
4394 try {
4395 synchronized(sCallbacks) {
4396 if (callback.networkRequest != null
4397 && callback.networkRequest != ALREADY_UNREGISTERED) {
4398 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4399 // and requests (http://b/20701525).
4400 Log.e(TAG, "NetworkCallback was already registered");
4401 }
4402 Messenger messenger = new Messenger(handler);
4403 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004404 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004405 if (reqType == LISTEN) {
4406 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004407 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004408 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004409 } else {
4410 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004411 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4412 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004413 }
4414 if (request != null) {
4415 sCallbacks.put(request, callback);
4416 }
4417 callback.networkRequest = request;
4418 }
4419 } catch (RemoteException e) {
4420 throw e.rethrowFromSystemServer();
4421 } catch (ServiceSpecificException e) {
4422 throw convertServiceException(e);
4423 }
4424 return request;
4425 }
4426
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004427 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4428 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4429 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4430 legacyType, handler);
4431 }
4432
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004433 /**
4434 * Helper function to request a network with a particular legacy type.
4435 *
4436 * This API is only for use in internal system code that requests networks with legacy type and
4437 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4438 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4439 *
4440 * @param request {@link NetworkRequest} describing this request.
4441 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4442 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4443 * be a positive value (i.e. >0).
4444 * @param legacyType to specify the network type(#TYPE_*).
4445 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4446 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4447 * the callback must not be shared - it uniquely specifies this request.
4448 *
4449 * @hide
4450 */
4451 @SystemApi
4452 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4453 public void requestNetwork(@NonNull NetworkRequest request,
4454 int timeoutMs, int legacyType, @NonNull Handler handler,
4455 @NonNull NetworkCallback networkCallback) {
4456 if (legacyType == TYPE_NONE) {
4457 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4458 }
4459 CallbackHandler cbHandler = new CallbackHandler(handler);
4460 NetworkCapabilities nc = request.networkCapabilities;
4461 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4462 }
4463
4464 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004465 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004466 *
4467 * <p>This method will attempt to find the best network that matches the passed
4468 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4469 * criteria. The platform will evaluate which network is the best at its own discretion.
4470 * Throughput, latency, cost per byte, policy, user preference and other considerations
4471 * may be factored in the decision of what is considered the best network.
4472 *
4473 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4474 * matching this request, while always attempting to match the request to a better network if
4475 * possible. If a better match is found, the platform will switch this request to the now-best
4476 * network and inform the app of the newly best network by invoking
4477 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4478 * will not try to maintain any other network than the best one currently matching the request:
4479 * a network not matching any network request may be disconnected at any time.
4480 *
4481 * <p>For example, an application could use this method to obtain a connected cellular network
4482 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4483 * radio to consume additional power. Or, an application could inform the system that it wants
4484 * a network supporting sending MMSes and have the system let it know about the currently best
4485 * MMS-supporting network through the provided {@link NetworkCallback}.
4486 *
4487 * <p>The status of the request can be followed by listening to the various callbacks described
4488 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4489 * used to direct traffic to the network (although accessing some networks may be subject to
4490 * holding specific permissions). Callers will learn about the specific characteristics of the
4491 * network through
4492 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4493 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4494 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4495 * matching the request at any given time; therefore when a better network matching the request
4496 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4497 * with the new network after which no further updates are given about the previously-best
4498 * network, unless it becomes the best again at some later time. All callbacks are invoked
4499 * in order on the same thread, which by default is a thread created by the framework running
4500 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004501 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004502 * callbacks are invoked.
4503 *
4504 * <p>This{@link NetworkRequest} will live until released via
4505 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4506 * which point the system may let go of the network at any time.
4507 *
4508 * <p>A version of this method which takes a timeout is
4509 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4510 * wait for a limited amount of time for the network to become unavailable.
4511 *
4512 * <p>It is presently unsupported to request a network with mutable
4513 * {@link NetworkCapabilities} such as
4514 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4515 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4516 * as these {@code NetworkCapabilities} represent states that a particular
4517 * network may never attain, and whether a network will attain these states
4518 * is unknown prior to bringing up the network so the framework does not
4519 * know how to go about satisfying a request with these capabilities.
4520 *
4521 * <p>This method requires the caller to hold either the
4522 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4523 * or the ability to modify system settings as determined by
4524 * {@link android.provider.Settings.System#canWrite}.</p>
4525 *
4526 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4527 * number of outstanding requests to 100 per app (identified by their UID), shared with
4528 * all variants of this method, of {@link #registerNetworkCallback} as well as
4529 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4530 * Requesting a network with this method will count toward this limit. If this limit is
4531 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4532 * make sure to unregister the callbacks with
4533 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4534 *
4535 * @param request {@link NetworkRequest} describing this request.
4536 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4537 * the callback must not be shared - it uniquely specifies this request.
4538 * The callback is invoked on the default internal Handler.
4539 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4540 * @throws SecurityException if missing the appropriate permissions.
4541 * @throws RuntimeException if the app already has too many callbacks registered.
4542 */
4543 public void requestNetwork(@NonNull NetworkRequest request,
4544 @NonNull NetworkCallback networkCallback) {
4545 requestNetwork(request, networkCallback, getDefaultHandler());
4546 }
4547
4548 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004549 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004550 *
4551 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4552 * but runs all the callbacks on the passed Handler.
4553 *
4554 * <p>This method has the same permission requirements as
4555 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4556 * and throws the same exceptions in the same conditions.
4557 *
4558 * @param request {@link NetworkRequest} describing this request.
4559 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4560 * the callback must not be shared - it uniquely specifies this request.
4561 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4562 */
4563 public void requestNetwork(@NonNull NetworkRequest request,
4564 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4565 CallbackHandler cbHandler = new CallbackHandler(handler);
4566 NetworkCapabilities nc = request.networkCapabilities;
4567 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4568 }
4569
4570 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004571 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004572 * by a timeout.
4573 *
4574 * This function behaves identically to the non-timed-out version
4575 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4576 * is not found within the given time (in milliseconds) the
4577 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4578 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4579 * not have to be released if timed-out (it is automatically released). Unregistering a
4580 * request that timed out is not an error.
4581 *
4582 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4583 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4584 * for that purpose. Calling this method will attempt to bring up the requested network.
4585 *
4586 * <p>This method has the same permission requirements as
4587 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4588 * and throws the same exceptions in the same conditions.
4589 *
4590 * @param request {@link NetworkRequest} describing this request.
4591 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4592 * the callback must not be shared - it uniquely specifies this request.
4593 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4594 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4595 * be a positive value (i.e. >0).
4596 */
4597 public void requestNetwork(@NonNull NetworkRequest request,
4598 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4599 checkTimeout(timeoutMs);
4600 NetworkCapabilities nc = request.networkCapabilities;
4601 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4602 getDefaultHandler());
4603 }
4604
4605 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004606 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004607 * by a timeout.
4608 *
4609 * This method behaves identically to
4610 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4611 * on the passed Handler.
4612 *
4613 * <p>This method has the same permission requirements as
4614 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4615 * and throws the same exceptions in the same conditions.
4616 *
4617 * @param request {@link NetworkRequest} describing this request.
4618 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4619 * the callback must not be shared - it uniquely specifies this request.
4620 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4621 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4622 * before {@link NetworkCallback#onUnavailable} is called.
4623 */
4624 public void requestNetwork(@NonNull NetworkRequest request,
4625 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4626 checkTimeout(timeoutMs);
4627 CallbackHandler cbHandler = new CallbackHandler(handler);
4628 NetworkCapabilities nc = request.networkCapabilities;
4629 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4630 }
4631
4632 /**
4633 * The lookup key for a {@link Network} object included with the intent after
4634 * successfully finding a network for the applications request. Retrieve it with
4635 * {@link android.content.Intent#getParcelableExtra(String)}.
4636 * <p>
4637 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4638 * then you must get a ConnectivityManager instance before doing so.
4639 */
4640 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4641
4642 /**
4643 * The lookup key for a {@link NetworkRequest} object included with the intent after
4644 * successfully finding a network for the applications request. Retrieve it with
4645 * {@link android.content.Intent#getParcelableExtra(String)}.
4646 */
4647 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4648
4649
4650 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004651 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004652 *
4653 * This function behaves identically to the version that takes a NetworkCallback, but instead
4654 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4655 * the request may outlive the calling application and get called back when a suitable
4656 * network is found.
4657 * <p>
4658 * The operation is an Intent broadcast that goes to a broadcast receiver that
4659 * you registered with {@link Context#registerReceiver} or through the
4660 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4661 * <p>
4662 * The operation Intent is delivered with two extras, a {@link Network} typed
4663 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4664 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4665 * the original requests parameters. It is important to create a new,
4666 * {@link NetworkCallback} based request before completing the processing of the
4667 * Intent to reserve the network or it will be released shortly after the Intent
4668 * is processed.
4669 * <p>
4670 * If there is already a request for this Intent registered (with the equality of
4671 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4672 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4673 * <p>
4674 * The request may be released normally by calling
4675 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4676 * <p>It is presently unsupported to request a network with either
4677 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4678 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4679 * as these {@code NetworkCapabilities} represent states that a particular
4680 * network may never attain, and whether a network will attain these states
4681 * is unknown prior to bringing up the network so the framework does not
4682 * know how to go about satisfying a request with these capabilities.
4683 *
4684 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4685 * number of outstanding requests to 100 per app (identified by their UID), shared with
4686 * all variants of this method, of {@link #registerNetworkCallback} as well as
4687 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4688 * Requesting a network with this method will count toward this limit. If this limit is
4689 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4690 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4691 * or {@link #releaseNetworkRequest(PendingIntent)}.
4692 *
4693 * <p>This method requires the caller to hold either the
4694 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4695 * or the ability to modify system settings as determined by
4696 * {@link android.provider.Settings.System#canWrite}.</p>
4697 *
4698 * @param request {@link NetworkRequest} describing this request.
4699 * @param operation Action to perform when the network is available (corresponds
4700 * to the {@link NetworkCallback#onAvailable} call. Typically
4701 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4702 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4703 * @throws SecurityException if missing the appropriate permissions.
4704 * @throws RuntimeException if the app already has too many callbacks registered.
4705 */
4706 public void requestNetwork(@NonNull NetworkRequest request,
4707 @NonNull PendingIntent operation) {
4708 printStackTrace();
4709 checkPendingIntentNotNull(operation);
4710 try {
4711 mService.pendingRequestForNetwork(
4712 request.networkCapabilities, operation, mContext.getOpPackageName(),
4713 getAttributionTag());
4714 } catch (RemoteException e) {
4715 throw e.rethrowFromSystemServer();
4716 } catch (ServiceSpecificException e) {
4717 throw convertServiceException(e);
4718 }
4719 }
4720
4721 /**
4722 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4723 * <p>
4724 * This method has the same behavior as
4725 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4726 * releasing network resources and disconnecting.
4727 *
4728 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4729 * PendingIntent passed to
4730 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4731 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4732 */
4733 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4734 printStackTrace();
4735 checkPendingIntentNotNull(operation);
4736 try {
4737 mService.releasePendingNetworkRequest(operation);
4738 } catch (RemoteException e) {
4739 throw e.rethrowFromSystemServer();
4740 }
4741 }
4742
4743 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004744 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004745 }
4746
4747 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004748 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004749 }
4750
4751 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004752 if (timeoutMs <= 0) {
4753 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4754 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004755 }
4756
4757 /**
4758 * Registers to receive notifications about all networks which satisfy the given
4759 * {@link NetworkRequest}. The callbacks will continue to be called until
4760 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4761 * called.
4762 *
4763 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4764 * number of outstanding requests to 100 per app (identified by their UID), shared with
4765 * all variants of this method, of {@link #requestNetwork} as well as
4766 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4767 * Requesting a network with this method will count toward this limit. If this limit is
4768 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4769 * make sure to unregister the callbacks with
4770 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4771 *
4772 * @param request {@link NetworkRequest} describing this request.
4773 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4774 * networks change state.
4775 * The callback is invoked on the default internal Handler.
4776 * @throws RuntimeException if the app already has too many callbacks registered.
4777 */
4778 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4779 public void registerNetworkCallback(@NonNull NetworkRequest request,
4780 @NonNull NetworkCallback networkCallback) {
4781 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4782 }
4783
4784 /**
4785 * Registers to receive notifications about all networks which satisfy the given
4786 * {@link NetworkRequest}. The callbacks will continue to be called until
4787 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4788 * called.
4789 *
4790 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4791 * number of outstanding requests to 100 per app (identified by their UID), shared with
4792 * all variants of this method, of {@link #requestNetwork} as well as
4793 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4794 * Requesting a network with this method will count toward this limit. If this limit is
4795 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4796 * make sure to unregister the callbacks with
4797 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4798 *
4799 *
4800 * @param request {@link NetworkRequest} describing this request.
4801 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4802 * networks change state.
4803 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4804 * @throws RuntimeException if the app already has too many callbacks registered.
4805 */
4806 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4807 public void registerNetworkCallback(@NonNull NetworkRequest request,
4808 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4809 CallbackHandler cbHandler = new CallbackHandler(handler);
4810 NetworkCapabilities nc = request.networkCapabilities;
4811 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4812 }
4813
4814 /**
4815 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4816 * {@link NetworkRequest}.
4817 *
4818 * This function behaves identically to the version that takes a NetworkCallback, but instead
4819 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4820 * the request may outlive the calling application and get called back when a suitable
4821 * network is found.
4822 * <p>
4823 * The operation is an Intent broadcast that goes to a broadcast receiver that
4824 * you registered with {@link Context#registerReceiver} or through the
4825 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4826 * <p>
4827 * The operation Intent is delivered with two extras, a {@link Network} typed
4828 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4829 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4830 * the original requests parameters.
4831 * <p>
4832 * If there is already a request for this Intent registered (with the equality of
4833 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4834 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4835 * <p>
4836 * The request may be released normally by calling
4837 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4838 *
4839 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4840 * number of outstanding requests to 100 per app (identified by their UID), shared with
4841 * all variants of this method, of {@link #requestNetwork} as well as
4842 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4843 * Requesting a network with this method will count toward this limit. If this limit is
4844 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4845 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4846 * or {@link #releaseNetworkRequest(PendingIntent)}.
4847 *
4848 * @param request {@link NetworkRequest} describing this request.
4849 * @param operation Action to perform when the network is available (corresponds
4850 * to the {@link NetworkCallback#onAvailable} call. Typically
4851 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4852 * @throws RuntimeException if the app already has too many callbacks registered.
4853 */
4854 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4855 public void registerNetworkCallback(@NonNull NetworkRequest request,
4856 @NonNull PendingIntent operation) {
4857 printStackTrace();
4858 checkPendingIntentNotNull(operation);
4859 try {
4860 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004861 request.networkCapabilities, operation, mContext.getOpPackageName(),
4862 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004863 } catch (RemoteException e) {
4864 throw e.rethrowFromSystemServer();
4865 } catch (ServiceSpecificException e) {
4866 throw convertServiceException(e);
4867 }
4868 }
4869
4870 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004871 * Registers to receive notifications about changes in the application's default network. This
4872 * may be a physical network or a virtual network, such as a VPN that applies to the
4873 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004874 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4875 *
4876 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4877 * number of outstanding requests to 100 per app (identified by their UID), shared with
4878 * all variants of this method, of {@link #requestNetwork} as well as
4879 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4880 * Requesting a network with this method will count toward this limit. If this limit is
4881 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4882 * make sure to unregister the callbacks with
4883 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4884 *
4885 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004886 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004887 * The callback is invoked on the default internal Handler.
4888 * @throws RuntimeException if the app already has too many callbacks registered.
4889 */
4890 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4891 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4892 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
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
4899 * {@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
4911 * application's default network changes.
4912 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
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 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004918 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004919 }
4920
4921 /**
4922 * Registers to receive notifications about changes in the default network for the specified
4923 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4924 * UID. The callbacks will continue to be called until either the application exits or
4925 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4926 *
4927 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4928 * number of outstanding requests to 100 per app (identified by their UID), shared with
4929 * all variants of this method, of {@link #requestNetwork} as well as
4930 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4931 * Requesting a network with this method will count toward this limit. If this limit is
4932 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4933 * make sure to unregister the callbacks with
4934 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4935 *
4936 * @param uid the UID for which to track default network changes.
4937 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4938 * UID's default network changes.
4939 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4940 * @throws RuntimeException if the app already has too many callbacks registered.
4941 * @hide
4942 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004943 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004944 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4945 @RequiresPermission(anyOf = {
4946 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4947 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004948 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004949 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004950 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004951 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004952 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4953 }
4954
4955 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004956 * Registers to receive notifications about changes in the system default network. The callbacks
4957 * will continue to be called until either the application exits or
4958 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4959 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004960 * This method should not be used to determine networking state seen by applications, because in
4961 * many cases, most or even all application traffic may not use the default network directly,
4962 * and traffic from different applications may go on different networks by default. As an
4963 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4964 * and not onto the system default network. Applications or system components desiring to do
4965 * determine network state as seen by applications should use other methods such as
4966 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4967 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004968 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4969 * number of outstanding requests to 100 per app (identified by their UID), shared with
4970 * all variants of this method, of {@link #requestNetwork} as well as
4971 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4972 * Requesting a network with this method will count toward this limit. If this limit is
4973 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4974 * make sure to unregister the callbacks with
4975 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4976 *
4977 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4978 * system default network changes.
4979 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4980 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004981 *
4982 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004983 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004984 @SystemApi(client = MODULE_LIBRARIES)
4985 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4986 @RequiresPermission(anyOf = {
4987 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004988 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00004989 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004990 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004991 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004992 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004993 CallbackHandler cbHandler = new CallbackHandler(handler);
4994 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004995 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004996 }
4997
4998 /**
junyulaibd123062021-03-15 11:48:48 +08004999 * Registers to receive notifications about the best matching network which satisfy the given
5000 * {@link NetworkRequest}. The callbacks will continue to be called until
5001 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
5002 * called.
5003 *
5004 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5005 * number of outstanding requests to 100 per app (identified by their UID), shared with
5006 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
5007 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5008 * Requesting a network with this method will count toward this limit. If this limit is
5009 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5010 * make sure to unregister the callbacks with
5011 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5012 *
5013 *
5014 * @param request {@link NetworkRequest} describing this request.
5015 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
5016 * networks change state.
5017 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5018 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08005019 */
junyulai5a5c99b2021-03-05 15:51:17 +08005020 @SuppressLint("ExecutorRegistration")
5021 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
5022 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
5023 final NetworkCapabilities nc = request.networkCapabilities;
5024 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08005025 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08005026 }
5027
5028 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005029 * Requests bandwidth update for a given {@link Network} and returns whether the update request
5030 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
5031 * network connection for updated bandwidth information. The caller will be notified via
5032 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
5033 * method assumes that the caller has previously called
5034 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
5035 * changes.
5036 *
5037 * @param network {@link Network} specifying which network you're interested.
5038 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5039 */
5040 public boolean requestBandwidthUpdate(@NonNull Network network) {
5041 try {
5042 return mService.requestBandwidthUpdate(network);
5043 } catch (RemoteException e) {
5044 throw e.rethrowFromSystemServer();
5045 }
5046 }
5047
5048 /**
5049 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
5050 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
5051 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005052 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
5053 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005054 *
5055 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
5056 * triggering it as soon as this call returns.
5057 *
5058 * @param networkCallback The {@link NetworkCallback} used when making the request.
5059 */
5060 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
5061 printStackTrace();
5062 checkCallbackNotNull(networkCallback);
5063 final List<NetworkRequest> reqs = new ArrayList<>();
5064 // Find all requests associated to this callback and stop callback triggers immediately.
5065 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
5066 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00005067 if (networkCallback.networkRequest == null) {
5068 throw new IllegalArgumentException("NetworkCallback was not registered");
5069 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005070 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
5071 Log.d(TAG, "NetworkCallback was already unregistered");
5072 return;
5073 }
5074 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
5075 if (e.getValue() == networkCallback) {
5076 reqs.add(e.getKey());
5077 }
5078 }
5079 // TODO: throw exception if callback was registered more than once (http://b/20701525).
5080 for (NetworkRequest r : reqs) {
5081 try {
5082 mService.releaseNetworkRequest(r);
5083 } catch (RemoteException e) {
5084 throw e.rethrowFromSystemServer();
5085 }
5086 // Only remove mapping if rpc was successful.
5087 sCallbacks.remove(r);
5088 }
5089 networkCallback.networkRequest = ALREADY_UNREGISTERED;
5090 }
5091 }
5092
5093 /**
5094 * Unregisters a callback previously registered via
5095 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5096 *
5097 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
5098 * PendingIntent passed to
5099 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5100 * Cannot be null.
5101 */
5102 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
5103 releaseNetworkRequest(operation);
5104 }
5105
5106 /**
5107 * Informs the system whether it should switch to {@code network} regardless of whether it is
5108 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
5109 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
5110 * the system default network regardless of any other network that's currently connected. If
5111 * {@code always} is true, then the choice is remembered, so that the next time the user
5112 * connects to this network, the system will switch to it.
5113 *
5114 * @param network The network to accept.
5115 * @param accept Whether to accept the network even if unvalidated.
5116 * @param always Whether to remember this choice in the future.
5117 *
5118 * @hide
5119 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005120 @SystemApi(client = MODULE_LIBRARIES)
5121 @RequiresPermission(anyOf = {
5122 android.Manifest.permission.NETWORK_SETTINGS,
5123 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5124 android.Manifest.permission.NETWORK_STACK,
5125 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5126 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005127 try {
5128 mService.setAcceptUnvalidated(network, accept, always);
5129 } catch (RemoteException e) {
5130 throw e.rethrowFromSystemServer();
5131 }
5132 }
5133
5134 /**
5135 * Informs the system whether it should consider the network as validated even if it only has
5136 * partial connectivity. If {@code accept} is true, then the network will be considered as
5137 * validated even if connectivity is only partial. If {@code always} is true, then the choice
5138 * is remembered, so that the next time the user connects to this network, the system will
5139 * switch to it.
5140 *
5141 * @param network The network to accept.
5142 * @param accept Whether to consider the network as validated even if it has partial
5143 * connectivity.
5144 * @param always Whether to remember this choice in the future.
5145 *
5146 * @hide
5147 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005148 @SystemApi(client = MODULE_LIBRARIES)
5149 @RequiresPermission(anyOf = {
5150 android.Manifest.permission.NETWORK_SETTINGS,
5151 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5152 android.Manifest.permission.NETWORK_STACK,
5153 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5154 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5155 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005156 try {
5157 mService.setAcceptPartialConnectivity(network, accept, always);
5158 } catch (RemoteException e) {
5159 throw e.rethrowFromSystemServer();
5160 }
5161 }
5162
5163 /**
5164 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5165 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5166 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5167 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5168 *
5169 * @param network The network to accept.
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 setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005180 try {
5181 mService.setAvoidUnvalidated(network);
5182 } catch (RemoteException e) {
5183 throw e.rethrowFromSystemServer();
5184 }
5185 }
5186
5187 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005188 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005189 *
5190 * @param timeMs The expired current time. The value should be set within a limited time from
5191 * now.
5192 *
5193 * @hide
5194 */
5195 public void setTestAllowBadWifiUntil(long timeMs) {
5196 try {
5197 mService.setTestAllowBadWifiUntil(timeMs);
5198 } catch (RemoteException e) {
5199 throw e.rethrowFromSystemServer();
5200 }
5201 }
5202
5203 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005204 * Requests that the system open the captive portal app on the specified network.
5205 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005206 * <p>This is to be used on networks where a captive portal was detected, as per
5207 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5208 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005209 * @param network The network to log into.
5210 *
5211 * @hide
5212 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005213 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5214 @RequiresPermission(anyOf = {
5215 android.Manifest.permission.NETWORK_SETTINGS,
5216 android.Manifest.permission.NETWORK_STACK,
5217 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5218 })
5219 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005220 try {
5221 mService.startCaptivePortalApp(network);
5222 } catch (RemoteException e) {
5223 throw e.rethrowFromSystemServer();
5224 }
5225 }
5226
5227 /**
5228 * Requests that the system open the captive portal app with the specified extras.
5229 *
5230 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5231 * corresponding permission.
5232 * @param network Network on which the captive portal was detected.
5233 * @param appExtras Extras to include in the app start intent.
5234 * @hide
5235 */
5236 @SystemApi
5237 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5238 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5239 try {
5240 mService.startCaptivePortalAppInternal(network, appExtras);
5241 } catch (RemoteException e) {
5242 throw e.rethrowFromSystemServer();
5243 }
5244 }
5245
5246 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005247 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005248 * @hide
5249 */
5250 @SystemApi
5251 @RequiresPermission(anyOf = {
5252 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5253 android.Manifest.permission.NETWORK_STACK})
5254 public boolean shouldAvoidBadWifi() {
5255 try {
5256 return mService.shouldAvoidBadWifi();
5257 } catch (RemoteException e) {
5258 throw e.rethrowFromSystemServer();
5259 }
5260 }
5261
5262 /**
5263 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5264 * time-sensitive user-facing operations when the system default network is temporarily
5265 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5266 * this method), and the operation should be infrequent to ensure that data usage is limited.
5267 *
5268 * An example of such an operation might be a time-sensitive foreground activity, such as a
5269 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5270 */
5271 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5272
5273 /**
5274 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5275 * a backup channel for traffic that is primarily going over another network.
5276 *
5277 * An example might be maintaining backup connections to peers or servers for the purpose of
5278 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5279 * on backup paths should be negligible compared to the traffic on the main path.
5280 */
5281 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5282
5283 /**
5284 * It is acceptable to use metered data to improve network latency and performance.
5285 */
5286 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5287
5288 /**
5289 * Return value to use for unmetered networks. On such networks we currently set all the flags
5290 * to true.
5291 * @hide
5292 */
5293 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5294 MULTIPATH_PREFERENCE_HANDOVER |
5295 MULTIPATH_PREFERENCE_RELIABILITY |
5296 MULTIPATH_PREFERENCE_PERFORMANCE;
5297
Aaron Huangcff22942021-05-27 16:31:26 +08005298 /** @hide */
5299 @Retention(RetentionPolicy.SOURCE)
5300 @IntDef(flag = true, value = {
5301 MULTIPATH_PREFERENCE_HANDOVER,
5302 MULTIPATH_PREFERENCE_RELIABILITY,
5303 MULTIPATH_PREFERENCE_PERFORMANCE,
5304 })
5305 public @interface MultipathPreference {
5306 }
5307
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005308 /**
5309 * Provides a hint to the calling application on whether it is desirable to use the
5310 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5311 * for multipath data transfer on this network when it is not the system default network.
5312 * Applications desiring to use multipath network protocols should call this method before
5313 * each such operation.
5314 *
5315 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005316 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005317 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005318 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005319 */
5320 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5321 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5322 try {
5323 return mService.getMultipathPreference(network);
5324 } catch (RemoteException e) {
5325 throw e.rethrowFromSystemServer();
5326 }
5327 }
5328
5329 /**
5330 * Resets all connectivity manager settings back to factory defaults.
5331 * @hide
5332 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005333 @SystemApi(client = MODULE_LIBRARIES)
5334 @RequiresPermission(anyOf = {
5335 android.Manifest.permission.NETWORK_SETTINGS,
5336 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005337 public void factoryReset() {
5338 try {
5339 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005340 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005341 } catch (RemoteException e) {
5342 throw e.rethrowFromSystemServer();
5343 }
5344 }
5345
5346 /**
5347 * Binds the current process to {@code network}. All Sockets created in the future
5348 * (and not explicitly bound via a bound SocketFactory from
5349 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5350 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5351 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5352 * work and all host name resolutions will fail. This is by design so an application doesn't
5353 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5354 * To clear binding pass {@code null} for {@code network}. Using individually bound
5355 * Sockets created by Network.getSocketFactory().createSocket() and
5356 * performing network-specific host name resolutions via
5357 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5358 * {@code bindProcessToNetwork}.
5359 *
5360 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5361 * the current binding.
5362 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5363 */
5364 public boolean bindProcessToNetwork(@Nullable Network network) {
5365 // Forcing callers to call through non-static function ensures ConnectivityManager
5366 // instantiated.
5367 return setProcessDefaultNetwork(network);
5368 }
5369
5370 /**
5371 * Binds the current process to {@code network}. All Sockets created in the future
5372 * (and not explicitly bound via a bound SocketFactory from
5373 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5374 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5375 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5376 * work and all host name resolutions will fail. This is by design so an application doesn't
5377 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5378 * To clear binding pass {@code null} for {@code network}. Using individually bound
5379 * Sockets created by Network.getSocketFactory().createSocket() and
5380 * performing network-specific host name resolutions via
5381 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5382 * {@code setProcessDefaultNetwork}.
5383 *
5384 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5385 * the current binding.
5386 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5387 * @deprecated This function can throw {@link IllegalStateException}. Use
5388 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5389 * is a direct replacement.
5390 */
5391 @Deprecated
5392 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5393 int netId = (network == null) ? NETID_UNSET : network.netId;
5394 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5395
5396 if (netId != NETID_UNSET) {
5397 netId = network.getNetIdForResolv();
5398 }
5399
5400 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5401 return false;
5402 }
5403
5404 if (!isSameNetId) {
5405 // Set HTTP proxy system properties to match network.
5406 // TODO: Deprecate this static method and replace it with a non-static version.
5407 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005408 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005409 } catch (SecurityException e) {
5410 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5411 Log.e(TAG, "Can't set proxy properties", e);
5412 }
5413 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005414 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005415 // Must flush socket pool as idle sockets will be bound to previous network and may
5416 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005417 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005418 }
5419
5420 return true;
5421 }
5422
5423 /**
5424 * Returns the {@link Network} currently bound to this process via
5425 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5426 *
5427 * @return {@code Network} to which this process is bound, or {@code null}.
5428 */
5429 @Nullable
5430 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005431 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005432 // instantiated.
5433 return getProcessDefaultNetwork();
5434 }
5435
5436 /**
5437 * Returns the {@link Network} currently bound to this process via
5438 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5439 *
5440 * @return {@code Network} to which this process is bound, or {@code null}.
5441 * @deprecated Using this function can lead to other functions throwing
5442 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5443 * {@code getBoundNetworkForProcess} is a direct replacement.
5444 */
5445 @Deprecated
5446 @Nullable
5447 public static Network getProcessDefaultNetwork() {
5448 int netId = NetworkUtils.getBoundNetworkForProcess();
5449 if (netId == NETID_UNSET) return null;
5450 return new Network(netId);
5451 }
5452
5453 private void unsupportedStartingFrom(int version) {
5454 if (Process.myUid() == Process.SYSTEM_UID) {
5455 // The getApplicationInfo() call we make below is not supported in system context. Let
5456 // the call through here, and rely on the fact that ConnectivityService will refuse to
5457 // allow the system to use these APIs anyway.
5458 return;
5459 }
5460
5461 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5462 throw new UnsupportedOperationException(
5463 "This method is not supported in target SDK version " + version + " and above");
5464 }
5465 }
5466
5467 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5468 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5469 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5470 // remove these exemptions. Note that this check is not secure, and apps can still access these
5471 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5472 // so is unsupported and may break in the future. http://b/22728205
5473 private void checkLegacyRoutingApiAccess() {
5474 unsupportedStartingFrom(VERSION_CODES.M);
5475 }
5476
5477 /**
5478 * Binds host resolutions performed by this process to {@code network}.
5479 * {@link #bindProcessToNetwork} takes precedence over this setting.
5480 *
5481 * @param network The {@link Network} to bind host resolutions from the current process to, or
5482 * {@code null} to clear the current binding.
5483 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5484 * @hide
5485 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5486 */
5487 @Deprecated
5488 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5489 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5490 return NetworkUtils.bindProcessToNetworkForHostResolution(
5491 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5492 }
5493
5494 /**
5495 * Device is not restricting metered network activity while application is running on
5496 * background.
5497 */
5498 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5499
5500 /**
5501 * Device is restricting metered network activity while application is running on background,
5502 * but application is allowed to bypass it.
5503 * <p>
5504 * In this state, application should take action to mitigate metered network access.
5505 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5506 */
5507 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5508
5509 /**
5510 * Device is restricting metered network activity while application is running on background.
5511 * <p>
5512 * In this state, application should not try to use the network while running on background,
5513 * because it would be denied.
5514 */
5515 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5516
5517 /**
5518 * A change in the background metered network activity restriction has occurred.
5519 * <p>
5520 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5521 * applies to them.
5522 * <p>
5523 * This is only sent to registered receivers, not manifest receivers.
5524 */
5525 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5526 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5527 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5528
Aaron Huangcff22942021-05-27 16:31:26 +08005529 /** @hide */
5530 @Retention(RetentionPolicy.SOURCE)
5531 @IntDef(flag = false, value = {
5532 RESTRICT_BACKGROUND_STATUS_DISABLED,
5533 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5534 RESTRICT_BACKGROUND_STATUS_ENABLED,
5535 })
5536 public @interface RestrictBackgroundStatus {
5537 }
5538
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005539 /**
5540 * Determines if the calling application is subject to metered network restrictions while
5541 * running on background.
5542 *
5543 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5544 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5545 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5546 */
5547 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5548 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005549 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005550 } catch (RemoteException e) {
5551 throw e.rethrowFromSystemServer();
5552 }
5553 }
5554
5555 /**
5556 * The network watchlist is a list of domains and IP addresses that are associated with
5557 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5558 * currently used by the system for validation purposes.
5559 *
5560 * @return Hash of network watchlist config file. Null if config does not exist.
5561 */
5562 @Nullable
5563 public byte[] getNetworkWatchlistConfigHash() {
5564 try {
5565 return mService.getNetworkWatchlistConfigHash();
5566 } catch (RemoteException e) {
5567 Log.e(TAG, "Unable to get watchlist config hash");
5568 throw e.rethrowFromSystemServer();
5569 }
5570 }
5571
5572 /**
5573 * Returns the {@code uid} of the owner of a network connection.
5574 *
5575 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5576 * IPPROTO_UDP} currently supported.
5577 * @param local The local {@link InetSocketAddress} of a connection.
5578 * @param remote The remote {@link InetSocketAddress} of a connection.
5579 * @return {@code uid} if the connection is found and the app has permission to observe it
5580 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5581 * android.os.Process#INVALID_UID} if the connection is not found.
Sherri Lin443b7182023-02-08 04:49:29 +01005582 * @throws SecurityException if the caller is not the active VpnService for the current
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005583 * user.
Sherri Lin443b7182023-02-08 04:49:29 +01005584 * @throws IllegalArgumentException if an unsupported protocol is requested.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005585 */
5586 public int getConnectionOwnerUid(
5587 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5588 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5589 try {
5590 return mService.getConnectionOwnerUid(connectionInfo);
5591 } catch (RemoteException e) {
5592 throw e.rethrowFromSystemServer();
5593 }
5594 }
5595
5596 private void printStackTrace() {
5597 if (DEBUG) {
5598 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5599 final StringBuffer sb = new StringBuffer();
5600 for (int i = 3; i < callStack.length; i++) {
5601 final String stackTrace = callStack[i].toString();
5602 if (stackTrace == null || stackTrace.contains("android.os")) {
5603 break;
5604 }
5605 sb.append(" [").append(stackTrace).append("]");
5606 }
5607 Log.d(TAG, "StackLog:" + sb.toString());
5608 }
5609 }
5610
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005611 /** @hide */
5612 public TestNetworkManager startOrGetTestNetworkManager() {
5613 final IBinder tnBinder;
5614 try {
5615 tnBinder = mService.startOrGetTestNetworkService();
5616 } catch (RemoteException e) {
5617 throw e.rethrowFromSystemServer();
5618 }
5619
5620 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5621 }
5622
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005623 /** @hide */
5624 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5625 return new ConnectivityDiagnosticsManager(mContext, mService);
5626 }
5627
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005628 /**
5629 * Simulates a Data Stall for the specified Network.
5630 *
5631 * <p>This method should only be used for tests.
5632 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005633 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5634 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005635 *
5636 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005637 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5638 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5639 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005640 * @param network The Network for which a Data Stall is being simluated.
5641 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5642 * @throws SecurityException if the caller is not the owner of the given network.
5643 * @hide
5644 */
5645 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5646 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5647 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005648 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005649 @NonNull Network network, @NonNull PersistableBundle extras) {
5650 try {
5651 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5652 } catch (RemoteException e) {
5653 e.rethrowFromSystemServer();
5654 }
5655 }
5656
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005657 @NonNull
5658 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5659
5660 /**
5661 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5662 * receive available QoS events related to the {@link Network} and local ip + port
5663 * specified within socketInfo.
5664 * <p/>
5665 * The same {@link QosCallback} must be unregistered before being registered a second time,
5666 * otherwise {@link QosCallbackRegistrationException} is thrown.
5667 * <p/>
5668 * This API does not, in itself, require any permission if called with a network that is not
5669 * restricted. However, the underlying implementation currently only supports the IMS network,
5670 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5671 * useful, because they'd never be called back on networks that they would have access to.
5672 *
5673 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5674 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5675 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5676 * @throws RuntimeException if the app already has too many callbacks registered.
5677 *
5678 * Exceptions after the time of registration is passed through
5679 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5680 *
5681 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005682 * @param executor The executor on which the callback will be invoked. The provided
5683 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005684 * callbacks cannot be guaranteed.onQosCallbackRegistered
5685 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005686 *
5687 * @hide
5688 */
5689 @SystemApi
5690 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005691 @CallbackExecutor @NonNull final Executor executor,
5692 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005693 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005694 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005695 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005696
5697 try {
5698 synchronized (mQosCallbackConnections) {
5699 if (getQosCallbackConnection(callback) == null) {
5700 final QosCallbackConnection connection =
5701 new QosCallbackConnection(this, callback, executor);
5702 mQosCallbackConnections.add(connection);
5703 mService.registerQosSocketCallback(socketInfo, connection);
5704 } else {
5705 Log.e(TAG, "registerQosCallback: Callback already registered");
5706 throw new QosCallbackRegistrationException();
5707 }
5708 }
5709 } catch (final RemoteException e) {
5710 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5711
5712 // The same unregister method method is called for consistency even though nothing
5713 // will be sent to the ConnectivityService since the callback was never successfully
5714 // registered.
5715 unregisterQosCallback(callback);
5716 e.rethrowFromSystemServer();
5717 } catch (final ServiceSpecificException e) {
5718 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5719 unregisterQosCallback(callback);
5720 throw convertServiceException(e);
5721 }
5722 }
5723
5724 /**
5725 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5726 * events once unregistered and can be registered a second time.
5727 * <p/>
5728 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5729 *
5730 * @param callback the callback being unregistered
5731 *
5732 * @hide
5733 */
5734 @SystemApi
5735 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5736 Objects.requireNonNull(callback, "The callback must be non-null");
5737 try {
5738 synchronized (mQosCallbackConnections) {
5739 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5740 if (connection != null) {
5741 connection.stopReceivingMessages();
5742 mService.unregisterQosCallback(connection);
5743 mQosCallbackConnections.remove(connection);
5744 } else {
5745 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5746 }
5747 }
5748 } catch (final RemoteException e) {
5749 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5750 e.rethrowFromSystemServer();
5751 }
5752 }
5753
5754 /**
5755 * Gets the connection related to the callback.
5756 *
5757 * @param callback the callback to look up
5758 * @return the related connection
5759 */
5760 @Nullable
5761 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5762 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5763 // Checking by reference here is intentional
5764 if (connection.getCallback() == callback) {
5765 return connection;
5766 }
5767 }
5768 return null;
5769 }
5770
5771 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005772 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005773 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5774 * be used to request that the system provide a network without causing the network to be
5775 * in the foreground.
5776 *
5777 * <p>This method will attempt to find the best network that matches the passed
5778 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5779 * criteria. The platform will evaluate which network is the best at its own discretion.
5780 * Throughput, latency, cost per byte, policy, user preference and other considerations
5781 * may be factored in the decision of what is considered the best network.
5782 *
5783 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5784 * matching this request, while always attempting to match the request to a better network if
5785 * possible. If a better match is found, the platform will switch this request to the now-best
5786 * network and inform the app of the newly best network by invoking
5787 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5788 * will not try to maintain any other network than the best one currently matching the request:
5789 * a network not matching any network request may be disconnected at any time.
5790 *
5791 * <p>For example, an application could use this method to obtain a connected cellular network
5792 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5793 * radio to consume additional power. Or, an application could inform the system that it wants
5794 * a network supporting sending MMSes and have the system let it know about the currently best
5795 * MMS-supporting network through the provided {@link NetworkCallback}.
5796 *
5797 * <p>The status of the request can be followed by listening to the various callbacks described
5798 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5799 * used to direct traffic to the network (although accessing some networks may be subject to
5800 * holding specific permissions). Callers will learn about the specific characteristics of the
5801 * network through
5802 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5803 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5804 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5805 * matching the request at any given time; therefore when a better network matching the request
5806 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5807 * with the new network after which no further updates are given about the previously-best
5808 * network, unless it becomes the best again at some later time. All callbacks are invoked
5809 * in order on the same thread, which by default is a thread created by the framework running
5810 * in the app.
5811 *
5812 * <p>This{@link NetworkRequest} will live until released via
5813 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5814 * which point the system may let go of the network at any time.
5815 *
5816 * <p>It is presently unsupported to request a network with mutable
5817 * {@link NetworkCapabilities} such as
5818 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5819 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5820 * as these {@code NetworkCapabilities} represent states that a particular
5821 * network may never attain, and whether a network will attain these states
5822 * is unknown prior to bringing up the network so the framework does not
5823 * know how to go about satisfying a request with these capabilities.
5824 *
5825 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5826 * number of outstanding requests to 100 per app (identified by their UID), shared with
5827 * all variants of this method, of {@link #registerNetworkCallback} as well as
5828 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5829 * Requesting a network with this method will count toward this limit. If this limit is
5830 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5831 * make sure to unregister the callbacks with
5832 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5833 *
5834 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005835 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5836 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005837 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5838 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005839 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5840 * @throws SecurityException if missing the appropriate permissions.
5841 * @throws RuntimeException if the app already has too many callbacks registered.
5842 *
5843 * @hide
5844 */
5845 @SystemApi(client = MODULE_LIBRARIES)
5846 @SuppressLint("ExecutorRegistration")
5847 @RequiresPermission(anyOf = {
5848 android.Manifest.permission.NETWORK_SETTINGS,
5849 android.Manifest.permission.NETWORK_STACK,
5850 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5851 })
5852 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005853 @NonNull NetworkCallback networkCallback,
5854 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005855 final NetworkCapabilities nc = request.networkCapabilities;
5856 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005857 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005858 }
James Mattis12aeab82021-01-10 14:24:24 -08005859
5860 /**
James Mattis12aeab82021-01-10 14:24:24 -08005861 * Used by automotive devices to set the network preferences used to direct traffic at an
5862 * application level as per the given OemNetworkPreferences. An example use-case would be an
5863 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5864 * vehicle via a particular network.
5865 *
5866 * Calling this will overwrite the existing preference.
5867 *
5868 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5869 * @param executor the executor on which listener will be invoked.
5870 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5871 * communicate completion of setOemNetworkPreference(). This will only be
5872 * called once upon successful completion of setOemNetworkPreference().
5873 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5874 * @throws SecurityException if missing the appropriate permissions.
5875 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005876 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005877 */
James Mattis6e2d7022021-01-26 16:23:52 -08005878 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005879 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005880 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005881 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005882 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005883 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5884 if (null != listener) {
5885 Objects.requireNonNull(executor, "Executor must be non-null");
5886 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005887 final IOnCompleteListener listenerInternal = listener == null ? null :
5888 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005889 @Override
5890 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005891 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005892 }
5893 };
5894
5895 try {
5896 mService.setOemNetworkPreference(preference, listenerInternal);
5897 } catch (RemoteException e) {
5898 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5899 throw e.rethrowFromSystemServer();
5900 }
5901 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005902
Chalard Jeanad565e22021-02-25 17:23:40 +09005903 /**
5904 * Request that a user profile is put by default on a network matching a given preference.
5905 *
5906 * See the documentation for the individual preferences for a description of the supported
5907 * behaviors.
5908 *
5909 * @param profile the profile concerned.
5910 * @param preference the preference for this profile.
5911 * @param executor an executor to execute the listener on. Optional if listener is null.
5912 * @param listener an optional listener to listen for completion of the operation.
5913 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5914 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005915 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5916 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005917 * @hide
5918 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005919 // This function is for establishing per-profile default networking and can only be called by
5920 // the device policy manager, running as the system server. It would make no sense to call it
5921 // on a context for a user because it does not establish a setting on behalf of a user, rather
5922 // it establishes a setting for a user on behalf of the DPM.
5923 @SuppressLint({"UserHandle"})
5924 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005925 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005926 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005927 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005928 @ProfileNetworkPreferencePolicy final int preference,
5929 @Nullable @CallbackExecutor final Executor executor,
5930 @Nullable final Runnable listener) {
5931
5932 ProfileNetworkPreference.Builder preferenceBuilder =
5933 new ProfileNetworkPreference.Builder();
5934 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005935 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5936 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5937 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005938 setProfileNetworkPreferences(profile,
5939 List.of(preferenceBuilder.build()), executor, listener);
5940 }
5941
5942 /**
5943 * Set a list of default network selection policies for a user profile.
5944 *
5945 * Calling this API with a user handle defines the entire policy for that user handle.
5946 * It will overwrite any setting previously set for the same user profile,
5947 * and not affect previously set settings for other handles.
5948 *
5949 * Call this API with an empty list to remove settings for this user profile.
5950 *
5951 * See {@link ProfileNetworkPreference} for more details on each preference
5952 * parameter.
5953 *
5954 * @param profile the user profile for which the preference is being set.
5955 * @param profileNetworkPreferences the list of profile network preferences for the
5956 * provided profile.
5957 * @param executor an executor to execute the listener on. Optional if listener is null.
5958 * @param listener an optional listener to listen for completion of the operation.
5959 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5960 * @throws SecurityException if missing the appropriate permissions.
5961 * @hide
5962 */
5963 @SystemApi(client = MODULE_LIBRARIES)
5964 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5965 public void setProfileNetworkPreferences(
5966 @NonNull final UserHandle profile,
5967 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005968 @Nullable @CallbackExecutor final Executor executor,
5969 @Nullable final Runnable listener) {
5970 if (null != listener) {
5971 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5972 }
5973 final IOnCompleteListener proxy;
5974 if (null == listener) {
5975 proxy = null;
5976 } else {
5977 proxy = new IOnCompleteListener.Stub() {
5978 @Override
5979 public void onComplete() {
5980 executor.execute(listener::run);
5981 }
5982 };
5983 }
5984 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005985 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005986 } catch (RemoteException e) {
5987 throw e.rethrowFromSystemServer();
5988 }
5989 }
5990
lucaslin5cdbcfb2021-03-12 00:46:33 +08005991 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005992 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005993 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005994 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005995
5996 /**
5997 * Get the network ID range reserved for IPSec tunnel interfaces.
5998 *
5999 * @return A Range which indicates the network ID range of IPSec tunnel interface.
6000 * @hide
6001 */
6002 @SystemApi(client = MODULE_LIBRARIES)
6003 @NonNull
6004 public static Range<Integer> getIpSecNetIdRange() {
6005 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
6006 }
markchien738ad912021-12-09 18:15:45 +08006007
6008 /**
Junyu Laidf210362023-10-24 02:47:50 +00006009 * Sets data saver switch.
6010 *
6011 * @param enable True if enable.
6012 * @throws IllegalStateException if failed.
6013 * @hide
6014 */
6015 @FlaggedApi(Flags.SET_DATA_SAVER_VIA_CM)
6016 @SystemApi(client = MODULE_LIBRARIES)
6017 @RequiresPermission(anyOf = {
6018 android.Manifest.permission.NETWORK_SETTINGS,
6019 android.Manifest.permission.NETWORK_STACK,
6020 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6021 })
6022 public void setDataSaverEnabled(final boolean enable) {
6023 try {
6024 mService.setDataSaverEnabled(enable);
6025 } catch (RemoteException e) {
6026 throw e.rethrowFromSystemServer();
6027 }
6028 }
6029
6030 /**
markchiene46042b2022-03-02 18:07:35 +08006031 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
6032 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08006033 *
6034 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006035 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08006036 * @hide
6037 */
6038 @SystemApi(client = MODULE_LIBRARIES)
6039 @RequiresPermission(anyOf = {
6040 android.Manifest.permission.NETWORK_SETTINGS,
6041 android.Manifest.permission.NETWORK_STACK,
6042 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6043 })
markchiene46042b2022-03-02 18:07:35 +08006044 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006045 try {
markchiene46042b2022-03-02 18:07:35 +08006046 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08006047 } catch (RemoteException e) {
6048 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006049 }
6050 }
6051
6052 /**
markchiene46042b2022-03-02 18:07:35 +08006053 * Removes the specified UID from the list of UIDs that are allowed to use background data on
6054 * metered networks when background data is restricted. The deny list takes precedence over
6055 * the allow list.
6056 *
6057 * @param uid uid of target app
6058 * @throws IllegalStateException if updating allow list failed.
6059 * @hide
6060 */
6061 @SystemApi(client = MODULE_LIBRARIES)
6062 @RequiresPermission(anyOf = {
6063 android.Manifest.permission.NETWORK_SETTINGS,
6064 android.Manifest.permission.NETWORK_STACK,
6065 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6066 })
6067 public void removeUidFromMeteredNetworkAllowList(final int uid) {
6068 try {
6069 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
6070 } catch (RemoteException e) {
6071 throw e.rethrowFromSystemServer();
6072 }
6073 }
6074
6075 /**
6076 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
6077 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08006078 *
6079 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006080 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08006081 * @hide
6082 */
6083 @SystemApi(client = MODULE_LIBRARIES)
6084 @RequiresPermission(anyOf = {
6085 android.Manifest.permission.NETWORK_SETTINGS,
6086 android.Manifest.permission.NETWORK_STACK,
6087 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6088 })
markchiene46042b2022-03-02 18:07:35 +08006089 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006090 try {
markchiene46042b2022-03-02 18:07:35 +08006091 mService.updateMeteredNetworkDenyList(uid, true /* add */);
6092 } catch (RemoteException e) {
6093 throw e.rethrowFromSystemServer();
6094 }
6095 }
6096
6097 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09006098 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08006099 * networks if background data is not restricted. The deny list takes precedence over the
6100 * allow list.
6101 *
6102 * @param uid uid of target app
6103 * @throws IllegalStateException if updating deny list failed.
6104 * @hide
6105 */
6106 @SystemApi(client = MODULE_LIBRARIES)
6107 @RequiresPermission(anyOf = {
6108 android.Manifest.permission.NETWORK_SETTINGS,
6109 android.Manifest.permission.NETWORK_STACK,
6110 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6111 })
6112 public void removeUidFromMeteredNetworkDenyList(final int uid) {
6113 try {
6114 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08006115 } catch (RemoteException e) {
6116 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08006117 }
6118 }
6119
6120 /**
6121 * Sets a firewall rule for the specified UID on the specified chain.
6122 *
6123 * @param chain target chain.
6124 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08006125 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08006126 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08006127 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08006128 * @hide
6129 */
6130 @SystemApi(client = MODULE_LIBRARIES)
6131 @RequiresPermission(anyOf = {
6132 android.Manifest.permission.NETWORK_SETTINGS,
6133 android.Manifest.permission.NETWORK_STACK,
6134 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6135 })
markchien3c04e662022-03-22 16:29:56 +08006136 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
6137 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08006138 try {
markchien3c04e662022-03-22 16:29:56 +08006139 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08006140 } catch (RemoteException e) {
6141 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006142 }
6143 }
markchien98a6f952022-01-13 23:43:53 +08006144
6145 /**
Motomu Utsumi900b8062023-01-19 16:16:49 +09006146 * Get firewall rule of specified firewall chain on specified uid.
6147 *
6148 * @param chain target chain.
6149 * @param uid target uid
6150 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
6151 * @throws UnsupportedOperationException if called on pre-T devices.
6152 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6153 * cause of the failure.
6154 * @hide
6155 */
6156 @RequiresPermission(anyOf = {
6157 android.Manifest.permission.NETWORK_SETTINGS,
6158 android.Manifest.permission.NETWORK_STACK,
6159 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6160 })
6161 public int getUidFirewallRule(@FirewallChain final int chain, final int uid) {
6162 try {
6163 return mService.getUidFirewallRule(chain, uid);
6164 } catch (RemoteException e) {
6165 throw e.rethrowFromSystemServer();
6166 }
6167 }
6168
6169 /**
markchien98a6f952022-01-13 23:43:53 +08006170 * Enables or disables the specified firewall chain.
6171 *
6172 * @param chain target chain.
6173 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00006174 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08006175 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08006176 * @hide
6177 */
6178 @SystemApi(client = MODULE_LIBRARIES)
6179 @RequiresPermission(anyOf = {
6180 android.Manifest.permission.NETWORK_SETTINGS,
6181 android.Manifest.permission.NETWORK_STACK,
6182 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6183 })
6184 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
6185 try {
6186 mService.setFirewallChainEnabled(chain, enable);
6187 } catch (RemoteException e) {
6188 throw e.rethrowFromSystemServer();
6189 }
6190 }
markchien00a0bed2022-01-13 23:46:13 +08006191
6192 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00006193 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006194 *
6195 * @param chain target chain.
6196 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6197 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006198 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6199 * cause of the failure.
6200 * @hide
6201 */
6202 @RequiresPermission(anyOf = {
6203 android.Manifest.permission.NETWORK_SETTINGS,
6204 android.Manifest.permission.NETWORK_STACK,
6205 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6206 })
6207 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6208 try {
6209 return mService.getFirewallChainEnabled(chain);
6210 } catch (RemoteException e) {
6211 throw e.rethrowFromSystemServer();
6212 }
6213 }
6214
6215 /**
markchien00a0bed2022-01-13 23:46:13 +08006216 * Replaces the contents of the specified UID-based firewall chain.
6217 *
6218 * @param chain target chain to replace.
6219 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006220 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006221 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6222 * @hide
6223 */
6224 @SystemApi(client = MODULE_LIBRARIES)
6225 @RequiresPermission(anyOf = {
6226 android.Manifest.permission.NETWORK_SETTINGS,
6227 android.Manifest.permission.NETWORK_STACK,
6228 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6229 })
6230 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6231 Objects.requireNonNull(uids);
6232 try {
6233 mService.replaceFirewallChain(chain, uids);
6234 } catch (RemoteException e) {
6235 throw e.rethrowFromSystemServer();
6236 }
6237 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006238
Junyu Laie0031522023-08-29 18:32:57 +08006239 /**
Junyu Laic3dc5b62023-09-06 19:10:02 +08006240 * Helper class to track data saver status.
6241 *
6242 * The class will fetch current data saver status from {@link NetworkPolicyManager} when
6243 * initialized, and listening for status changed intent to cache the latest status.
6244 *
6245 * @hide
6246 */
6247 @TargetApi(Build.VERSION_CODES.TIRAMISU) // RECEIVER_NOT_EXPORTED requires T.
6248 @VisibleForTesting(visibility = PRIVATE)
6249 public static class DataSaverStatusTracker extends BroadcastReceiver {
6250 private static final Object sDataSaverStatusTrackerLock = new Object();
6251
6252 private static volatile DataSaverStatusTracker sInstance;
6253
6254 /**
6255 * Gets a static instance of the class.
6256 *
6257 * @param context A {@link Context} for initialization. Note that since the data saver
6258 * status is global on a device, passing any context is equivalent.
6259 * @return The static instance of a {@link DataSaverStatusTracker}.
6260 */
6261 public static DataSaverStatusTracker getInstance(@NonNull Context context) {
6262 if (sInstance == null) {
6263 synchronized (sDataSaverStatusTrackerLock) {
6264 if (sInstance == null) {
6265 sInstance = new DataSaverStatusTracker(context);
6266 }
6267 }
6268 }
6269 return sInstance;
6270 }
6271
6272 private final NetworkPolicyManager mNpm;
6273 // The value updates on the caller's binder thread or UI thread.
6274 private final AtomicBoolean mIsDataSaverEnabled;
6275
6276 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6277 public DataSaverStatusTracker(final Context context) {
6278 // To avoid leaks, take the application context.
6279 final Context appContext;
6280 if (context instanceof Application) {
6281 appContext = context;
6282 } else {
6283 appContext = context.getApplicationContext();
6284 }
6285
6286 if ((appContext.getApplicationInfo().flags & FLAG_PERSISTENT) == 0
6287 && (appContext.getApplicationInfo().flags & FLAG_SYSTEM) == 0) {
6288 throw new IllegalStateException("Unexpected caller: "
6289 + appContext.getApplicationInfo().packageName);
6290 }
6291
6292 mNpm = appContext.getSystemService(NetworkPolicyManager.class);
6293 final IntentFilter filter = new IntentFilter(
6294 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
6295 // The receiver should not receive broadcasts from other Apps.
6296 appContext.registerReceiver(this, filter, Context.RECEIVER_NOT_EXPORTED);
6297 mIsDataSaverEnabled = new AtomicBoolean();
6298 updateDataSaverEnabled();
6299 }
6300
6301 // Runs on caller's UI thread.
6302 @Override
6303 public void onReceive(Context context, Intent intent) {
6304 if (intent.getAction().equals(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED)) {
6305 updateDataSaverEnabled();
6306 } else {
6307 throw new IllegalStateException("Unexpected intent " + intent);
6308 }
6309 }
6310
6311 public boolean getDataSaverEnabled() {
6312 return mIsDataSaverEnabled.get();
6313 }
6314
6315 private void updateDataSaverEnabled() {
6316 // Uid doesn't really matter, but use a fixed UID to make things clearer.
6317 final int dataSaverForCallerUid = mNpm.getRestrictBackgroundStatus(Process.SYSTEM_UID);
6318 mIsDataSaverEnabled.set(dataSaverForCallerUid
6319 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
6320 }
6321 }
6322
6323 /**
6324 * Return whether the network is blocked for the given uid and metered condition.
Junyu Laie0031522023-08-29 18:32:57 +08006325 *
6326 * Similar to {@link NetworkPolicyManager#isUidNetworkingBlocked}, but directly reads the BPF
6327 * maps and therefore considerably faster. For use by the NetworkStack process only.
6328 *
6329 * @param uid The target uid.
Junyu Laic3dc5b62023-09-06 19:10:02 +08006330 * @param isNetworkMetered Whether the target network is metered.
6331 *
6332 * @return True if all networking with the given condition is blocked. Otherwise, false.
Junyu Laie0031522023-08-29 18:32:57 +08006333 * @throws IllegalStateException if the map cannot be opened.
6334 * @throws ServiceSpecificException if the read fails.
6335 * @hide
6336 */
6337 // This isn't protected by a standard Android permission since it can't
6338 // afford to do IPC for performance reasons. Instead, the access control
6339 // is provided by linux file group permission AID_NET_BW_ACCT and the
6340 // selinux context fs_bpf_net*.
6341 // Only the system server process and the network stack have access.
Junyu Laibb594802023-09-04 11:37:03 +08006342 @FlaggedApi(Flags.SUPPORT_IS_UID_NETWORKING_BLOCKED)
6343 @SystemApi(client = MODULE_LIBRARIES)
Junyu Laie0031522023-08-29 18:32:57 +08006344 @RequiresApi(Build.VERSION_CODES.TIRAMISU) // BPF maps were only mainlined in T
6345 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Junyu Laic3dc5b62023-09-06 19:10:02 +08006346 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Junyu Laie0031522023-08-29 18:32:57 +08006347 final BpfNetMapsReader reader = BpfNetMapsReader.getInstance();
6348
Junyu Laic3dc5b62023-09-06 19:10:02 +08006349 final boolean isDataSaverEnabled;
6350 // TODO: For U-QPR3+ devices, get data saver status from bpf configuration map directly.
6351 final DataSaverStatusTracker dataSaverStatusTracker =
6352 DataSaverStatusTracker.getInstance(mContext);
6353 isDataSaverEnabled = dataSaverStatusTracker.getDataSaverEnabled();
Junyu Laie0031522023-08-29 18:32:57 +08006354
Junyu Laic3dc5b62023-09-06 19:10:02 +08006355 return reader.isUidNetworkingBlocked(uid, isNetworkMetered, isDataSaverEnabled);
Junyu Laie0031522023-08-29 18:32:57 +08006356 }
6357
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006358 /** @hide */
6359 public IBinder getCompanionDeviceManagerProxyService() {
6360 try {
6361 return mService.getCompanionDeviceManagerProxyService();
6362 } catch (RemoteException e) {
6363 throw e.rethrowFromSystemServer();
6364 }
6365 }
Chalard Jean2fb66f12023-08-25 12:50:37 +09006366
6367 private static final Object sRoutingCoordinatorManagerLock = new Object();
6368 @GuardedBy("sRoutingCoordinatorManagerLock")
6369 private static RoutingCoordinatorManager sRoutingCoordinatorManager = null;
6370 /** @hide */
6371 @RequiresApi(Build.VERSION_CODES.S)
6372 public RoutingCoordinatorManager getRoutingCoordinatorManager() {
6373 try {
6374 synchronized (sRoutingCoordinatorManagerLock) {
6375 if (null == sRoutingCoordinatorManager) {
6376 sRoutingCoordinatorManager = new RoutingCoordinatorManager(mContext,
6377 IRoutingCoordinator.Stub.asInterface(
6378 mService.getRoutingCoordinatorService()));
6379 }
6380 return sRoutingCoordinatorManager;
6381 }
6382 } catch (RemoteException e) {
6383 throw e.rethrowFromSystemServer();
6384 }
6385 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006386}