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