blob: f44fd0e83ca72d558df4ba78ec50552008ad4cf2 [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";
136 }
137
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900138 /**
139 * A change in network connectivity has occurred. A default connection has either
140 * been established or lost. The NetworkInfo for the affected network is
141 * sent as an extra; it should be consulted to see what kind of
142 * connectivity event occurred.
143 * <p/>
144 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
145 * broadcast if they declare the broadcast receiver in their manifest. Apps
146 * will still receive broadcasts if they register their
147 * {@link android.content.BroadcastReceiver} with
148 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
149 * and that context is still valid.
150 * <p/>
151 * If this is a connection that was the result of failing over from a
152 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
153 * set to true.
154 * <p/>
155 * For a loss of connectivity, if the connectivity manager is attempting
156 * to connect (or has already connected) to another network, the
157 * NetworkInfo for the new network is also passed as an extra. This lets
158 * any receivers of the broadcast know that they should not necessarily
159 * tell the user that no data traffic will be possible. Instead, the
160 * receiver should expect another broadcast soon, indicating either that
161 * the failover attempt succeeded (and so there is still overall data
162 * connectivity), or that the failover attempt failed, meaning that all
163 * connectivity has been lost.
164 * <p/>
165 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
166 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900167 * <p />
168 * Note that this broadcast is deprecated and generally tries to implement backwards
169 * compatibility with older versions of Android. As such, it may not reflect new
170 * capabilities of the system, like multiple networks being connected at the same
171 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900172 *
173 * @deprecated apps should use the more versatile {@link #requestNetwork},
174 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
175 * functions instead for faster and more detailed updates about the network
176 * changes they care about.
177 */
178 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
179 @Deprecated
180 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
181
182 /**
183 * The device has connected to a network that has presented a captive
184 * portal, which is blocking Internet connectivity. The user was presented
185 * with a notification that network sign in is required,
186 * and the user invoked the notification's action indicating they
187 * desire to sign in to the network. Apps handling this activity should
188 * facilitate signing in to the network. This action includes a
189 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
190 * the network presenting the captive portal; all communication with the
191 * captive portal must be done using this {@code Network} object.
192 * <p/>
193 * This activity includes a {@link CaptivePortal} extra named
194 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
195 * outcomes of the captive portal sign in to the system:
196 * <ul>
197 * <li> When the app handling this action believes the user has signed in to
198 * the network and the captive portal has been dismissed, the app should
199 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
200 * reevaluate the network. If reevaluation finds the network no longer
201 * subject to a captive portal, the network may become the default active
202 * data network.</li>
203 * <li> When the app handling this action believes the user explicitly wants
204 * to ignore the captive portal and the network, the app should call
205 * {@link CaptivePortal#ignoreNetwork}. </li>
206 * </ul>
207 */
208 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
209 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
210
211 /**
212 * The lookup key for a {@link NetworkInfo} object. Retrieve with
213 * {@link android.content.Intent#getParcelableExtra(String)}.
214 *
215 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
216 * can't accurately represent modern network characteristics.
217 * Please obtain information about networks from the {@link NetworkCapabilities}
218 * or {@link LinkProperties} objects instead.
219 */
220 @Deprecated
221 public static final String EXTRA_NETWORK_INFO = "networkInfo";
222
223 /**
224 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
225 *
226 * @see android.content.Intent#getIntExtra(String, int)
227 * @deprecated The network type is not rich enough to represent the characteristics
228 * of modern networks. Please use {@link NetworkCapabilities} instead,
229 * in particular the transports.
230 */
231 @Deprecated
232 public static final String EXTRA_NETWORK_TYPE = "networkType";
233
234 /**
235 * The lookup key for a boolean that indicates whether a connect event
236 * is for a network to which the connectivity manager was failing over
237 * following a disconnect on another network.
238 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
239 *
240 * @deprecated See {@link NetworkInfo}.
241 */
242 @Deprecated
243 public static final String EXTRA_IS_FAILOVER = "isFailover";
244 /**
245 * The lookup key for a {@link NetworkInfo} object. This is supplied when
246 * there is another network that it may be possible to connect to. Retrieve with
247 * {@link android.content.Intent#getParcelableExtra(String)}.
248 *
249 * @deprecated See {@link NetworkInfo}.
250 */
251 @Deprecated
252 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
253 /**
254 * The lookup key for a boolean that indicates whether there is a
255 * complete lack of connectivity, i.e., no network is available.
256 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
257 */
258 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
259 /**
260 * The lookup key for a string that indicates why an attempt to connect
261 * to a network failed. The string has no particular structure. It is
262 * intended to be used in notifications presented to users. Retrieve
263 * it with {@link android.content.Intent#getStringExtra(String)}.
264 */
265 public static final String EXTRA_REASON = "reason";
266 /**
267 * The lookup key for a string that provides optionally supplied
268 * extra information about the network state. The information
269 * may be passed up from the lower networking layers, and its
270 * meaning may be specific to a particular network type. Retrieve
271 * it with {@link android.content.Intent#getStringExtra(String)}.
272 *
273 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
274 */
275 @Deprecated
276 public static final String EXTRA_EXTRA_INFO = "extraInfo";
277 /**
278 * The lookup key for an int that provides information about
279 * our connection to the internet at large. 0 indicates no connection,
280 * 100 indicates a great connection. Retrieve it with
281 * {@link android.content.Intent#getIntExtra(String, int)}.
282 * {@hide}
283 */
284 public static final String EXTRA_INET_CONDITION = "inetCondition";
285 /**
286 * The lookup key for a {@link CaptivePortal} object included with the
287 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
288 * object can be used to either indicate to the system that the captive
289 * portal has been dismissed or that the user does not want to pursue
290 * signing in to captive portal. Retrieve it with
291 * {@link android.content.Intent#getParcelableExtra(String)}.
292 */
293 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
294
295 /**
296 * Key for passing a URL to the captive portal login activity.
297 */
298 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
299
300 /**
301 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
302 * portal login activity.
303 * {@hide}
304 */
305 @SystemApi
306 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
307 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
308
309 /**
310 * Key for passing a user agent string to the captive portal login activity.
311 * {@hide}
312 */
313 @SystemApi
314 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
315 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
316
317 /**
318 * Broadcast action to indicate the change of data activity status
319 * (idle or active) on a network in a recent period.
320 * The network becomes active when data transmission is started, or
321 * idle if there is no data transmission for a period of time.
322 * {@hide}
323 */
324 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
325 public static final String ACTION_DATA_ACTIVITY_CHANGE =
326 "android.net.conn.DATA_ACTIVITY_CHANGE";
327 /**
328 * The lookup key for an enum that indicates the network device type on which this data activity
329 * change happens.
330 * {@hide}
331 */
332 public static final String EXTRA_DEVICE_TYPE = "deviceType";
333 /**
334 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
335 * it is actively sending or receiving data and {@code false} means it is idle.
336 * {@hide}
337 */
338 public static final String EXTRA_IS_ACTIVE = "isActive";
339 /**
340 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
341 * {@hide}
342 */
343 public static final String EXTRA_REALTIME_NS = "tsNanos";
344
345 /**
346 * Broadcast Action: The setting for background data usage has changed
347 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
348 * <p>
349 * If an application uses the network in the background, it should listen
350 * for this broadcast and stop using the background data if the value is
351 * {@code false}.
352 * <p>
353 *
354 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
355 * of background data depends on several combined factors, and
356 * this broadcast is no longer sent. Instead, when background
357 * data is unavailable, {@link #getActiveNetworkInfo()} will now
358 * appear disconnected. During first boot after a platform
359 * upgrade, this broadcast will be sent once if
360 * {@link #getBackgroundDataSetting()} was {@code false} before
361 * the upgrade.
362 */
363 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
364 @Deprecated
365 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
366 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
367
368 /**
369 * Broadcast Action: The network connection may not be good
370 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
371 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
372 * the network and it's condition.
373 * @hide
374 */
375 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
376 @UnsupportedAppUsage
377 public static final String INET_CONDITION_ACTION =
378 "android.net.conn.INET_CONDITION_ACTION";
379
380 /**
381 * Broadcast Action: A tetherable connection has come or gone.
382 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
383 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
384 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
385 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
386 * the current state of tethering. Each include a list of
387 * interface names in that state (may be empty).
388 * @hide
389 */
390 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
391 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
392 public static final String ACTION_TETHER_STATE_CHANGED =
393 TetheringManager.ACTION_TETHER_STATE_CHANGED;
394
395 /**
396 * @hide
397 * gives a String[] listing all the interfaces configured for
398 * tethering and currently available for tethering.
399 */
400 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
401 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
402
403 /**
404 * @hide
405 * gives a String[] listing all the interfaces currently in local-only
406 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
407 */
408 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
409
410 /**
411 * @hide
412 * gives a String[] listing all the interfaces currently tethered
413 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
414 */
415 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
416 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
417
418 /**
419 * @hide
420 * gives a String[] listing all the interfaces we tried to tether and
421 * failed. Use {@link #getLastTetherError} to find the error code
422 * for any interfaces listed here.
423 */
424 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
425 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
426
427 /**
428 * Broadcast Action: The captive portal tracker has finished its test.
429 * Sent only while running Setup Wizard, in lieu of showing a user
430 * notification.
431 * @hide
432 */
433 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
434 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
435 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
436 /**
437 * The lookup key for a boolean that indicates whether a captive portal was detected.
438 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
439 * @hide
440 */
441 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
442
443 /**
444 * Action used to display a dialog that asks the user whether to connect to a network that is
445 * not validated. This intent is used to start the dialog in settings via startActivity.
446 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800447 * This action includes a {@link Network} typed extra which is called
448 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
449 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900450 * @hide
451 */
lucaslincf6d4502021-03-04 17:09:51 +0800452 @SystemApi(client = MODULE_LIBRARIES)
453 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900454
455 /**
456 * Action used to display a dialog that asks the user whether to avoid a network that is no
457 * longer validated. This intent is used to start the dialog in settings via startActivity.
458 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800459 * This action includes a {@link Network} typed extra which is called
460 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
461 * validated.
462 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900463 * @hide
464 */
lucaslincf6d4502021-03-04 17:09:51 +0800465 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900466 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800467 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900468
469 /**
470 * Action used to display a dialog that asks the user whether to stay connected to a network
471 * that has not validated. This intent is used to start the dialog in settings via
472 * startActivity.
473 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800474 * This action includes a {@link Network} typed extra which is called
475 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
476 * connectivity.
477 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900478 * @hide
479 */
lucaslincf6d4502021-03-04 17:09:51 +0800480 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900481 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800482 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900483
484 /**
paulhub49c8422021-04-07 16:18:13 +0800485 * Clear DNS Cache Action: This is broadcast when networks have changed and old
486 * DNS entries should be cleared.
487 * @hide
488 */
489 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
490 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
491 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
492
493 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900494 * Invalid tethering type.
495 * @see #startTethering(int, boolean, OnStartTetheringCallback)
496 * @hide
497 */
498 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
499
500 /**
501 * Wifi tethering type.
502 * @see #startTethering(int, boolean, OnStartTetheringCallback)
503 * @hide
504 */
505 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900506 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900507
508 /**
509 * USB tethering type.
510 * @see #startTethering(int, boolean, OnStartTetheringCallback)
511 * @hide
512 */
513 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900514 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900515
516 /**
517 * Bluetooth tethering type.
518 * @see #startTethering(int, boolean, OnStartTetheringCallback)
519 * @hide
520 */
521 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900522 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900523
524 /**
525 * Wifi P2p tethering type.
526 * Wifi P2p tethering is set through events automatically, and don't
527 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
528 * @hide
529 */
530 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
531
532 /**
533 * Extra used for communicating with the TetherService. Includes the type of tethering to
534 * enable if any.
535 * @hide
536 */
537 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
538
539 /**
540 * Extra used for communicating with the TetherService. Includes the type of tethering for
541 * which to cancel provisioning.
542 * @hide
543 */
544 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
545
546 /**
547 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
548 * provisioning.
549 * @hide
550 */
551 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
552
553 /**
554 * Tells the TetherService to run a provision check now.
555 * @hide
556 */
557 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
558
559 /**
560 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
561 * which will receive provisioning results. Can be left empty.
562 * @hide
563 */
564 public static final String EXTRA_PROVISION_CALLBACK =
565 TetheringConstants.EXTRA_PROVISION_CALLBACK;
566
567 /**
568 * The absence of a connection type.
569 * @hide
570 */
571 @SystemApi
572 public static final int TYPE_NONE = -1;
573
574 /**
575 * A Mobile data connection. Devices may support more than one.
576 *
577 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
578 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000579 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900580 */
581 @Deprecated
582 public static final int TYPE_MOBILE = 0;
583
584 /**
585 * A WIFI data connection. Devices may support more than one.
586 *
587 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
588 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000589 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900590 */
591 @Deprecated
592 public static final int TYPE_WIFI = 1;
593
594 /**
595 * An MMS-specific Mobile data connection. This network type may use the
596 * same network interface as {@link #TYPE_MOBILE} or it may use a different
597 * one. This is used by applications needing to talk to the carrier's
598 * Multimedia Messaging Service servers.
599 *
600 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
601 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
602 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
603 */
604 @Deprecated
605 public static final int TYPE_MOBILE_MMS = 2;
606
607 /**
608 * A SUPL-specific Mobile data connection. This network type may use the
609 * same network interface as {@link #TYPE_MOBILE} or it may use a different
610 * one. This is used by applications needing to talk to the carrier's
611 * Secure User Plane Location servers for help locating the device.
612 *
613 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
614 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
615 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
616 */
617 @Deprecated
618 public static final int TYPE_MOBILE_SUPL = 3;
619
620 /**
621 * A DUN-specific Mobile data connection. This network type may use the
622 * same network interface as {@link #TYPE_MOBILE} or it may use a different
623 * one. This is sometimes by the system when setting up an upstream connection
624 * for tethering so that the carrier is aware of DUN traffic.
625 *
626 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
627 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
628 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
629 */
630 @Deprecated
631 public static final int TYPE_MOBILE_DUN = 4;
632
633 /**
634 * A High Priority Mobile data connection. This network type uses the
635 * same network interface as {@link #TYPE_MOBILE} but the routing setup
636 * is different.
637 *
638 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
639 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000640 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900641 */
642 @Deprecated
643 public static final int TYPE_MOBILE_HIPRI = 5;
644
645 /**
646 * A WiMAX data connection.
647 *
648 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
649 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000650 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900651 */
652 @Deprecated
653 public static final int TYPE_WIMAX = 6;
654
655 /**
656 * A Bluetooth data connection.
657 *
658 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
659 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000660 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900661 */
662 @Deprecated
663 public static final int TYPE_BLUETOOTH = 7;
664
665 /**
666 * Fake data connection. This should not be used on shipping devices.
667 * @deprecated This is not used any more.
668 */
669 @Deprecated
670 public static final int TYPE_DUMMY = 8;
671
672 /**
673 * An Ethernet data connection.
674 *
675 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
676 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000677 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900678 */
679 @Deprecated
680 public static final int TYPE_ETHERNET = 9;
681
682 /**
683 * Over the air Administration.
684 * @deprecated Use {@link NetworkCapabilities} instead.
685 * {@hide}
686 */
687 @Deprecated
688 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
689 public static final int TYPE_MOBILE_FOTA = 10;
690
691 /**
692 * IP Multimedia Subsystem.
693 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
694 * {@hide}
695 */
696 @Deprecated
697 @UnsupportedAppUsage
698 public static final int TYPE_MOBILE_IMS = 11;
699
700 /**
701 * Carrier Branded Services.
702 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
703 * {@hide}
704 */
705 @Deprecated
706 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
707 public static final int TYPE_MOBILE_CBS = 12;
708
709 /**
710 * A Wi-Fi p2p connection. Only requesting processes will have access to
711 * the peers connected.
712 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
713 * {@hide}
714 */
715 @Deprecated
716 @SystemApi
717 public static final int TYPE_WIFI_P2P = 13;
718
719 /**
720 * The network to use for initially attaching to the network
721 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
722 * {@hide}
723 */
724 @Deprecated
725 @UnsupportedAppUsage
726 public static final int TYPE_MOBILE_IA = 14;
727
728 /**
729 * Emergency PDN connection for emergency services. This
730 * may include IMS and MMS in emergency situations.
731 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
732 * {@hide}
733 */
734 @Deprecated
735 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
736 public static final int TYPE_MOBILE_EMERGENCY = 15;
737
738 /**
739 * The network that uses proxy to achieve connectivity.
740 * @deprecated Use {@link NetworkCapabilities} instead.
741 * {@hide}
742 */
743 @Deprecated
744 @SystemApi
745 public static final int TYPE_PROXY = 16;
746
747 /**
748 * A virtual network using one or more native bearers.
749 * It may or may not be providing security services.
750 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
751 */
752 @Deprecated
753 public static final int TYPE_VPN = 17;
754
755 /**
756 * A network that is exclusively meant to be used for testing
757 *
758 * @deprecated Use {@link NetworkCapabilities} instead.
759 * @hide
760 */
761 @Deprecated
762 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
763
764 /**
765 * @deprecated Use {@link NetworkCapabilities} instead.
766 * @hide
767 */
768 @Deprecated
769 @Retention(RetentionPolicy.SOURCE)
770 @IntDef(prefix = { "TYPE_" }, value = {
771 TYPE_NONE,
772 TYPE_MOBILE,
773 TYPE_WIFI,
774 TYPE_MOBILE_MMS,
775 TYPE_MOBILE_SUPL,
776 TYPE_MOBILE_DUN,
777 TYPE_MOBILE_HIPRI,
778 TYPE_WIMAX,
779 TYPE_BLUETOOTH,
780 TYPE_DUMMY,
781 TYPE_ETHERNET,
782 TYPE_MOBILE_FOTA,
783 TYPE_MOBILE_IMS,
784 TYPE_MOBILE_CBS,
785 TYPE_WIFI_P2P,
786 TYPE_MOBILE_IA,
787 TYPE_MOBILE_EMERGENCY,
788 TYPE_PROXY,
789 TYPE_VPN,
790 TYPE_TEST
791 })
792 public @interface LegacyNetworkType {}
793
794 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
795 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
796 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
797 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
798 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
799
800 /** {@hide} */
801 public static final int MAX_RADIO_TYPE = TYPE_TEST;
802
803 /** {@hide} */
804 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
805
806 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
807
808 /**
809 * If you want to set the default network preference,you can directly
810 * change the networkAttributes array in framework's config.xml.
811 *
812 * @deprecated Since we support so many more networks now, the single
813 * network default network preference can't really express
814 * the hierarchy. Instead, the default is defined by the
815 * networkAttributes in config.xml. You can determine
816 * the current value by calling {@link #getNetworkPreference()}
817 * from an App.
818 */
819 @Deprecated
820 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
821
822 /**
823 * @hide
824 */
825 public static final int REQUEST_ID_UNSET = 0;
826
827 /**
828 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
829 * This allows to distinguish when unregistering NetworkCallbacks those that were never
830 * registered from those that were already unregistered.
831 * @hide
832 */
833 private static final NetworkRequest ALREADY_UNREGISTERED =
834 new NetworkRequest.Builder().clearCapabilities().build();
835
836 /**
837 * A NetID indicating no Network is selected.
838 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
839 * @hide
840 */
841 public static final int NETID_UNSET = 0;
842
843 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000844 * Flag to indicate that an app is not subject to any restrictions that could result in its
845 * network access blocked.
846 *
847 * @hide
848 */
849 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
850 public static final int BLOCKED_REASON_NONE = 0;
851
852 /**
853 * Flag to indicate that an app is subject to Battery saver restrictions that would
854 * result in its network access being blocked.
855 *
856 * @hide
857 */
858 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
859 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
860
861 /**
862 * Flag to indicate that an app is subject to Doze restrictions that would
863 * result in its network access being blocked.
864 *
865 * @hide
866 */
867 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
868 public static final int BLOCKED_REASON_DOZE = 1 << 1;
869
870 /**
871 * Flag to indicate that an app is subject to App Standby restrictions that would
872 * result in its network access being blocked.
873 *
874 * @hide
875 */
876 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
877 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
878
879 /**
880 * Flag to indicate that an app is subject to Restricted mode restrictions that would
881 * result in its network access being blocked.
882 *
883 * @hide
884 */
885 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
886 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
887
888 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900889 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
890 * is not currently connected.
891 *
892 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
893 *
894 * @hide
895 */
896 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
897 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
898
899 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100900 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
901 * result in its network access being blocked.
902 *
903 * @hide
904 */
905 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
906 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
907
908 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000909 * Flag to indicate that an app is subject to Data saver restrictions that would
910 * result in its metered network access being blocked.
911 *
912 * @hide
913 */
914 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
915 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
916
917 /**
918 * Flag to indicate that an app is subject to user restrictions that would
919 * result in its metered network access being blocked.
920 *
921 * @hide
922 */
923 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
924 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
925
926 /**
927 * Flag to indicate that an app is subject to Device admin restrictions that would
928 * result in its metered network access being blocked.
929 *
930 * @hide
931 */
932 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
933 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
934
935 /**
936 * @hide
937 */
938 @Retention(RetentionPolicy.SOURCE)
939 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
940 BLOCKED_REASON_NONE,
941 BLOCKED_REASON_BATTERY_SAVER,
942 BLOCKED_REASON_DOZE,
943 BLOCKED_REASON_APP_STANDBY,
944 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900945 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100946 BLOCKED_REASON_LOW_POWER_STANDBY,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000947 BLOCKED_METERED_REASON_DATA_SAVER,
948 BLOCKED_METERED_REASON_USER_RESTRICTED,
949 BLOCKED_METERED_REASON_ADMIN_DISABLED,
950 })
951 public @interface BlockedReason {}
952
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900953 /**
954 * Set of blocked reasons that are only applicable on metered networks.
955 *
956 * @hide
957 */
958 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
959 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
960
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900961 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
962 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900963
Robert Horvathd945bf02022-01-27 19:55:16 +0100964 // LINT.IfChange(firewall_chain)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900965 /**
markchiene1561fa2021-12-09 22:00:56 +0800966 * Firewall chain for device idle (doze mode).
967 * Allowlist of apps that have network access in device idle.
968 * @hide
969 */
970 @SystemApi(client = MODULE_LIBRARIES)
971 public static final int FIREWALL_CHAIN_DOZABLE = 1;
972
973 /**
974 * Firewall chain used for app standby.
975 * Denylist of apps that do not have network access.
976 * @hide
977 */
978 @SystemApi(client = MODULE_LIBRARIES)
979 public static final int FIREWALL_CHAIN_STANDBY = 2;
980
981 /**
982 * Firewall chain used for battery saver.
983 * Allowlist of apps that have network access when battery saver is on.
984 * @hide
985 */
986 @SystemApi(client = MODULE_LIBRARIES)
987 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
988
989 /**
990 * Firewall chain used for restricted networking mode.
991 * Allowlist of apps that have access in restricted networking mode.
992 * @hide
993 */
994 @SystemApi(client = MODULE_LIBRARIES)
995 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
996
Robert Horvath34cba142022-01-27 19:52:43 +0100997 /**
998 * Firewall chain used for low power standby.
999 * Allowlist of apps that have access in low power standby.
1000 * @hide
1001 */
1002 @SystemApi(client = MODULE_LIBRARIES)
1003 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
1004
Motomu Utsumib08654c2022-05-11 05:56:26 +00001005 /**
Motomu Utsumid9801492022-06-01 13:57:27 +00001006 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001007 *
1008 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1009 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1010 *
1011 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1012 * independent of the others. The chains can be enabled and disabled independently, and apps can
1013 * be added and removed from each chain independently.
1014 *
1015 * @see #FIREWALL_CHAIN_OEM_DENY_2
1016 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001017 * @hide
1018 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001019 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001020 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1021
1022 /**
1023 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001024 *
1025 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1026 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1027 *
1028 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1029 * independent of the others. The chains can be enabled and disabled independently, and apps can
1030 * be added and removed from each chain independently.
1031 *
1032 * @see #FIREWALL_CHAIN_OEM_DENY_1
1033 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001034 * @hide
1035 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001036 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001037 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1038
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001039 /**
1040 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001041 *
1042 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1043 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1044 *
1045 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1046 * independent of the others. The chains can be enabled and disabled independently, and apps can
1047 * be added and removed from each chain independently.
1048 *
1049 * @see #FIREWALL_CHAIN_OEM_DENY_1
1050 * @see #FIREWALL_CHAIN_OEM_DENY_2
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001051 * @hide
1052 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001053 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001054 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1055
markchiene1561fa2021-12-09 22:00:56 +08001056 /** @hide */
1057 @Retention(RetentionPolicy.SOURCE)
1058 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1059 FIREWALL_CHAIN_DOZABLE,
1060 FIREWALL_CHAIN_STANDBY,
1061 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001062 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001063 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Motomu Utsumid9801492022-06-01 13:57:27 +00001064 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001065 FIREWALL_CHAIN_OEM_DENY_2,
1066 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001067 })
1068 public @interface FirewallChain {}
Robert Horvathd945bf02022-01-27 19:55:16 +01001069 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
markchiene1561fa2021-12-09 22:00:56 +08001070
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.
3964 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3965 * @hide
3966 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003967 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003968 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003969 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003970 // Internally only this method is called when a new network is available, and
3971 // it calls the callback in the same way and order that older versions used
3972 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003973 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3974 onBlockedStatusChanged(network, blocked);
3975 }
3976
3977 /**
3978 * Legacy variant of onAvailable that takes a boolean blocked reason.
3979 *
3980 * This method has never been public API, but it's not final, so there may be apps that
3981 * implemented it and rely on it being called. Do our best not to break them.
3982 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3983 * this method is called. There does not seem to be a way to avoid this.
3984 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3985 *
3986 * @hide
3987 */
3988 public void onAvailable(@NonNull Network network,
3989 @NonNull NetworkCapabilities networkCapabilities,
3990 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003991 onAvailable(network);
3992 if (!networkCapabilities.hasCapability(
3993 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3994 onNetworkSuspended(network);
3995 }
3996 onCapabilitiesChanged(network, networkCapabilities);
3997 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003998 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003999 }
4000
4001 /**
4002 * Called when the framework connects and has declared a new network ready for use.
4003 *
4004 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
4005 * be available at the same time, and onAvailable will be called for each of these as they
4006 * appear.
4007 *
4008 * <p>For callbacks registered with {@link #requestNetwork} and
4009 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
4010 * is the new best network for this request and is now tracked by this callback ; this
4011 * callback will no longer receive method calls about other networks that may have been
4012 * passed to this method previously. The previously-best network may have disconnected, or
4013 * it may still be around and the newly-best network may simply be better.
4014 *
4015 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
4016 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
4017 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
4018 * to {@link #onBlockedStatusChanged(Network, boolean)}.
4019 *
4020 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4021 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4022 * this callback as this is prone to race conditions (there is no guarantee the objects
4023 * returned by these methods will be current). Instead, wait for a call to
4024 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
4025 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
4026 * to be well-ordered with respect to other callbacks.
4027 *
4028 * @param network The {@link Network} of the satisfying network.
4029 */
4030 public void onAvailable(@NonNull Network network) {}
4031
4032 /**
4033 * Called when the network is about to be lost, typically because there are no outstanding
4034 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
4035 * with the new replacement network for graceful handover. This method is not guaranteed
4036 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
4037 * network is suddenly disconnected.
4038 *
4039 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4040 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4041 * this callback as this is prone to race conditions ; calling these methods while in a
4042 * callback may return an outdated or even a null object.
4043 *
4044 * @param network The {@link Network} that is about to be lost.
4045 * @param maxMsToLive The time in milliseconds the system intends to keep the network
4046 * connected for graceful handover; note that the network may still
4047 * suffer a hard loss at any time.
4048 */
4049 public void onLosing(@NonNull Network network, int maxMsToLive) {}
4050
4051 /**
4052 * Called when a network disconnects or otherwise no longer satisfies this request or
4053 * callback.
4054 *
4055 * <p>If the callback was registered with requestNetwork() or
4056 * registerDefaultNetworkCallback(), it will only be invoked against the last network
4057 * returned by onAvailable() when that network is lost and no other network satisfies
4058 * the criteria of the request.
4059 *
4060 * <p>If the callback was registered with registerNetworkCallback() it will be called for
4061 * each network which no longer satisfies the criteria of the callback.
4062 *
4063 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4064 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4065 * this callback as this is prone to race conditions ; calling these methods while in a
4066 * callback may return an outdated or even a null object.
4067 *
4068 * @param network The {@link Network} lost.
4069 */
4070 public void onLost(@NonNull Network network) {}
4071
4072 /**
4073 * Called if no network is found within the timeout time specified in
4074 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
4075 * requested network request cannot be fulfilled (whether or not a timeout was
4076 * specified). When this callback is invoked the associated
4077 * {@link NetworkRequest} will have already been removed and released, as if
4078 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
4079 */
4080 public void onUnavailable() {}
4081
4082 /**
4083 * Called when the network corresponding to this request changes capabilities but still
4084 * satisfies the requested criteria.
4085 *
4086 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4087 * to be called immediately after {@link #onAvailable}.
4088 *
4089 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
4090 * ConnectivityManager methods in this callback as this is prone to race conditions :
4091 * calling these methods while in a callback may return an outdated or even a null object.
4092 *
4093 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08004094 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004095 * network.
4096 */
4097 public void onCapabilitiesChanged(@NonNull Network network,
4098 @NonNull NetworkCapabilities networkCapabilities) {}
4099
4100 /**
4101 * Called when the network corresponding to this request changes {@link LinkProperties}.
4102 *
4103 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4104 * to be called immediately after {@link #onAvailable}.
4105 *
4106 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
4107 * ConnectivityManager methods in this callback as this is prone to race conditions :
4108 * calling these methods while in a callback may return an outdated or even a null object.
4109 *
4110 * @param network The {@link Network} whose link properties have changed.
4111 * @param linkProperties The new {@link LinkProperties} for this network.
4112 */
4113 public void onLinkPropertiesChanged(@NonNull Network network,
4114 @NonNull LinkProperties linkProperties) {}
4115
4116 /**
4117 * Called when the network the framework connected to for this request suspends data
4118 * transmission temporarily.
4119 *
4120 * <p>This generally means that while the TCP connections are still live temporarily
4121 * network data fails to transfer. To give a specific example, this is used on cellular
4122 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4123 * means read operations on sockets on this network will block once the buffers are
4124 * drained, and write operations will block once the buffers are full.
4125 *
4126 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4127 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4128 * this callback as this is prone to race conditions (there is no guarantee the objects
4129 * returned by these methods will be current).
4130 *
4131 * @hide
4132 */
4133 public void onNetworkSuspended(@NonNull Network network) {}
4134
4135 /**
4136 * Called when the network the framework connected to for this request
4137 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4138 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4139
4140 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4141 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4142 * this callback as this is prone to race conditions : calling these methods while in a
4143 * callback may return an outdated or even a null object.
4144 *
4145 * @hide
4146 */
4147 public void onNetworkResumed(@NonNull Network network) {}
4148
4149 /**
4150 * Called when access to the specified network is blocked or unblocked.
4151 *
4152 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4153 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4154 * this callback as this is prone to race conditions : calling these methods while in a
4155 * callback may return an outdated or even a null object.
4156 *
4157 * @param network The {@link Network} whose blocked status has changed.
4158 * @param blocked The blocked status of this {@link Network}.
4159 */
4160 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4161
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004162 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004163 * Called when access to the specified network is blocked or unblocked, or the reason for
4164 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004165 *
4166 * If a NetworkCallback object implements this method,
4167 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4168 *
4169 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4170 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4171 * this callback as this is prone to race conditions : calling these methods while in a
4172 * callback may return an outdated or even a null object.
4173 *
4174 * @param network The {@link Network} whose blocked status has changed.
4175 * @param blocked The blocked status of this {@link Network}.
4176 * @hide
4177 */
4178 @SystemApi(client = MODULE_LIBRARIES)
4179 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4180 onBlockedStatusChanged(network, blocked != 0);
4181 }
4182
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004183 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004184 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004185 }
4186
4187 /**
4188 * Constant error codes used by ConnectivityService to communicate about failures and errors
4189 * across a Binder boundary.
4190 * @hide
4191 */
4192 public interface Errors {
4193 int TOO_MANY_REQUESTS = 1;
4194 }
4195
4196 /** @hide */
4197 public static class TooManyRequestsException extends RuntimeException {}
4198
4199 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4200 switch (e.errorCode) {
4201 case Errors.TOO_MANY_REQUESTS:
4202 return new TooManyRequestsException();
4203 default:
4204 Log.w(TAG, "Unknown service error code " + e.errorCode);
4205 return new RuntimeException(e);
4206 }
4207 }
4208
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004209 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004210 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004211 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004212 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004213 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004214 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004215 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004216 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004217 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004218 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004219 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004220 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004221 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004222 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004223 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004224 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004225 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004226 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004227 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004228 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004229 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004230 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004231
4232 /** @hide */
4233 public static String getCallbackName(int whichCallback) {
4234 switch (whichCallback) {
4235 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4236 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4237 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4238 case CALLBACK_LOST: return "CALLBACK_LOST";
4239 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4240 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4241 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4242 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4243 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4244 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4245 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4246 default:
4247 return Integer.toString(whichCallback);
4248 }
4249 }
4250
zhujiatai79b0de92022-09-22 15:44:02 +08004251 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004252 private static final String TAG = "ConnectivityManager.CallbackHandler";
4253 private static final boolean DBG = false;
4254
4255 CallbackHandler(Looper looper) {
4256 super(looper);
4257 }
4258
4259 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004260 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004261 }
4262
4263 @Override
4264 public void handleMessage(Message message) {
4265 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004266 // the sInstance can't be null because to send this message a ConnectivityManager
4267 // instance must have been created prior to creating the thread on which this
4268 // Handler is running.
4269 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004270 return;
4271 }
4272
4273 final NetworkRequest request = getObject(message, NetworkRequest.class);
4274 final Network network = getObject(message, Network.class);
4275 final NetworkCallback callback;
4276 synchronized (sCallbacks) {
4277 callback = sCallbacks.get(request);
4278 if (callback == null) {
4279 Log.w(TAG,
4280 "callback not found for " + getCallbackName(message.what) + " message");
4281 return;
4282 }
4283 if (message.what == CALLBACK_UNAVAIL) {
4284 sCallbacks.remove(request);
4285 callback.networkRequest = ALREADY_UNREGISTERED;
4286 }
4287 }
4288 if (DBG) {
4289 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4290 }
4291
4292 switch (message.what) {
4293 case CALLBACK_PRECHECK: {
4294 callback.onPreCheck(network);
4295 break;
4296 }
4297 case CALLBACK_AVAILABLE: {
4298 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4299 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004300 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004301 break;
4302 }
4303 case CALLBACK_LOSING: {
4304 callback.onLosing(network, message.arg1);
4305 break;
4306 }
4307 case CALLBACK_LOST: {
4308 callback.onLost(network);
4309 break;
4310 }
4311 case CALLBACK_UNAVAIL: {
4312 callback.onUnavailable();
4313 break;
4314 }
4315 case CALLBACK_CAP_CHANGED: {
4316 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4317 callback.onCapabilitiesChanged(network, cap);
4318 break;
4319 }
4320 case CALLBACK_IP_CHANGED: {
4321 LinkProperties lp = getObject(message, LinkProperties.class);
4322 callback.onLinkPropertiesChanged(network, lp);
4323 break;
4324 }
4325 case CALLBACK_SUSPENDED: {
4326 callback.onNetworkSuspended(network);
4327 break;
4328 }
4329 case CALLBACK_RESUMED: {
4330 callback.onNetworkResumed(network);
4331 break;
4332 }
4333 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004334 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004335 }
4336 }
4337 }
4338
4339 private <T> T getObject(Message msg, Class<T> c) {
4340 return (T) msg.getData().getParcelable(c.getSimpleName());
4341 }
4342 }
4343
4344 private CallbackHandler getDefaultHandler() {
4345 synchronized (sCallbacks) {
4346 if (sCallbackHandler == null) {
4347 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4348 }
4349 return sCallbackHandler;
4350 }
4351 }
4352
4353 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4354 private static CallbackHandler sCallbackHandler;
4355
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004356 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4357 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4358 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004359 printStackTrace();
4360 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004361 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4362 throw new IllegalArgumentException("null NetworkCapabilities");
4363 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004364 final NetworkRequest request;
4365 final String callingPackageName = mContext.getOpPackageName();
4366 try {
4367 synchronized(sCallbacks) {
4368 if (callback.networkRequest != null
4369 && callback.networkRequest != ALREADY_UNREGISTERED) {
4370 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4371 // and requests (http://b/20701525).
4372 Log.e(TAG, "NetworkCallback was already registered");
4373 }
4374 Messenger messenger = new Messenger(handler);
4375 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004376 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004377 if (reqType == LISTEN) {
4378 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004379 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004380 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004381 } else {
4382 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004383 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4384 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004385 }
4386 if (request != null) {
4387 sCallbacks.put(request, callback);
4388 }
4389 callback.networkRequest = request;
4390 }
4391 } catch (RemoteException e) {
4392 throw e.rethrowFromSystemServer();
4393 } catch (ServiceSpecificException e) {
4394 throw convertServiceException(e);
4395 }
4396 return request;
4397 }
4398
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004399 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4400 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4401 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4402 legacyType, handler);
4403 }
4404
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004405 /**
4406 * Helper function to request a network with a particular legacy type.
4407 *
4408 * This API is only for use in internal system code that requests networks with legacy type and
4409 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4410 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4411 *
4412 * @param request {@link NetworkRequest} describing this request.
4413 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4414 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4415 * be a positive value (i.e. >0).
4416 * @param legacyType to specify the network type(#TYPE_*).
4417 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4418 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4419 * the callback must not be shared - it uniquely specifies this request.
4420 *
4421 * @hide
4422 */
4423 @SystemApi
4424 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4425 public void requestNetwork(@NonNull NetworkRequest request,
4426 int timeoutMs, int legacyType, @NonNull Handler handler,
4427 @NonNull NetworkCallback networkCallback) {
4428 if (legacyType == TYPE_NONE) {
4429 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4430 }
4431 CallbackHandler cbHandler = new CallbackHandler(handler);
4432 NetworkCapabilities nc = request.networkCapabilities;
4433 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4434 }
4435
4436 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004437 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004438 *
4439 * <p>This method will attempt to find the best network that matches the passed
4440 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4441 * criteria. The platform will evaluate which network is the best at its own discretion.
4442 * Throughput, latency, cost per byte, policy, user preference and other considerations
4443 * may be factored in the decision of what is considered the best network.
4444 *
4445 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4446 * matching this request, while always attempting to match the request to a better network if
4447 * possible. If a better match is found, the platform will switch this request to the now-best
4448 * network and inform the app of the newly best network by invoking
4449 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4450 * will not try to maintain any other network than the best one currently matching the request:
4451 * a network not matching any network request may be disconnected at any time.
4452 *
4453 * <p>For example, an application could use this method to obtain a connected cellular network
4454 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4455 * radio to consume additional power. Or, an application could inform the system that it wants
4456 * a network supporting sending MMSes and have the system let it know about the currently best
4457 * MMS-supporting network through the provided {@link NetworkCallback}.
4458 *
4459 * <p>The status of the request can be followed by listening to the various callbacks described
4460 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4461 * used to direct traffic to the network (although accessing some networks may be subject to
4462 * holding specific permissions). Callers will learn about the specific characteristics of the
4463 * network through
4464 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4465 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4466 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4467 * matching the request at any given time; therefore when a better network matching the request
4468 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4469 * with the new network after which no further updates are given about the previously-best
4470 * network, unless it becomes the best again at some later time. All callbacks are invoked
4471 * in order on the same thread, which by default is a thread created by the framework running
4472 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004473 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004474 * callbacks are invoked.
4475 *
4476 * <p>This{@link NetworkRequest} will live until released via
4477 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4478 * which point the system may let go of the network at any time.
4479 *
4480 * <p>A version of this method which takes a timeout is
4481 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4482 * wait for a limited amount of time for the network to become unavailable.
4483 *
4484 * <p>It is presently unsupported to request a network with mutable
4485 * {@link NetworkCapabilities} such as
4486 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4487 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4488 * as these {@code NetworkCapabilities} represent states that a particular
4489 * network may never attain, and whether a network will attain these states
4490 * is unknown prior to bringing up the network so the framework does not
4491 * know how to go about satisfying a request with these capabilities.
4492 *
4493 * <p>This method requires the caller to hold either the
4494 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4495 * or the ability to modify system settings as determined by
4496 * {@link android.provider.Settings.System#canWrite}.</p>
4497 *
4498 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4499 * number of outstanding requests to 100 per app (identified by their UID), shared with
4500 * all variants of this method, of {@link #registerNetworkCallback} as well as
4501 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4502 * Requesting a network with this method will count toward this limit. If this limit is
4503 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4504 * make sure to unregister the callbacks with
4505 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4506 *
4507 * @param request {@link NetworkRequest} describing this request.
4508 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4509 * the callback must not be shared - it uniquely specifies this request.
4510 * The callback is invoked on the default internal Handler.
4511 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4512 * @throws SecurityException if missing the appropriate permissions.
4513 * @throws RuntimeException if the app already has too many callbacks registered.
4514 */
4515 public void requestNetwork(@NonNull NetworkRequest request,
4516 @NonNull NetworkCallback networkCallback) {
4517 requestNetwork(request, networkCallback, getDefaultHandler());
4518 }
4519
4520 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004521 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004522 *
4523 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4524 * but runs all the callbacks on the passed Handler.
4525 *
4526 * <p>This method has the same permission requirements as
4527 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4528 * and throws the same exceptions in the same conditions.
4529 *
4530 * @param request {@link NetworkRequest} describing this request.
4531 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4532 * the callback must not be shared - it uniquely specifies this request.
4533 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4534 */
4535 public void requestNetwork(@NonNull NetworkRequest request,
4536 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4537 CallbackHandler cbHandler = new CallbackHandler(handler);
4538 NetworkCapabilities nc = request.networkCapabilities;
4539 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4540 }
4541
4542 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004543 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004544 * by a timeout.
4545 *
4546 * This function behaves identically to the non-timed-out version
4547 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4548 * is not found within the given time (in milliseconds) the
4549 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4550 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4551 * not have to be released if timed-out (it is automatically released). Unregistering a
4552 * request that timed out is not an error.
4553 *
4554 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4555 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4556 * for that purpose. Calling this method will attempt to bring up the requested network.
4557 *
4558 * <p>This method has the same permission requirements as
4559 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4560 * and throws the same exceptions in the same conditions.
4561 *
4562 * @param request {@link NetworkRequest} describing this request.
4563 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4564 * the callback must not be shared - it uniquely specifies this request.
4565 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4566 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4567 * be a positive value (i.e. >0).
4568 */
4569 public void requestNetwork(@NonNull NetworkRequest request,
4570 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4571 checkTimeout(timeoutMs);
4572 NetworkCapabilities nc = request.networkCapabilities;
4573 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4574 getDefaultHandler());
4575 }
4576
4577 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004578 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004579 * by a timeout.
4580 *
4581 * This method behaves identically to
4582 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4583 * on the passed Handler.
4584 *
4585 * <p>This method has the same permission requirements as
4586 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4587 * and throws the same exceptions in the same conditions.
4588 *
4589 * @param request {@link NetworkRequest} describing this request.
4590 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4591 * the callback must not be shared - it uniquely specifies this request.
4592 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4593 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4594 * before {@link NetworkCallback#onUnavailable} is called.
4595 */
4596 public void requestNetwork(@NonNull NetworkRequest request,
4597 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4598 checkTimeout(timeoutMs);
4599 CallbackHandler cbHandler = new CallbackHandler(handler);
4600 NetworkCapabilities nc = request.networkCapabilities;
4601 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4602 }
4603
4604 /**
4605 * The lookup key for a {@link Network} object included with the intent after
4606 * successfully finding a network for the applications request. Retrieve it with
4607 * {@link android.content.Intent#getParcelableExtra(String)}.
4608 * <p>
4609 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4610 * then you must get a ConnectivityManager instance before doing so.
4611 */
4612 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4613
4614 /**
4615 * The lookup key for a {@link NetworkRequest} object included with the intent after
4616 * successfully finding a network for the applications request. Retrieve it with
4617 * {@link android.content.Intent#getParcelableExtra(String)}.
4618 */
4619 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4620
4621
4622 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004623 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004624 *
4625 * This function behaves identically to the version that takes a NetworkCallback, but instead
4626 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4627 * the request may outlive the calling application and get called back when a suitable
4628 * network is found.
4629 * <p>
4630 * The operation is an Intent broadcast that goes to a broadcast receiver that
4631 * you registered with {@link Context#registerReceiver} or through the
4632 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4633 * <p>
4634 * The operation Intent is delivered with two extras, a {@link Network} typed
4635 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4636 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4637 * the original requests parameters. It is important to create a new,
4638 * {@link NetworkCallback} based request before completing the processing of the
4639 * Intent to reserve the network or it will be released shortly after the Intent
4640 * is processed.
4641 * <p>
4642 * If there is already a request for this Intent registered (with the equality of
4643 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4644 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4645 * <p>
4646 * The request may be released normally by calling
4647 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4648 * <p>It is presently unsupported to request a network with either
4649 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4650 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4651 * as these {@code NetworkCapabilities} represent states that a particular
4652 * network may never attain, and whether a network will attain these states
4653 * is unknown prior to bringing up the network so the framework does not
4654 * know how to go about satisfying a request with these capabilities.
4655 *
4656 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4657 * number of outstanding requests to 100 per app (identified by their UID), shared with
4658 * all variants of this method, of {@link #registerNetworkCallback} as well as
4659 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4660 * Requesting a network with this method will count toward this limit. If this limit is
4661 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4662 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4663 * or {@link #releaseNetworkRequest(PendingIntent)}.
4664 *
4665 * <p>This method requires the caller to hold either the
4666 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4667 * or the ability to modify system settings as determined by
4668 * {@link android.provider.Settings.System#canWrite}.</p>
4669 *
4670 * @param request {@link NetworkRequest} describing this request.
4671 * @param operation Action to perform when the network is available (corresponds
4672 * to the {@link NetworkCallback#onAvailable} call. Typically
4673 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4674 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4675 * @throws SecurityException if missing the appropriate permissions.
4676 * @throws RuntimeException if the app already has too many callbacks registered.
4677 */
4678 public void requestNetwork(@NonNull NetworkRequest request,
4679 @NonNull PendingIntent operation) {
4680 printStackTrace();
4681 checkPendingIntentNotNull(operation);
4682 try {
4683 mService.pendingRequestForNetwork(
4684 request.networkCapabilities, operation, mContext.getOpPackageName(),
4685 getAttributionTag());
4686 } catch (RemoteException e) {
4687 throw e.rethrowFromSystemServer();
4688 } catch (ServiceSpecificException e) {
4689 throw convertServiceException(e);
4690 }
4691 }
4692
4693 /**
4694 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4695 * <p>
4696 * This method has the same behavior as
4697 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4698 * releasing network resources and disconnecting.
4699 *
4700 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4701 * PendingIntent passed to
4702 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4703 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4704 */
4705 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4706 printStackTrace();
4707 checkPendingIntentNotNull(operation);
4708 try {
4709 mService.releasePendingNetworkRequest(operation);
4710 } catch (RemoteException e) {
4711 throw e.rethrowFromSystemServer();
4712 }
4713 }
4714
4715 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004716 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004717 }
4718
4719 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004720 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004721 }
4722
4723 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004724 if (timeoutMs <= 0) {
4725 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4726 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004727 }
4728
4729 /**
4730 * Registers to receive notifications about all networks which satisfy the given
4731 * {@link NetworkRequest}. The callbacks will continue to be called until
4732 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4733 * called.
4734 *
4735 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4736 * number of outstanding requests to 100 per app (identified by their UID), shared with
4737 * all variants of this method, of {@link #requestNetwork} as well as
4738 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4739 * Requesting a network with this method will count toward this limit. If this limit is
4740 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4741 * make sure to unregister the callbacks with
4742 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4743 *
4744 * @param request {@link NetworkRequest} describing this request.
4745 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4746 * networks change state.
4747 * The callback is invoked on the default internal Handler.
4748 * @throws RuntimeException if the app already has too many callbacks registered.
4749 */
4750 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4751 public void registerNetworkCallback(@NonNull NetworkRequest request,
4752 @NonNull NetworkCallback networkCallback) {
4753 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4754 }
4755
4756 /**
4757 * Registers to receive notifications about all networks which satisfy the given
4758 * {@link NetworkRequest}. The callbacks will continue to be called until
4759 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4760 * called.
4761 *
4762 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4763 * number of outstanding requests to 100 per app (identified by their UID), shared with
4764 * all variants of this method, of {@link #requestNetwork} as well as
4765 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4766 * Requesting a network with this method will count toward this limit. If this limit is
4767 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4768 * make sure to unregister the callbacks with
4769 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4770 *
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 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
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, @NonNull Handler handler) {
4781 CallbackHandler cbHandler = new CallbackHandler(handler);
4782 NetworkCapabilities nc = request.networkCapabilities;
4783 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4784 }
4785
4786 /**
4787 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4788 * {@link NetworkRequest}.
4789 *
4790 * This function behaves identically to the version that takes a NetworkCallback, but instead
4791 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4792 * the request may outlive the calling application and get called back when a suitable
4793 * network is found.
4794 * <p>
4795 * The operation is an Intent broadcast that goes to a broadcast receiver that
4796 * you registered with {@link Context#registerReceiver} or through the
4797 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4798 * <p>
4799 * The operation Intent is delivered with two extras, a {@link Network} typed
4800 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4801 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4802 * the original requests parameters.
4803 * <p>
4804 * If there is already a request for this Intent registered (with the equality of
4805 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4806 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4807 * <p>
4808 * The request may be released normally by calling
4809 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4810 *
4811 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4812 * number of outstanding requests to 100 per app (identified by their UID), shared with
4813 * all variants of this method, of {@link #requestNetwork} as well as
4814 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4815 * Requesting a network with this method will count toward this limit. If this limit is
4816 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4817 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4818 * or {@link #releaseNetworkRequest(PendingIntent)}.
4819 *
4820 * @param request {@link NetworkRequest} describing this request.
4821 * @param operation Action to perform when the network is available (corresponds
4822 * to the {@link NetworkCallback#onAvailable} call. Typically
4823 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4824 * @throws RuntimeException if the app already has too many callbacks registered.
4825 */
4826 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4827 public void registerNetworkCallback(@NonNull NetworkRequest request,
4828 @NonNull PendingIntent operation) {
4829 printStackTrace();
4830 checkPendingIntentNotNull(operation);
4831 try {
4832 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004833 request.networkCapabilities, operation, mContext.getOpPackageName(),
4834 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004835 } catch (RemoteException e) {
4836 throw e.rethrowFromSystemServer();
4837 } catch (ServiceSpecificException e) {
4838 throw convertServiceException(e);
4839 }
4840 }
4841
4842 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004843 * Registers to receive notifications about changes in the application's default network. This
4844 * may be a physical network or a virtual network, such as a VPN that applies to the
4845 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004846 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4847 *
4848 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4849 * number of outstanding requests to 100 per app (identified by their UID), shared with
4850 * all variants of this method, of {@link #requestNetwork} as well as
4851 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4852 * Requesting a network with this method will count toward this limit. If this limit is
4853 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4854 * make sure to unregister the callbacks with
4855 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4856 *
4857 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004858 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004859 * The callback is invoked on the default internal Handler.
4860 * @throws RuntimeException if the app already has too many callbacks registered.
4861 */
4862 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4863 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4864 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4865 }
4866
4867 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004868 * Registers to receive notifications about changes in the application's default network. This
4869 * may be a physical network or a virtual network, such as a VPN that applies to the
4870 * application. The callbacks will continue to be called until either the application exits or
4871 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4872 *
4873 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4874 * number of outstanding requests to 100 per app (identified by their UID), shared with
4875 * all variants of this method, of {@link #requestNetwork} as well as
4876 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4877 * Requesting a network with this method will count toward this limit. If this limit is
4878 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4879 * make sure to unregister the callbacks with
4880 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4881 *
4882 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4883 * application's default network changes.
4884 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4885 * @throws RuntimeException if the app already has too many callbacks registered.
4886 */
4887 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4888 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4889 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004890 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004891 }
4892
4893 /**
4894 * Registers to receive notifications about changes in the default network for the specified
4895 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4896 * UID. The callbacks will continue to be called until either the application exits or
4897 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4898 *
4899 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4900 * number of outstanding requests to 100 per app (identified by their UID), shared with
4901 * all variants of this method, of {@link #requestNetwork} as well as
4902 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4903 * Requesting a network with this method will count toward this limit. If this limit is
4904 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4905 * make sure to unregister the callbacks with
4906 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4907 *
4908 * @param uid the UID for which to track default network changes.
4909 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4910 * UID's default network changes.
4911 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4912 * @throws RuntimeException if the app already has too many callbacks registered.
4913 * @hide
4914 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004915 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004916 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4917 @RequiresPermission(anyOf = {
4918 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4919 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004920 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004921 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004922 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004923 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004924 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4925 }
4926
4927 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004928 * Registers to receive notifications about changes in the system default network. The callbacks
4929 * will continue to be called until either the application exits or
4930 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4931 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004932 * This method should not be used to determine networking state seen by applications, because in
4933 * many cases, most or even all application traffic may not use the default network directly,
4934 * and traffic from different applications may go on different networks by default. As an
4935 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4936 * and not onto the system default network. Applications or system components desiring to do
4937 * determine network state as seen by applications should use other methods such as
4938 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4939 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004940 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4941 * number of outstanding requests to 100 per app (identified by their UID), shared with
4942 * all variants of this method, of {@link #requestNetwork} as well as
4943 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4944 * Requesting a network with this method will count toward this limit. If this limit is
4945 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4946 * make sure to unregister the callbacks with
4947 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4948 *
4949 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4950 * system default network changes.
4951 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4952 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004953 *
4954 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004955 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004956 @SystemApi(client = MODULE_LIBRARIES)
4957 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4958 @RequiresPermission(anyOf = {
4959 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004960 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00004961 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004962 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004963 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004964 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004965 CallbackHandler cbHandler = new CallbackHandler(handler);
4966 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004967 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004968 }
4969
4970 /**
junyulaibd123062021-03-15 11:48:48 +08004971 * Registers to receive notifications about the best matching network which satisfy the given
4972 * {@link NetworkRequest}. The callbacks will continue to be called until
4973 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4974 * called.
4975 *
4976 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4977 * number of outstanding requests to 100 per app (identified by their UID), shared with
4978 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4979 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4980 * Requesting a network with this method will count toward this limit. If this limit is
4981 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4982 * make sure to unregister the callbacks with
4983 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4984 *
4985 *
4986 * @param request {@link NetworkRequest} describing this request.
4987 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4988 * networks change state.
4989 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4990 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004991 */
junyulai5a5c99b2021-03-05 15:51:17 +08004992 @SuppressLint("ExecutorRegistration")
4993 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4994 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4995 final NetworkCapabilities nc = request.networkCapabilities;
4996 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004997 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004998 }
4999
5000 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005001 * Requests bandwidth update for a given {@link Network} and returns whether the update request
5002 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
5003 * network connection for updated bandwidth information. The caller will be notified via
5004 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
5005 * method assumes that the caller has previously called
5006 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
5007 * changes.
5008 *
5009 * @param network {@link Network} specifying which network you're interested.
5010 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5011 */
5012 public boolean requestBandwidthUpdate(@NonNull Network network) {
5013 try {
5014 return mService.requestBandwidthUpdate(network);
5015 } catch (RemoteException e) {
5016 throw e.rethrowFromSystemServer();
5017 }
5018 }
5019
5020 /**
5021 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
5022 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
5023 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005024 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
5025 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005026 *
5027 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
5028 * triggering it as soon as this call returns.
5029 *
5030 * @param networkCallback The {@link NetworkCallback} used when making the request.
5031 */
5032 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
5033 printStackTrace();
5034 checkCallbackNotNull(networkCallback);
5035 final List<NetworkRequest> reqs = new ArrayList<>();
5036 // Find all requests associated to this callback and stop callback triggers immediately.
5037 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
5038 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00005039 if (networkCallback.networkRequest == null) {
5040 throw new IllegalArgumentException("NetworkCallback was not registered");
5041 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005042 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
5043 Log.d(TAG, "NetworkCallback was already unregistered");
5044 return;
5045 }
5046 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
5047 if (e.getValue() == networkCallback) {
5048 reqs.add(e.getKey());
5049 }
5050 }
5051 // TODO: throw exception if callback was registered more than once (http://b/20701525).
5052 for (NetworkRequest r : reqs) {
5053 try {
5054 mService.releaseNetworkRequest(r);
5055 } catch (RemoteException e) {
5056 throw e.rethrowFromSystemServer();
5057 }
5058 // Only remove mapping if rpc was successful.
5059 sCallbacks.remove(r);
5060 }
5061 networkCallback.networkRequest = ALREADY_UNREGISTERED;
5062 }
5063 }
5064
5065 /**
5066 * Unregisters a callback previously registered via
5067 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5068 *
5069 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
5070 * PendingIntent passed to
5071 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5072 * Cannot be null.
5073 */
5074 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
5075 releaseNetworkRequest(operation);
5076 }
5077
5078 /**
5079 * Informs the system whether it should switch to {@code network} regardless of whether it is
5080 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
5081 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
5082 * the system default network regardless of any other network that's currently connected. If
5083 * {@code always} is true, then the choice is remembered, so that the next time the user
5084 * connects to this network, the system will switch to it.
5085 *
5086 * @param network The network to accept.
5087 * @param accept Whether to accept the network even if unvalidated.
5088 * @param always Whether to remember this choice in the future.
5089 *
5090 * @hide
5091 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005092 @SystemApi(client = MODULE_LIBRARIES)
5093 @RequiresPermission(anyOf = {
5094 android.Manifest.permission.NETWORK_SETTINGS,
5095 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5096 android.Manifest.permission.NETWORK_STACK,
5097 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5098 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005099 try {
5100 mService.setAcceptUnvalidated(network, accept, always);
5101 } catch (RemoteException e) {
5102 throw e.rethrowFromSystemServer();
5103 }
5104 }
5105
5106 /**
5107 * Informs the system whether it should consider the network as validated even if it only has
5108 * partial connectivity. If {@code accept} is true, then the network will be considered as
5109 * validated even if connectivity is only partial. If {@code always} is true, then the choice
5110 * is remembered, so that the next time the user connects to this network, the system will
5111 * switch to it.
5112 *
5113 * @param network The network to accept.
5114 * @param accept Whether to consider the network as validated even if it has partial
5115 * connectivity.
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 setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5127 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005128 try {
5129 mService.setAcceptPartialConnectivity(network, accept, always);
5130 } catch (RemoteException e) {
5131 throw e.rethrowFromSystemServer();
5132 }
5133 }
5134
5135 /**
5136 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5137 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5138 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5139 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5140 *
5141 * @param network The network to accept.
5142 *
5143 * @hide
5144 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005145 @SystemApi(client = MODULE_LIBRARIES)
5146 @RequiresPermission(anyOf = {
5147 android.Manifest.permission.NETWORK_SETTINGS,
5148 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5149 android.Manifest.permission.NETWORK_STACK,
5150 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5151 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005152 try {
5153 mService.setAvoidUnvalidated(network);
5154 } catch (RemoteException e) {
5155 throw e.rethrowFromSystemServer();
5156 }
5157 }
5158
5159 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005160 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005161 *
5162 * @param timeMs The expired current time. The value should be set within a limited time from
5163 * now.
5164 *
5165 * @hide
5166 */
5167 public void setTestAllowBadWifiUntil(long timeMs) {
5168 try {
5169 mService.setTestAllowBadWifiUntil(timeMs);
5170 } catch (RemoteException e) {
5171 throw e.rethrowFromSystemServer();
5172 }
5173 }
5174
5175 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005176 * Requests that the system open the captive portal app on the specified network.
5177 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005178 * <p>This is to be used on networks where a captive portal was detected, as per
5179 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5180 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005181 * @param network The network to log into.
5182 *
5183 * @hide
5184 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005185 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5186 @RequiresPermission(anyOf = {
5187 android.Manifest.permission.NETWORK_SETTINGS,
5188 android.Manifest.permission.NETWORK_STACK,
5189 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5190 })
5191 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005192 try {
5193 mService.startCaptivePortalApp(network);
5194 } catch (RemoteException e) {
5195 throw e.rethrowFromSystemServer();
5196 }
5197 }
5198
5199 /**
5200 * Requests that the system open the captive portal app with the specified extras.
5201 *
5202 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5203 * corresponding permission.
5204 * @param network Network on which the captive portal was detected.
5205 * @param appExtras Extras to include in the app start intent.
5206 * @hide
5207 */
5208 @SystemApi
5209 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5210 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5211 try {
5212 mService.startCaptivePortalAppInternal(network, appExtras);
5213 } catch (RemoteException e) {
5214 throw e.rethrowFromSystemServer();
5215 }
5216 }
5217
5218 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005219 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005220 * @hide
5221 */
5222 @SystemApi
5223 @RequiresPermission(anyOf = {
5224 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5225 android.Manifest.permission.NETWORK_STACK})
5226 public boolean shouldAvoidBadWifi() {
5227 try {
5228 return mService.shouldAvoidBadWifi();
5229 } catch (RemoteException e) {
5230 throw e.rethrowFromSystemServer();
5231 }
5232 }
5233
5234 /**
5235 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5236 * time-sensitive user-facing operations when the system default network is temporarily
5237 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5238 * this method), and the operation should be infrequent to ensure that data usage is limited.
5239 *
5240 * An example of such an operation might be a time-sensitive foreground activity, such as a
5241 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5242 */
5243 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5244
5245 /**
5246 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5247 * a backup channel for traffic that is primarily going over another network.
5248 *
5249 * An example might be maintaining backup connections to peers or servers for the purpose of
5250 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5251 * on backup paths should be negligible compared to the traffic on the main path.
5252 */
5253 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5254
5255 /**
5256 * It is acceptable to use metered data to improve network latency and performance.
5257 */
5258 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5259
5260 /**
5261 * Return value to use for unmetered networks. On such networks we currently set all the flags
5262 * to true.
5263 * @hide
5264 */
5265 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5266 MULTIPATH_PREFERENCE_HANDOVER |
5267 MULTIPATH_PREFERENCE_RELIABILITY |
5268 MULTIPATH_PREFERENCE_PERFORMANCE;
5269
Aaron Huangcff22942021-05-27 16:31:26 +08005270 /** @hide */
5271 @Retention(RetentionPolicy.SOURCE)
5272 @IntDef(flag = true, value = {
5273 MULTIPATH_PREFERENCE_HANDOVER,
5274 MULTIPATH_PREFERENCE_RELIABILITY,
5275 MULTIPATH_PREFERENCE_PERFORMANCE,
5276 })
5277 public @interface MultipathPreference {
5278 }
5279
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005280 /**
5281 * Provides a hint to the calling application on whether it is desirable to use the
5282 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5283 * for multipath data transfer on this network when it is not the system default network.
5284 * Applications desiring to use multipath network protocols should call this method before
5285 * each such operation.
5286 *
5287 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005288 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005289 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005290 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005291 */
5292 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5293 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5294 try {
5295 return mService.getMultipathPreference(network);
5296 } catch (RemoteException e) {
5297 throw e.rethrowFromSystemServer();
5298 }
5299 }
5300
5301 /**
5302 * Resets all connectivity manager settings back to factory defaults.
5303 * @hide
5304 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005305 @SystemApi(client = MODULE_LIBRARIES)
5306 @RequiresPermission(anyOf = {
5307 android.Manifest.permission.NETWORK_SETTINGS,
5308 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005309 public void factoryReset() {
5310 try {
5311 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005312 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005313 } catch (RemoteException e) {
5314 throw e.rethrowFromSystemServer();
5315 }
5316 }
5317
5318 /**
5319 * Binds the current process to {@code network}. All Sockets created in the future
5320 * (and not explicitly bound via a bound SocketFactory from
5321 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5322 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5323 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5324 * work and all host name resolutions will fail. This is by design so an application doesn't
5325 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5326 * To clear binding pass {@code null} for {@code network}. Using individually bound
5327 * Sockets created by Network.getSocketFactory().createSocket() and
5328 * performing network-specific host name resolutions via
5329 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5330 * {@code bindProcessToNetwork}.
5331 *
5332 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5333 * the current binding.
5334 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5335 */
5336 public boolean bindProcessToNetwork(@Nullable Network network) {
5337 // Forcing callers to call through non-static function ensures ConnectivityManager
5338 // instantiated.
5339 return setProcessDefaultNetwork(network);
5340 }
5341
5342 /**
5343 * Binds the current process to {@code network}. All Sockets created in the future
5344 * (and not explicitly bound via a bound SocketFactory from
5345 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5346 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5347 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5348 * work and all host name resolutions will fail. This is by design so an application doesn't
5349 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5350 * To clear binding pass {@code null} for {@code network}. Using individually bound
5351 * Sockets created by Network.getSocketFactory().createSocket() and
5352 * performing network-specific host name resolutions via
5353 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5354 * {@code setProcessDefaultNetwork}.
5355 *
5356 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5357 * the current binding.
5358 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5359 * @deprecated This function can throw {@link IllegalStateException}. Use
5360 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5361 * is a direct replacement.
5362 */
5363 @Deprecated
5364 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5365 int netId = (network == null) ? NETID_UNSET : network.netId;
5366 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5367
5368 if (netId != NETID_UNSET) {
5369 netId = network.getNetIdForResolv();
5370 }
5371
5372 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5373 return false;
5374 }
5375
5376 if (!isSameNetId) {
5377 // Set HTTP proxy system properties to match network.
5378 // TODO: Deprecate this static method and replace it with a non-static version.
5379 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005380 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005381 } catch (SecurityException e) {
5382 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5383 Log.e(TAG, "Can't set proxy properties", e);
5384 }
5385 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005386 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005387 // Must flush socket pool as idle sockets will be bound to previous network and may
5388 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005389 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005390 }
5391
5392 return true;
5393 }
5394
5395 /**
5396 * Returns the {@link Network} currently bound to this process via
5397 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5398 *
5399 * @return {@code Network} to which this process is bound, or {@code null}.
5400 */
5401 @Nullable
5402 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005403 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005404 // instantiated.
5405 return getProcessDefaultNetwork();
5406 }
5407
5408 /**
5409 * Returns the {@link Network} currently bound to this process via
5410 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5411 *
5412 * @return {@code Network} to which this process is bound, or {@code null}.
5413 * @deprecated Using this function can lead to other functions throwing
5414 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5415 * {@code getBoundNetworkForProcess} is a direct replacement.
5416 */
5417 @Deprecated
5418 @Nullable
5419 public static Network getProcessDefaultNetwork() {
5420 int netId = NetworkUtils.getBoundNetworkForProcess();
5421 if (netId == NETID_UNSET) return null;
5422 return new Network(netId);
5423 }
5424
5425 private void unsupportedStartingFrom(int version) {
5426 if (Process.myUid() == Process.SYSTEM_UID) {
5427 // The getApplicationInfo() call we make below is not supported in system context. Let
5428 // the call through here, and rely on the fact that ConnectivityService will refuse to
5429 // allow the system to use these APIs anyway.
5430 return;
5431 }
5432
5433 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5434 throw new UnsupportedOperationException(
5435 "This method is not supported in target SDK version " + version + " and above");
5436 }
5437 }
5438
5439 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5440 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5441 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5442 // remove these exemptions. Note that this check is not secure, and apps can still access these
5443 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5444 // so is unsupported and may break in the future. http://b/22728205
5445 private void checkLegacyRoutingApiAccess() {
5446 unsupportedStartingFrom(VERSION_CODES.M);
5447 }
5448
5449 /**
5450 * Binds host resolutions performed by this process to {@code network}.
5451 * {@link #bindProcessToNetwork} takes precedence over this setting.
5452 *
5453 * @param network The {@link Network} to bind host resolutions from the current process to, or
5454 * {@code null} to clear the current binding.
5455 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5456 * @hide
5457 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5458 */
5459 @Deprecated
5460 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5461 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5462 return NetworkUtils.bindProcessToNetworkForHostResolution(
5463 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5464 }
5465
5466 /**
5467 * Device is not restricting metered network activity while application is running on
5468 * background.
5469 */
5470 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5471
5472 /**
5473 * Device is restricting metered network activity while application is running on background,
5474 * but application is allowed to bypass it.
5475 * <p>
5476 * In this state, application should take action to mitigate metered network access.
5477 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5478 */
5479 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5480
5481 /**
5482 * Device is restricting metered network activity while application is running on background.
5483 * <p>
5484 * In this state, application should not try to use the network while running on background,
5485 * because it would be denied.
5486 */
5487 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5488
5489 /**
5490 * A change in the background metered network activity restriction has occurred.
5491 * <p>
5492 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5493 * applies to them.
5494 * <p>
5495 * This is only sent to registered receivers, not manifest receivers.
5496 */
5497 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5498 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5499 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5500
Aaron Huangcff22942021-05-27 16:31:26 +08005501 /** @hide */
5502 @Retention(RetentionPolicy.SOURCE)
5503 @IntDef(flag = false, value = {
5504 RESTRICT_BACKGROUND_STATUS_DISABLED,
5505 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5506 RESTRICT_BACKGROUND_STATUS_ENABLED,
5507 })
5508 public @interface RestrictBackgroundStatus {
5509 }
5510
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005511 /**
5512 * Determines if the calling application is subject to metered network restrictions while
5513 * running on background.
5514 *
5515 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5516 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5517 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5518 */
5519 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5520 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005521 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005522 } catch (RemoteException e) {
5523 throw e.rethrowFromSystemServer();
5524 }
5525 }
5526
5527 /**
5528 * The network watchlist is a list of domains and IP addresses that are associated with
5529 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5530 * currently used by the system for validation purposes.
5531 *
5532 * @return Hash of network watchlist config file. Null if config does not exist.
5533 */
5534 @Nullable
5535 public byte[] getNetworkWatchlistConfigHash() {
5536 try {
5537 return mService.getNetworkWatchlistConfigHash();
5538 } catch (RemoteException e) {
5539 Log.e(TAG, "Unable to get watchlist config hash");
5540 throw e.rethrowFromSystemServer();
5541 }
5542 }
5543
5544 /**
5545 * Returns the {@code uid} of the owner of a network connection.
5546 *
5547 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5548 * IPPROTO_UDP} currently supported.
5549 * @param local The local {@link InetSocketAddress} of a connection.
5550 * @param remote The remote {@link InetSocketAddress} of a connection.
5551 * @return {@code uid} if the connection is found and the app has permission to observe it
5552 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5553 * android.os.Process#INVALID_UID} if the connection is not found.
Sherri Lin443b7182023-02-08 04:49:29 +01005554 * @throws SecurityException if the caller is not the active VpnService for the current
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005555 * user.
Sherri Lin443b7182023-02-08 04:49:29 +01005556 * @throws IllegalArgumentException if an unsupported protocol is requested.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005557 */
5558 public int getConnectionOwnerUid(
5559 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5560 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5561 try {
5562 return mService.getConnectionOwnerUid(connectionInfo);
5563 } catch (RemoteException e) {
5564 throw e.rethrowFromSystemServer();
5565 }
5566 }
5567
5568 private void printStackTrace() {
5569 if (DEBUG) {
5570 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5571 final StringBuffer sb = new StringBuffer();
5572 for (int i = 3; i < callStack.length; i++) {
5573 final String stackTrace = callStack[i].toString();
5574 if (stackTrace == null || stackTrace.contains("android.os")) {
5575 break;
5576 }
5577 sb.append(" [").append(stackTrace).append("]");
5578 }
5579 Log.d(TAG, "StackLog:" + sb.toString());
5580 }
5581 }
5582
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005583 /** @hide */
5584 public TestNetworkManager startOrGetTestNetworkManager() {
5585 final IBinder tnBinder;
5586 try {
5587 tnBinder = mService.startOrGetTestNetworkService();
5588 } catch (RemoteException e) {
5589 throw e.rethrowFromSystemServer();
5590 }
5591
5592 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5593 }
5594
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005595 /** @hide */
5596 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5597 return new ConnectivityDiagnosticsManager(mContext, mService);
5598 }
5599
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005600 /**
5601 * Simulates a Data Stall for the specified Network.
5602 *
5603 * <p>This method should only be used for tests.
5604 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005605 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5606 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005607 *
5608 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005609 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5610 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5611 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005612 * @param network The Network for which a Data Stall is being simluated.
5613 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5614 * @throws SecurityException if the caller is not the owner of the given network.
5615 * @hide
5616 */
5617 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5618 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5619 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005620 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005621 @NonNull Network network, @NonNull PersistableBundle extras) {
5622 try {
5623 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5624 } catch (RemoteException e) {
5625 e.rethrowFromSystemServer();
5626 }
5627 }
5628
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005629 @NonNull
5630 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5631
5632 /**
5633 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5634 * receive available QoS events related to the {@link Network} and local ip + port
5635 * specified within socketInfo.
5636 * <p/>
5637 * The same {@link QosCallback} must be unregistered before being registered a second time,
5638 * otherwise {@link QosCallbackRegistrationException} is thrown.
5639 * <p/>
5640 * This API does not, in itself, require any permission if called with a network that is not
5641 * restricted. However, the underlying implementation currently only supports the IMS network,
5642 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5643 * useful, because they'd never be called back on networks that they would have access to.
5644 *
5645 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5646 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5647 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5648 * @throws RuntimeException if the app already has too many callbacks registered.
5649 *
5650 * Exceptions after the time of registration is passed through
5651 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5652 *
5653 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005654 * @param executor The executor on which the callback will be invoked. The provided
5655 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005656 * callbacks cannot be guaranteed.onQosCallbackRegistered
5657 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005658 *
5659 * @hide
5660 */
5661 @SystemApi
5662 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005663 @CallbackExecutor @NonNull final Executor executor,
5664 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005665 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005666 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005667 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005668
5669 try {
5670 synchronized (mQosCallbackConnections) {
5671 if (getQosCallbackConnection(callback) == null) {
5672 final QosCallbackConnection connection =
5673 new QosCallbackConnection(this, callback, executor);
5674 mQosCallbackConnections.add(connection);
5675 mService.registerQosSocketCallback(socketInfo, connection);
5676 } else {
5677 Log.e(TAG, "registerQosCallback: Callback already registered");
5678 throw new QosCallbackRegistrationException();
5679 }
5680 }
5681 } catch (final RemoteException e) {
5682 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5683
5684 // The same unregister method method is called for consistency even though nothing
5685 // will be sent to the ConnectivityService since the callback was never successfully
5686 // registered.
5687 unregisterQosCallback(callback);
5688 e.rethrowFromSystemServer();
5689 } catch (final ServiceSpecificException e) {
5690 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5691 unregisterQosCallback(callback);
5692 throw convertServiceException(e);
5693 }
5694 }
5695
5696 /**
5697 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5698 * events once unregistered and can be registered a second time.
5699 * <p/>
5700 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5701 *
5702 * @param callback the callback being unregistered
5703 *
5704 * @hide
5705 */
5706 @SystemApi
5707 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5708 Objects.requireNonNull(callback, "The callback must be non-null");
5709 try {
5710 synchronized (mQosCallbackConnections) {
5711 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5712 if (connection != null) {
5713 connection.stopReceivingMessages();
5714 mService.unregisterQosCallback(connection);
5715 mQosCallbackConnections.remove(connection);
5716 } else {
5717 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5718 }
5719 }
5720 } catch (final RemoteException e) {
5721 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5722 e.rethrowFromSystemServer();
5723 }
5724 }
5725
5726 /**
5727 * Gets the connection related to the callback.
5728 *
5729 * @param callback the callback to look up
5730 * @return the related connection
5731 */
5732 @Nullable
5733 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5734 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5735 // Checking by reference here is intentional
5736 if (connection.getCallback() == callback) {
5737 return connection;
5738 }
5739 }
5740 return null;
5741 }
5742
5743 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005744 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005745 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5746 * be used to request that the system provide a network without causing the network to be
5747 * in the foreground.
5748 *
5749 * <p>This method will attempt to find the best network that matches the passed
5750 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5751 * criteria. The platform will evaluate which network is the best at its own discretion.
5752 * Throughput, latency, cost per byte, policy, user preference and other considerations
5753 * may be factored in the decision of what is considered the best network.
5754 *
5755 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5756 * matching this request, while always attempting to match the request to a better network if
5757 * possible. If a better match is found, the platform will switch this request to the now-best
5758 * network and inform the app of the newly best network by invoking
5759 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5760 * will not try to maintain any other network than the best one currently matching the request:
5761 * a network not matching any network request may be disconnected at any time.
5762 *
5763 * <p>For example, an application could use this method to obtain a connected cellular network
5764 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5765 * radio to consume additional power. Or, an application could inform the system that it wants
5766 * a network supporting sending MMSes and have the system let it know about the currently best
5767 * MMS-supporting network through the provided {@link NetworkCallback}.
5768 *
5769 * <p>The status of the request can be followed by listening to the various callbacks described
5770 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5771 * used to direct traffic to the network (although accessing some networks may be subject to
5772 * holding specific permissions). Callers will learn about the specific characteristics of the
5773 * network through
5774 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5775 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5776 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5777 * matching the request at any given time; therefore when a better network matching the request
5778 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5779 * with the new network after which no further updates are given about the previously-best
5780 * network, unless it becomes the best again at some later time. All callbacks are invoked
5781 * in order on the same thread, which by default is a thread created by the framework running
5782 * in the app.
5783 *
5784 * <p>This{@link NetworkRequest} will live until released via
5785 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5786 * which point the system may let go of the network at any time.
5787 *
5788 * <p>It is presently unsupported to request a network with mutable
5789 * {@link NetworkCapabilities} such as
5790 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5791 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5792 * as these {@code NetworkCapabilities} represent states that a particular
5793 * network may never attain, and whether a network will attain these states
5794 * is unknown prior to bringing up the network so the framework does not
5795 * know how to go about satisfying a request with these capabilities.
5796 *
5797 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5798 * number of outstanding requests to 100 per app (identified by their UID), shared with
5799 * all variants of this method, of {@link #registerNetworkCallback} as well as
5800 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5801 * Requesting a network with this method will count toward this limit. If this limit is
5802 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5803 * make sure to unregister the callbacks with
5804 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5805 *
5806 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005807 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5808 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005809 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5810 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005811 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5812 * @throws SecurityException if missing the appropriate permissions.
5813 * @throws RuntimeException if the app already has too many callbacks registered.
5814 *
5815 * @hide
5816 */
5817 @SystemApi(client = MODULE_LIBRARIES)
5818 @SuppressLint("ExecutorRegistration")
5819 @RequiresPermission(anyOf = {
5820 android.Manifest.permission.NETWORK_SETTINGS,
5821 android.Manifest.permission.NETWORK_STACK,
5822 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5823 })
5824 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005825 @NonNull NetworkCallback networkCallback,
5826 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005827 final NetworkCapabilities nc = request.networkCapabilities;
5828 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005829 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005830 }
James Mattis12aeab82021-01-10 14:24:24 -08005831
5832 /**
James Mattis12aeab82021-01-10 14:24:24 -08005833 * Used by automotive devices to set the network preferences used to direct traffic at an
5834 * application level as per the given OemNetworkPreferences. An example use-case would be an
5835 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5836 * vehicle via a particular network.
5837 *
5838 * Calling this will overwrite the existing preference.
5839 *
5840 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5841 * @param executor the executor on which listener will be invoked.
5842 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5843 * communicate completion of setOemNetworkPreference(). This will only be
5844 * called once upon successful completion of setOemNetworkPreference().
5845 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5846 * @throws SecurityException if missing the appropriate permissions.
5847 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005848 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005849 */
James Mattis6e2d7022021-01-26 16:23:52 -08005850 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005851 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005852 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005853 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005854 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005855 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5856 if (null != listener) {
5857 Objects.requireNonNull(executor, "Executor must be non-null");
5858 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005859 final IOnCompleteListener listenerInternal = listener == null ? null :
5860 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005861 @Override
5862 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005863 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005864 }
5865 };
5866
5867 try {
5868 mService.setOemNetworkPreference(preference, listenerInternal);
5869 } catch (RemoteException e) {
5870 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5871 throw e.rethrowFromSystemServer();
5872 }
5873 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005874
Chalard Jeanad565e22021-02-25 17:23:40 +09005875 /**
5876 * Request that a user profile is put by default on a network matching a given preference.
5877 *
5878 * See the documentation for the individual preferences for a description of the supported
5879 * behaviors.
5880 *
5881 * @param profile the profile concerned.
5882 * @param preference the preference for this profile.
5883 * @param executor an executor to execute the listener on. Optional if listener is null.
5884 * @param listener an optional listener to listen for completion of the operation.
5885 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5886 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005887 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5888 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005889 * @hide
5890 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005891 // This function is for establishing per-profile default networking and can only be called by
5892 // the device policy manager, running as the system server. It would make no sense to call it
5893 // on a context for a user because it does not establish a setting on behalf of a user, rather
5894 // it establishes a setting for a user on behalf of the DPM.
5895 @SuppressLint({"UserHandle"})
5896 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005897 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005898 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005899 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005900 @ProfileNetworkPreferencePolicy final int preference,
5901 @Nullable @CallbackExecutor final Executor executor,
5902 @Nullable final Runnable listener) {
5903
5904 ProfileNetworkPreference.Builder preferenceBuilder =
5905 new ProfileNetworkPreference.Builder();
5906 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005907 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5908 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5909 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005910 setProfileNetworkPreferences(profile,
5911 List.of(preferenceBuilder.build()), executor, listener);
5912 }
5913
5914 /**
5915 * Set a list of default network selection policies for a user profile.
5916 *
5917 * Calling this API with a user handle defines the entire policy for that user handle.
5918 * It will overwrite any setting previously set for the same user profile,
5919 * and not affect previously set settings for other handles.
5920 *
5921 * Call this API with an empty list to remove settings for this user profile.
5922 *
5923 * See {@link ProfileNetworkPreference} for more details on each preference
5924 * parameter.
5925 *
5926 * @param profile the user profile for which the preference is being set.
5927 * @param profileNetworkPreferences the list of profile network preferences for the
5928 * provided profile.
5929 * @param executor an executor to execute the listener on. Optional if listener is null.
5930 * @param listener an optional listener to listen for completion of the operation.
5931 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5932 * @throws SecurityException if missing the appropriate permissions.
5933 * @hide
5934 */
5935 @SystemApi(client = MODULE_LIBRARIES)
5936 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5937 public void setProfileNetworkPreferences(
5938 @NonNull final UserHandle profile,
5939 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005940 @Nullable @CallbackExecutor final Executor executor,
5941 @Nullable final Runnable listener) {
5942 if (null != listener) {
5943 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5944 }
5945 final IOnCompleteListener proxy;
5946 if (null == listener) {
5947 proxy = null;
5948 } else {
5949 proxy = new IOnCompleteListener.Stub() {
5950 @Override
5951 public void onComplete() {
5952 executor.execute(listener::run);
5953 }
5954 };
5955 }
5956 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005957 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005958 } catch (RemoteException e) {
5959 throw e.rethrowFromSystemServer();
5960 }
5961 }
5962
lucaslin5cdbcfb2021-03-12 00:46:33 +08005963 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005964 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005965 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005966 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005967
5968 /**
5969 * Get the network ID range reserved for IPSec tunnel interfaces.
5970 *
5971 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5972 * @hide
5973 */
5974 @SystemApi(client = MODULE_LIBRARIES)
5975 @NonNull
5976 public static Range<Integer> getIpSecNetIdRange() {
5977 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5978 }
markchien738ad912021-12-09 18:15:45 +08005979
5980 /**
Junyu Laidf210362023-10-24 02:47:50 +00005981 * Sets data saver switch.
5982 *
5983 * @param enable True if enable.
5984 * @throws IllegalStateException if failed.
5985 * @hide
5986 */
5987 @FlaggedApi(Flags.SET_DATA_SAVER_VIA_CM)
5988 @SystemApi(client = MODULE_LIBRARIES)
5989 @RequiresPermission(anyOf = {
5990 android.Manifest.permission.NETWORK_SETTINGS,
5991 android.Manifest.permission.NETWORK_STACK,
5992 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5993 })
5994 public void setDataSaverEnabled(final boolean enable) {
5995 try {
5996 mService.setDataSaverEnabled(enable);
5997 } catch (RemoteException e) {
5998 throw e.rethrowFromSystemServer();
5999 }
6000 }
6001
6002 /**
markchiene46042b2022-03-02 18:07:35 +08006003 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
6004 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08006005 *
6006 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006007 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08006008 * @hide
6009 */
6010 @SystemApi(client = MODULE_LIBRARIES)
6011 @RequiresPermission(anyOf = {
6012 android.Manifest.permission.NETWORK_SETTINGS,
6013 android.Manifest.permission.NETWORK_STACK,
6014 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6015 })
markchiene46042b2022-03-02 18:07:35 +08006016 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006017 try {
markchiene46042b2022-03-02 18:07:35 +08006018 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08006019 } catch (RemoteException e) {
6020 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006021 }
6022 }
6023
6024 /**
markchiene46042b2022-03-02 18:07:35 +08006025 * Removes the specified UID from the list of UIDs that are allowed to use background data on
6026 * metered networks when background data is restricted. The deny list takes precedence over
6027 * the allow list.
6028 *
6029 * @param uid uid of target app
6030 * @throws IllegalStateException if updating allow list failed.
6031 * @hide
6032 */
6033 @SystemApi(client = MODULE_LIBRARIES)
6034 @RequiresPermission(anyOf = {
6035 android.Manifest.permission.NETWORK_SETTINGS,
6036 android.Manifest.permission.NETWORK_STACK,
6037 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6038 })
6039 public void removeUidFromMeteredNetworkAllowList(final int uid) {
6040 try {
6041 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
6042 } catch (RemoteException e) {
6043 throw e.rethrowFromSystemServer();
6044 }
6045 }
6046
6047 /**
6048 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
6049 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08006050 *
6051 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006052 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08006053 * @hide
6054 */
6055 @SystemApi(client = MODULE_LIBRARIES)
6056 @RequiresPermission(anyOf = {
6057 android.Manifest.permission.NETWORK_SETTINGS,
6058 android.Manifest.permission.NETWORK_STACK,
6059 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6060 })
markchiene46042b2022-03-02 18:07:35 +08006061 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006062 try {
markchiene46042b2022-03-02 18:07:35 +08006063 mService.updateMeteredNetworkDenyList(uid, true /* add */);
6064 } catch (RemoteException e) {
6065 throw e.rethrowFromSystemServer();
6066 }
6067 }
6068
6069 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09006070 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08006071 * networks if background data is not restricted. The deny list takes precedence over the
6072 * allow list.
6073 *
6074 * @param uid uid of target app
6075 * @throws IllegalStateException if updating deny list failed.
6076 * @hide
6077 */
6078 @SystemApi(client = MODULE_LIBRARIES)
6079 @RequiresPermission(anyOf = {
6080 android.Manifest.permission.NETWORK_SETTINGS,
6081 android.Manifest.permission.NETWORK_STACK,
6082 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6083 })
6084 public void removeUidFromMeteredNetworkDenyList(final int uid) {
6085 try {
6086 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08006087 } catch (RemoteException e) {
6088 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08006089 }
6090 }
6091
6092 /**
6093 * Sets a firewall rule for the specified UID on the specified chain.
6094 *
6095 * @param chain target chain.
6096 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08006097 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08006098 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08006099 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08006100 * @hide
6101 */
6102 @SystemApi(client = MODULE_LIBRARIES)
6103 @RequiresPermission(anyOf = {
6104 android.Manifest.permission.NETWORK_SETTINGS,
6105 android.Manifest.permission.NETWORK_STACK,
6106 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6107 })
markchien3c04e662022-03-22 16:29:56 +08006108 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
6109 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08006110 try {
markchien3c04e662022-03-22 16:29:56 +08006111 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08006112 } catch (RemoteException e) {
6113 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006114 }
6115 }
markchien98a6f952022-01-13 23:43:53 +08006116
6117 /**
Motomu Utsumi900b8062023-01-19 16:16:49 +09006118 * Get firewall rule of specified firewall chain on specified uid.
6119 *
6120 * @param chain target chain.
6121 * @param uid target uid
6122 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
6123 * @throws UnsupportedOperationException if called on pre-T devices.
6124 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6125 * cause of the failure.
6126 * @hide
6127 */
6128 @RequiresPermission(anyOf = {
6129 android.Manifest.permission.NETWORK_SETTINGS,
6130 android.Manifest.permission.NETWORK_STACK,
6131 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6132 })
6133 public int getUidFirewallRule(@FirewallChain final int chain, final int uid) {
6134 try {
6135 return mService.getUidFirewallRule(chain, uid);
6136 } catch (RemoteException e) {
6137 throw e.rethrowFromSystemServer();
6138 }
6139 }
6140
6141 /**
markchien98a6f952022-01-13 23:43:53 +08006142 * Enables or disables the specified firewall chain.
6143 *
6144 * @param chain target chain.
6145 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00006146 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08006147 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08006148 * @hide
6149 */
6150 @SystemApi(client = MODULE_LIBRARIES)
6151 @RequiresPermission(anyOf = {
6152 android.Manifest.permission.NETWORK_SETTINGS,
6153 android.Manifest.permission.NETWORK_STACK,
6154 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6155 })
6156 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
6157 try {
6158 mService.setFirewallChainEnabled(chain, enable);
6159 } catch (RemoteException e) {
6160 throw e.rethrowFromSystemServer();
6161 }
6162 }
markchien00a0bed2022-01-13 23:46:13 +08006163
6164 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00006165 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006166 *
6167 * @param chain target chain.
6168 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6169 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006170 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6171 * cause of the failure.
6172 * @hide
6173 */
6174 @RequiresPermission(anyOf = {
6175 android.Manifest.permission.NETWORK_SETTINGS,
6176 android.Manifest.permission.NETWORK_STACK,
6177 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6178 })
6179 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6180 try {
6181 return mService.getFirewallChainEnabled(chain);
6182 } catch (RemoteException e) {
6183 throw e.rethrowFromSystemServer();
6184 }
6185 }
6186
6187 /**
markchien00a0bed2022-01-13 23:46:13 +08006188 * Replaces the contents of the specified UID-based firewall chain.
6189 *
6190 * @param chain target chain to replace.
6191 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006192 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006193 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6194 * @hide
6195 */
6196 @SystemApi(client = MODULE_LIBRARIES)
6197 @RequiresPermission(anyOf = {
6198 android.Manifest.permission.NETWORK_SETTINGS,
6199 android.Manifest.permission.NETWORK_STACK,
6200 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6201 })
6202 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6203 Objects.requireNonNull(uids);
6204 try {
6205 mService.replaceFirewallChain(chain, uids);
6206 } catch (RemoteException e) {
6207 throw e.rethrowFromSystemServer();
6208 }
6209 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006210
Junyu Laie0031522023-08-29 18:32:57 +08006211 /**
Junyu Laic3dc5b62023-09-06 19:10:02 +08006212 * Helper class to track data saver status.
6213 *
6214 * The class will fetch current data saver status from {@link NetworkPolicyManager} when
6215 * initialized, and listening for status changed intent to cache the latest status.
6216 *
6217 * @hide
6218 */
6219 @TargetApi(Build.VERSION_CODES.TIRAMISU) // RECEIVER_NOT_EXPORTED requires T.
6220 @VisibleForTesting(visibility = PRIVATE)
6221 public static class DataSaverStatusTracker extends BroadcastReceiver {
6222 private static final Object sDataSaverStatusTrackerLock = new Object();
6223
6224 private static volatile DataSaverStatusTracker sInstance;
6225
6226 /**
6227 * Gets a static instance of the class.
6228 *
6229 * @param context A {@link Context} for initialization. Note that since the data saver
6230 * status is global on a device, passing any context is equivalent.
6231 * @return The static instance of a {@link DataSaverStatusTracker}.
6232 */
6233 public static DataSaverStatusTracker getInstance(@NonNull Context context) {
6234 if (sInstance == null) {
6235 synchronized (sDataSaverStatusTrackerLock) {
6236 if (sInstance == null) {
6237 sInstance = new DataSaverStatusTracker(context);
6238 }
6239 }
6240 }
6241 return sInstance;
6242 }
6243
6244 private final NetworkPolicyManager mNpm;
6245 // The value updates on the caller's binder thread or UI thread.
6246 private final AtomicBoolean mIsDataSaverEnabled;
6247
6248 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6249 public DataSaverStatusTracker(final Context context) {
6250 // To avoid leaks, take the application context.
6251 final Context appContext;
6252 if (context instanceof Application) {
6253 appContext = context;
6254 } else {
6255 appContext = context.getApplicationContext();
6256 }
6257
6258 if ((appContext.getApplicationInfo().flags & FLAG_PERSISTENT) == 0
6259 && (appContext.getApplicationInfo().flags & FLAG_SYSTEM) == 0) {
6260 throw new IllegalStateException("Unexpected caller: "
6261 + appContext.getApplicationInfo().packageName);
6262 }
6263
6264 mNpm = appContext.getSystemService(NetworkPolicyManager.class);
6265 final IntentFilter filter = new IntentFilter(
6266 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
6267 // The receiver should not receive broadcasts from other Apps.
6268 appContext.registerReceiver(this, filter, Context.RECEIVER_NOT_EXPORTED);
6269 mIsDataSaverEnabled = new AtomicBoolean();
6270 updateDataSaverEnabled();
6271 }
6272
6273 // Runs on caller's UI thread.
6274 @Override
6275 public void onReceive(Context context, Intent intent) {
6276 if (intent.getAction().equals(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED)) {
6277 updateDataSaverEnabled();
6278 } else {
6279 throw new IllegalStateException("Unexpected intent " + intent);
6280 }
6281 }
6282
6283 public boolean getDataSaverEnabled() {
6284 return mIsDataSaverEnabled.get();
6285 }
6286
6287 private void updateDataSaverEnabled() {
6288 // Uid doesn't really matter, but use a fixed UID to make things clearer.
6289 final int dataSaverForCallerUid = mNpm.getRestrictBackgroundStatus(Process.SYSTEM_UID);
6290 mIsDataSaverEnabled.set(dataSaverForCallerUid
6291 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
6292 }
6293 }
6294
6295 /**
6296 * Return whether the network is blocked for the given uid and metered condition.
Junyu Laie0031522023-08-29 18:32:57 +08006297 *
6298 * Similar to {@link NetworkPolicyManager#isUidNetworkingBlocked}, but directly reads the BPF
6299 * maps and therefore considerably faster. For use by the NetworkStack process only.
6300 *
6301 * @param uid The target uid.
Junyu Laic3dc5b62023-09-06 19:10:02 +08006302 * @param isNetworkMetered Whether the target network is metered.
6303 *
6304 * @return True if all networking with the given condition is blocked. Otherwise, false.
Junyu Laie0031522023-08-29 18:32:57 +08006305 * @throws IllegalStateException if the map cannot be opened.
6306 * @throws ServiceSpecificException if the read fails.
6307 * @hide
6308 */
6309 // This isn't protected by a standard Android permission since it can't
6310 // afford to do IPC for performance reasons. Instead, the access control
6311 // is provided by linux file group permission AID_NET_BW_ACCT and the
6312 // selinux context fs_bpf_net*.
6313 // Only the system server process and the network stack have access.
6314 // TODO: Expose api when ready.
6315 // @SystemApi(client = MODULE_LIBRARIES)
6316 @RequiresApi(Build.VERSION_CODES.TIRAMISU) // BPF maps were only mainlined in T
6317 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Junyu Laic3dc5b62023-09-06 19:10:02 +08006318 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Junyu Laie0031522023-08-29 18:32:57 +08006319 final BpfNetMapsReader reader = BpfNetMapsReader.getInstance();
6320
Junyu Laic3dc5b62023-09-06 19:10:02 +08006321 final boolean isDataSaverEnabled;
6322 // TODO: For U-QPR3+ devices, get data saver status from bpf configuration map directly.
6323 final DataSaverStatusTracker dataSaverStatusTracker =
6324 DataSaverStatusTracker.getInstance(mContext);
6325 isDataSaverEnabled = dataSaverStatusTracker.getDataSaverEnabled();
Junyu Laie0031522023-08-29 18:32:57 +08006326
Junyu Laic3dc5b62023-09-06 19:10:02 +08006327 return reader.isUidNetworkingBlocked(uid, isNetworkMetered, isDataSaverEnabled);
Junyu Laie0031522023-08-29 18:32:57 +08006328 }
6329
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006330 /** @hide */
6331 public IBinder getCompanionDeviceManagerProxyService() {
6332 try {
6333 return mService.getCompanionDeviceManagerProxyService();
6334 } catch (RemoteException e) {
6335 throw e.rethrowFromSystemServer();
6336 }
6337 }
Chalard Jean2fb66f12023-08-25 12:50:37 +09006338
6339 private static final Object sRoutingCoordinatorManagerLock = new Object();
6340 @GuardedBy("sRoutingCoordinatorManagerLock")
6341 private static RoutingCoordinatorManager sRoutingCoordinatorManager = null;
6342 /** @hide */
6343 @RequiresApi(Build.VERSION_CODES.S)
6344 public RoutingCoordinatorManager getRoutingCoordinatorManager() {
6345 try {
6346 synchronized (sRoutingCoordinatorManagerLock) {
6347 if (null == sRoutingCoordinatorManager) {
6348 sRoutingCoordinatorManager = new RoutingCoordinatorManager(mContext,
6349 IRoutingCoordinator.Stub.asInterface(
6350 mService.getRoutingCoordinatorService()));
6351 }
6352 return sRoutingCoordinatorManager;
6353 }
6354 } catch (RemoteException e) {
6355 throw e.rethrowFromSystemServer();
6356 }
6357 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006358}