blob: 5cc196897c8f2ac6f60a5e1b86670a3a25e26125 [file] [log] [blame]
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package android.net;
17
18import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080019import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
21import static android.net.NetworkRequest.Type.LISTEN;
junyulai7664f622021-03-12 20:05:08 +080022import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090023import static android.net.NetworkRequest.Type.REQUEST;
24import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colittia77d05e2021-01-29 20:14:04 +090025import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090026import static android.net.QosCallback.QosCallbackRegistrationException;
27
28import android.annotation.CallbackExecutor;
29import android.annotation.IntDef;
30import android.annotation.NonNull;
31import android.annotation.Nullable;
Chalard Jean2fb66f12023-08-25 12:50:37 +090032import android.annotation.RequiresApi;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090033import android.annotation.RequiresPermission;
34import android.annotation.SdkConstant;
35import android.annotation.SdkConstant.SdkConstantType;
36import android.annotation.SuppressLint;
37import android.annotation.SystemApi;
38import android.annotation.SystemService;
39import android.app.PendingIntent;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090040import android.app.admin.DevicePolicyManager;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090041import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090042import android.content.ComponentName;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090043import android.content.Context;
44import android.content.Intent;
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +090045import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090046import android.net.IpSecManager.UdpEncapsulationSocket;
47import android.net.SocketKeepalive.Callback;
48import android.net.TetheringManager.StartTetheringCallback;
49import android.net.TetheringManager.TetheringEventCallback;
50import android.net.TetheringManager.TetheringRequest;
51import android.os.Binder;
52import android.os.Build;
53import android.os.Build.VERSION_CODES;
54import android.os.Bundle;
55import android.os.Handler;
56import android.os.IBinder;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090057import android.os.Looper;
58import android.os.Message;
59import android.os.Messenger;
60import android.os.ParcelFileDescriptor;
61import android.os.PersistableBundle;
62import android.os.Process;
63import android.os.RemoteException;
64import android.os.ResultReceiver;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090065import android.os.ServiceSpecificException;
Chalard Jeanad565e22021-02-25 17:23:40 +090066import android.os.UserHandle;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090067import android.provider.Settings;
68import android.telephony.SubscriptionManager;
69import android.telephony.TelephonyManager;
70import android.util.ArrayMap;
71import android.util.Log;
72import android.util.Range;
73import android.util.SparseIntArray;
74
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090075import com.android.internal.annotations.GuardedBy;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090076
77import libcore.net.event.NetworkEventDispatcher;
78
79import java.io.IOException;
80import java.io.UncheckedIOException;
81import java.lang.annotation.Retention;
82import java.lang.annotation.RetentionPolicy;
83import java.net.DatagramSocket;
84import java.net.InetAddress;
85import java.net.InetSocketAddress;
86import java.net.Socket;
87import java.util.ArrayList;
88import java.util.Collection;
89import java.util.HashMap;
90import java.util.List;
91import java.util.Map;
92import java.util.Objects;
93import java.util.concurrent.Executor;
94import java.util.concurrent.ExecutorService;
95import java.util.concurrent.Executors;
96import java.util.concurrent.RejectedExecutionException;
97
98/**
99 * Class that answers queries about the state of network connectivity. It also
100 * notifies applications when network connectivity changes.
101 * <p>
102 * The primary responsibilities of this class are to:
103 * <ol>
104 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
105 * <li>Send broadcast intents when network connectivity changes</li>
106 * <li>Attempt to "fail over" to another network when connectivity to a network
107 * is lost</li>
108 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
109 * state of the available networks</li>
110 * <li>Provide an API that allows applications to request and select networks for their data
111 * traffic</li>
112 * </ol>
113 */
114@SystemService(Context.CONNECTIVITY_SERVICE)
115public class ConnectivityManager {
116 private static final String TAG = "ConnectivityManager";
117 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
118
119 /**
120 * A change in network connectivity has occurred. A default connection has either
121 * been established or lost. The NetworkInfo for the affected network is
122 * sent as an extra; it should be consulted to see what kind of
123 * connectivity event occurred.
124 * <p/>
125 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
126 * broadcast if they declare the broadcast receiver in their manifest. Apps
127 * will still receive broadcasts if they register their
128 * {@link android.content.BroadcastReceiver} with
129 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
130 * and that context is still valid.
131 * <p/>
132 * If this is a connection that was the result of failing over from a
133 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
134 * set to true.
135 * <p/>
136 * For a loss of connectivity, if the connectivity manager is attempting
137 * to connect (or has already connected) to another network, the
138 * NetworkInfo for the new network is also passed as an extra. This lets
139 * any receivers of the broadcast know that they should not necessarily
140 * tell the user that no data traffic will be possible. Instead, the
141 * receiver should expect another broadcast soon, indicating either that
142 * the failover attempt succeeded (and so there is still overall data
143 * connectivity), or that the failover attempt failed, meaning that all
144 * connectivity has been lost.
145 * <p/>
146 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
147 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900148 * <p />
149 * Note that this broadcast is deprecated and generally tries to implement backwards
150 * compatibility with older versions of Android. As such, it may not reflect new
151 * capabilities of the system, like multiple networks being connected at the same
152 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900153 *
154 * @deprecated apps should use the more versatile {@link #requestNetwork},
155 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
156 * functions instead for faster and more detailed updates about the network
157 * changes they care about.
158 */
159 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
160 @Deprecated
161 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
162
163 /**
164 * The device has connected to a network that has presented a captive
165 * portal, which is blocking Internet connectivity. The user was presented
166 * with a notification that network sign in is required,
167 * and the user invoked the notification's action indicating they
168 * desire to sign in to the network. Apps handling this activity should
169 * facilitate signing in to the network. This action includes a
170 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
171 * the network presenting the captive portal; all communication with the
172 * captive portal must be done using this {@code Network} object.
173 * <p/>
174 * This activity includes a {@link CaptivePortal} extra named
175 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
176 * outcomes of the captive portal sign in to the system:
177 * <ul>
178 * <li> When the app handling this action believes the user has signed in to
179 * the network and the captive portal has been dismissed, the app should
180 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
181 * reevaluate the network. If reevaluation finds the network no longer
182 * subject to a captive portal, the network may become the default active
183 * data network.</li>
184 * <li> When the app handling this action believes the user explicitly wants
185 * to ignore the captive portal and the network, the app should call
186 * {@link CaptivePortal#ignoreNetwork}. </li>
187 * </ul>
188 */
189 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
190 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
191
192 /**
193 * The lookup key for a {@link NetworkInfo} object. Retrieve with
194 * {@link android.content.Intent#getParcelableExtra(String)}.
195 *
196 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
197 * can't accurately represent modern network characteristics.
198 * Please obtain information about networks from the {@link NetworkCapabilities}
199 * or {@link LinkProperties} objects instead.
200 */
201 @Deprecated
202 public static final String EXTRA_NETWORK_INFO = "networkInfo";
203
204 /**
205 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
206 *
207 * @see android.content.Intent#getIntExtra(String, int)
208 * @deprecated The network type is not rich enough to represent the characteristics
209 * of modern networks. Please use {@link NetworkCapabilities} instead,
210 * in particular the transports.
211 */
212 @Deprecated
213 public static final String EXTRA_NETWORK_TYPE = "networkType";
214
215 /**
216 * The lookup key for a boolean that indicates whether a connect event
217 * is for a network to which the connectivity manager was failing over
218 * following a disconnect on another network.
219 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
220 *
221 * @deprecated See {@link NetworkInfo}.
222 */
223 @Deprecated
224 public static final String EXTRA_IS_FAILOVER = "isFailover";
225 /**
226 * The lookup key for a {@link NetworkInfo} object. This is supplied when
227 * there is another network that it may be possible to connect to. Retrieve with
228 * {@link android.content.Intent#getParcelableExtra(String)}.
229 *
230 * @deprecated See {@link NetworkInfo}.
231 */
232 @Deprecated
233 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
234 /**
235 * The lookup key for a boolean that indicates whether there is a
236 * complete lack of connectivity, i.e., no network is available.
237 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
238 */
239 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
240 /**
241 * The lookup key for a string that indicates why an attempt to connect
242 * to a network failed. The string has no particular structure. It is
243 * intended to be used in notifications presented to users. Retrieve
244 * it with {@link android.content.Intent#getStringExtra(String)}.
245 */
246 public static final String EXTRA_REASON = "reason";
247 /**
248 * The lookup key for a string that provides optionally supplied
249 * extra information about the network state. The information
250 * may be passed up from the lower networking layers, and its
251 * meaning may be specific to a particular network type. Retrieve
252 * it with {@link android.content.Intent#getStringExtra(String)}.
253 *
254 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
255 */
256 @Deprecated
257 public static final String EXTRA_EXTRA_INFO = "extraInfo";
258 /**
259 * The lookup key for an int that provides information about
260 * our connection to the internet at large. 0 indicates no connection,
261 * 100 indicates a great connection. Retrieve it with
262 * {@link android.content.Intent#getIntExtra(String, int)}.
263 * {@hide}
264 */
265 public static final String EXTRA_INET_CONDITION = "inetCondition";
266 /**
267 * The lookup key for a {@link CaptivePortal} object included with the
268 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
269 * object can be used to either indicate to the system that the captive
270 * portal has been dismissed or that the user does not want to pursue
271 * signing in to captive portal. Retrieve it with
272 * {@link android.content.Intent#getParcelableExtra(String)}.
273 */
274 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
275
276 /**
277 * Key for passing a URL to the captive portal login activity.
278 */
279 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
280
281 /**
282 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
283 * portal login activity.
284 * {@hide}
285 */
286 @SystemApi
287 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
288 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
289
290 /**
291 * Key for passing a user agent string to the captive portal login activity.
292 * {@hide}
293 */
294 @SystemApi
295 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
296 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
297
298 /**
299 * Broadcast action to indicate the change of data activity status
300 * (idle or active) on a network in a recent period.
301 * The network becomes active when data transmission is started, or
302 * idle if there is no data transmission for a period of time.
303 * {@hide}
304 */
305 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
306 public static final String ACTION_DATA_ACTIVITY_CHANGE =
307 "android.net.conn.DATA_ACTIVITY_CHANGE";
308 /**
309 * The lookup key for an enum that indicates the network device type on which this data activity
310 * change happens.
311 * {@hide}
312 */
313 public static final String EXTRA_DEVICE_TYPE = "deviceType";
314 /**
315 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
316 * it is actively sending or receiving data and {@code false} means it is idle.
317 * {@hide}
318 */
319 public static final String EXTRA_IS_ACTIVE = "isActive";
320 /**
321 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
322 * {@hide}
323 */
324 public static final String EXTRA_REALTIME_NS = "tsNanos";
325
326 /**
327 * Broadcast Action: The setting for background data usage has changed
328 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
329 * <p>
330 * If an application uses the network in the background, it should listen
331 * for this broadcast and stop using the background data if the value is
332 * {@code false}.
333 * <p>
334 *
335 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
336 * of background data depends on several combined factors, and
337 * this broadcast is no longer sent. Instead, when background
338 * data is unavailable, {@link #getActiveNetworkInfo()} will now
339 * appear disconnected. During first boot after a platform
340 * upgrade, this broadcast will be sent once if
341 * {@link #getBackgroundDataSetting()} was {@code false} before
342 * the upgrade.
343 */
344 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
345 @Deprecated
346 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
347 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
348
349 /**
350 * Broadcast Action: The network connection may not be good
351 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
352 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
353 * the network and it's condition.
354 * @hide
355 */
356 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
357 @UnsupportedAppUsage
358 public static final String INET_CONDITION_ACTION =
359 "android.net.conn.INET_CONDITION_ACTION";
360
361 /**
362 * Broadcast Action: A tetherable connection has come or gone.
363 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
364 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
365 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
366 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
367 * the current state of tethering. Each include a list of
368 * interface names in that state (may be empty).
369 * @hide
370 */
371 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
372 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
373 public static final String ACTION_TETHER_STATE_CHANGED =
374 TetheringManager.ACTION_TETHER_STATE_CHANGED;
375
376 /**
377 * @hide
378 * gives a String[] listing all the interfaces configured for
379 * tethering and currently available for tethering.
380 */
381 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
382 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
383
384 /**
385 * @hide
386 * gives a String[] listing all the interfaces currently in local-only
387 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
388 */
389 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
390
391 /**
392 * @hide
393 * gives a String[] listing all the interfaces currently tethered
394 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
395 */
396 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
397 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
398
399 /**
400 * @hide
401 * gives a String[] listing all the interfaces we tried to tether and
402 * failed. Use {@link #getLastTetherError} to find the error code
403 * for any interfaces listed here.
404 */
405 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
406 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
407
408 /**
409 * Broadcast Action: The captive portal tracker has finished its test.
410 * Sent only while running Setup Wizard, in lieu of showing a user
411 * notification.
412 * @hide
413 */
414 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
415 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
416 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
417 /**
418 * The lookup key for a boolean that indicates whether a captive portal was detected.
419 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
420 * @hide
421 */
422 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
423
424 /**
425 * Action used to display a dialog that asks the user whether to connect to a network that is
426 * not validated. This intent is used to start the dialog in settings via startActivity.
427 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800428 * This action includes a {@link Network} typed extra which is called
429 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
430 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900431 * @hide
432 */
lucaslincf6d4502021-03-04 17:09:51 +0800433 @SystemApi(client = MODULE_LIBRARIES)
434 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900435
436 /**
437 * Action used to display a dialog that asks the user whether to avoid a network that is no
438 * longer validated. This intent is used to start the dialog in settings via startActivity.
439 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800440 * This action includes a {@link Network} typed extra which is called
441 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
442 * validated.
443 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900444 * @hide
445 */
lucaslincf6d4502021-03-04 17:09:51 +0800446 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900447 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800448 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900449
450 /**
451 * Action used to display a dialog that asks the user whether to stay connected to a network
452 * that has not validated. This intent is used to start the dialog in settings via
453 * startActivity.
454 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800455 * This action includes a {@link Network} typed extra which is called
456 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
457 * connectivity.
458 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900459 * @hide
460 */
lucaslincf6d4502021-03-04 17:09:51 +0800461 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900462 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800463 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900464
465 /**
paulhub49c8422021-04-07 16:18:13 +0800466 * Clear DNS Cache Action: This is broadcast when networks have changed and old
467 * DNS entries should be cleared.
468 * @hide
469 */
470 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
471 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
472 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
473
474 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900475 * Invalid tethering type.
476 * @see #startTethering(int, boolean, OnStartTetheringCallback)
477 * @hide
478 */
479 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
480
481 /**
482 * Wifi tethering type.
483 * @see #startTethering(int, boolean, OnStartTetheringCallback)
484 * @hide
485 */
486 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900487 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900488
489 /**
490 * USB tethering type.
491 * @see #startTethering(int, boolean, OnStartTetheringCallback)
492 * @hide
493 */
494 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900495 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900496
497 /**
498 * Bluetooth tethering type.
499 * @see #startTethering(int, boolean, OnStartTetheringCallback)
500 * @hide
501 */
502 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900503 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900504
505 /**
506 * Wifi P2p tethering type.
507 * Wifi P2p tethering is set through events automatically, and don't
508 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
509 * @hide
510 */
511 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
512
513 /**
514 * Extra used for communicating with the TetherService. Includes the type of tethering to
515 * enable if any.
516 * @hide
517 */
518 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
519
520 /**
521 * Extra used for communicating with the TetherService. Includes the type of tethering for
522 * which to cancel provisioning.
523 * @hide
524 */
525 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
526
527 /**
528 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
529 * provisioning.
530 * @hide
531 */
532 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
533
534 /**
535 * Tells the TetherService to run a provision check now.
536 * @hide
537 */
538 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
539
540 /**
541 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
542 * which will receive provisioning results. Can be left empty.
543 * @hide
544 */
545 public static final String EXTRA_PROVISION_CALLBACK =
546 TetheringConstants.EXTRA_PROVISION_CALLBACK;
547
548 /**
549 * The absence of a connection type.
550 * @hide
551 */
552 @SystemApi
553 public static final int TYPE_NONE = -1;
554
555 /**
556 * A Mobile data connection. Devices may support more than one.
557 *
558 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
559 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000560 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900561 */
562 @Deprecated
563 public static final int TYPE_MOBILE = 0;
564
565 /**
566 * A WIFI data connection. Devices may support more than one.
567 *
568 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
569 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000570 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900571 */
572 @Deprecated
573 public static final int TYPE_WIFI = 1;
574
575 /**
576 * An MMS-specific Mobile data connection. This network type may use the
577 * same network interface as {@link #TYPE_MOBILE} or it may use a different
578 * one. This is used by applications needing to talk to the carrier's
579 * Multimedia Messaging Service servers.
580 *
581 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
582 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
583 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
584 */
585 @Deprecated
586 public static final int TYPE_MOBILE_MMS = 2;
587
588 /**
589 * A SUPL-specific Mobile data connection. This network type may use the
590 * same network interface as {@link #TYPE_MOBILE} or it may use a different
591 * one. This is used by applications needing to talk to the carrier's
592 * Secure User Plane Location servers for help locating the device.
593 *
594 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
595 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
596 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
597 */
598 @Deprecated
599 public static final int TYPE_MOBILE_SUPL = 3;
600
601 /**
602 * A DUN-specific Mobile data connection. This network type may use the
603 * same network interface as {@link #TYPE_MOBILE} or it may use a different
604 * one. This is sometimes by the system when setting up an upstream connection
605 * for tethering so that the carrier is aware of DUN traffic.
606 *
607 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
608 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
609 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
610 */
611 @Deprecated
612 public static final int TYPE_MOBILE_DUN = 4;
613
614 /**
615 * A High Priority Mobile data connection. This network type uses the
616 * same network interface as {@link #TYPE_MOBILE} but the routing setup
617 * is different.
618 *
619 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
620 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000621 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900622 */
623 @Deprecated
624 public static final int TYPE_MOBILE_HIPRI = 5;
625
626 /**
627 * A WiMAX data connection.
628 *
629 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
630 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000631 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900632 */
633 @Deprecated
634 public static final int TYPE_WIMAX = 6;
635
636 /**
637 * A Bluetooth data connection.
638 *
639 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
640 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000641 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900642 */
643 @Deprecated
644 public static final int TYPE_BLUETOOTH = 7;
645
646 /**
647 * Fake data connection. This should not be used on shipping devices.
648 * @deprecated This is not used any more.
649 */
650 @Deprecated
651 public static final int TYPE_DUMMY = 8;
652
653 /**
654 * An Ethernet data connection.
655 *
656 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
657 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000658 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900659 */
660 @Deprecated
661 public static final int TYPE_ETHERNET = 9;
662
663 /**
664 * Over the air Administration.
665 * @deprecated Use {@link NetworkCapabilities} instead.
666 * {@hide}
667 */
668 @Deprecated
669 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
670 public static final int TYPE_MOBILE_FOTA = 10;
671
672 /**
673 * IP Multimedia Subsystem.
674 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
675 * {@hide}
676 */
677 @Deprecated
678 @UnsupportedAppUsage
679 public static final int TYPE_MOBILE_IMS = 11;
680
681 /**
682 * Carrier Branded Services.
683 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
684 * {@hide}
685 */
686 @Deprecated
687 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
688 public static final int TYPE_MOBILE_CBS = 12;
689
690 /**
691 * A Wi-Fi p2p connection. Only requesting processes will have access to
692 * the peers connected.
693 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
694 * {@hide}
695 */
696 @Deprecated
697 @SystemApi
698 public static final int TYPE_WIFI_P2P = 13;
699
700 /**
701 * The network to use for initially attaching to the network
702 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
703 * {@hide}
704 */
705 @Deprecated
706 @UnsupportedAppUsage
707 public static final int TYPE_MOBILE_IA = 14;
708
709 /**
710 * Emergency PDN connection for emergency services. This
711 * may include IMS and MMS in emergency situations.
712 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
713 * {@hide}
714 */
715 @Deprecated
716 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
717 public static final int TYPE_MOBILE_EMERGENCY = 15;
718
719 /**
720 * The network that uses proxy to achieve connectivity.
721 * @deprecated Use {@link NetworkCapabilities} instead.
722 * {@hide}
723 */
724 @Deprecated
725 @SystemApi
726 public static final int TYPE_PROXY = 16;
727
728 /**
729 * A virtual network using one or more native bearers.
730 * It may or may not be providing security services.
731 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
732 */
733 @Deprecated
734 public static final int TYPE_VPN = 17;
735
736 /**
737 * A network that is exclusively meant to be used for testing
738 *
739 * @deprecated Use {@link NetworkCapabilities} instead.
740 * @hide
741 */
742 @Deprecated
743 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
744
745 /**
746 * @deprecated Use {@link NetworkCapabilities} instead.
747 * @hide
748 */
749 @Deprecated
750 @Retention(RetentionPolicy.SOURCE)
751 @IntDef(prefix = { "TYPE_" }, value = {
752 TYPE_NONE,
753 TYPE_MOBILE,
754 TYPE_WIFI,
755 TYPE_MOBILE_MMS,
756 TYPE_MOBILE_SUPL,
757 TYPE_MOBILE_DUN,
758 TYPE_MOBILE_HIPRI,
759 TYPE_WIMAX,
760 TYPE_BLUETOOTH,
761 TYPE_DUMMY,
762 TYPE_ETHERNET,
763 TYPE_MOBILE_FOTA,
764 TYPE_MOBILE_IMS,
765 TYPE_MOBILE_CBS,
766 TYPE_WIFI_P2P,
767 TYPE_MOBILE_IA,
768 TYPE_MOBILE_EMERGENCY,
769 TYPE_PROXY,
770 TYPE_VPN,
771 TYPE_TEST
772 })
773 public @interface LegacyNetworkType {}
774
775 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
776 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
777 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
778 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
779 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
780
781 /** {@hide} */
782 public static final int MAX_RADIO_TYPE = TYPE_TEST;
783
784 /** {@hide} */
785 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
786
787 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
788
789 /**
790 * If you want to set the default network preference,you can directly
791 * change the networkAttributes array in framework's config.xml.
792 *
793 * @deprecated Since we support so many more networks now, the single
794 * network default network preference can't really express
795 * the hierarchy. Instead, the default is defined by the
796 * networkAttributes in config.xml. You can determine
797 * the current value by calling {@link #getNetworkPreference()}
798 * from an App.
799 */
800 @Deprecated
801 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
802
803 /**
804 * @hide
805 */
806 public static final int REQUEST_ID_UNSET = 0;
807
808 /**
809 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
810 * This allows to distinguish when unregistering NetworkCallbacks those that were never
811 * registered from those that were already unregistered.
812 * @hide
813 */
814 private static final NetworkRequest ALREADY_UNREGISTERED =
815 new NetworkRequest.Builder().clearCapabilities().build();
816
817 /**
818 * A NetID indicating no Network is selected.
819 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
820 * @hide
821 */
822 public static final int NETID_UNSET = 0;
823
824 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000825 * Flag to indicate that an app is not subject to any restrictions that could result in its
826 * network access blocked.
827 *
828 * @hide
829 */
830 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
831 public static final int BLOCKED_REASON_NONE = 0;
832
833 /**
834 * Flag to indicate that an app is subject to Battery saver restrictions that would
835 * result in its network access being blocked.
836 *
837 * @hide
838 */
839 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
840 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
841
842 /**
843 * Flag to indicate that an app is subject to Doze restrictions that would
844 * result in its network access being blocked.
845 *
846 * @hide
847 */
848 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
849 public static final int BLOCKED_REASON_DOZE = 1 << 1;
850
851 /**
852 * Flag to indicate that an app is subject to App Standby restrictions that would
853 * result in its network access being blocked.
854 *
855 * @hide
856 */
857 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
858 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
859
860 /**
861 * Flag to indicate that an app is subject to Restricted mode restrictions that would
862 * result in its network access being blocked.
863 *
864 * @hide
865 */
866 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
867 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
868
869 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900870 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
871 * is not currently connected.
872 *
873 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
874 *
875 * @hide
876 */
877 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
878 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
879
880 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100881 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
882 * result in its network access being blocked.
883 *
884 * @hide
885 */
886 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
887 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
888
889 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000890 * Flag to indicate that an app is subject to Data saver restrictions that would
891 * result in its metered network access being blocked.
892 *
893 * @hide
894 */
895 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
896 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
897
898 /**
899 * Flag to indicate that an app is subject to user restrictions that would
900 * result in its metered network access being blocked.
901 *
902 * @hide
903 */
904 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
905 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
906
907 /**
908 * Flag to indicate that an app is subject to Device admin restrictions that would
909 * result in its metered network access being blocked.
910 *
911 * @hide
912 */
913 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
914 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
915
916 /**
917 * @hide
918 */
919 @Retention(RetentionPolicy.SOURCE)
920 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
921 BLOCKED_REASON_NONE,
922 BLOCKED_REASON_BATTERY_SAVER,
923 BLOCKED_REASON_DOZE,
924 BLOCKED_REASON_APP_STANDBY,
925 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900926 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100927 BLOCKED_REASON_LOW_POWER_STANDBY,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000928 BLOCKED_METERED_REASON_DATA_SAVER,
929 BLOCKED_METERED_REASON_USER_RESTRICTED,
930 BLOCKED_METERED_REASON_ADMIN_DISABLED,
931 })
932 public @interface BlockedReason {}
933
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900934 /**
935 * Set of blocked reasons that are only applicable on metered networks.
936 *
937 * @hide
938 */
939 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
940 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
941
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900942 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
943 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900944
Robert Horvathd945bf02022-01-27 19:55:16 +0100945 // LINT.IfChange(firewall_chain)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900946 /**
markchiene1561fa2021-12-09 22:00:56 +0800947 * Firewall chain for device idle (doze mode).
948 * Allowlist of apps that have network access in device idle.
949 * @hide
950 */
951 @SystemApi(client = MODULE_LIBRARIES)
952 public static final int FIREWALL_CHAIN_DOZABLE = 1;
953
954 /**
955 * Firewall chain used for app standby.
956 * Denylist of apps that do not have network access.
957 * @hide
958 */
959 @SystemApi(client = MODULE_LIBRARIES)
960 public static final int FIREWALL_CHAIN_STANDBY = 2;
961
962 /**
963 * Firewall chain used for battery saver.
964 * Allowlist of apps that have network access when battery saver is on.
965 * @hide
966 */
967 @SystemApi(client = MODULE_LIBRARIES)
968 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
969
970 /**
971 * Firewall chain used for restricted networking mode.
972 * Allowlist of apps that have access in restricted networking mode.
973 * @hide
974 */
975 @SystemApi(client = MODULE_LIBRARIES)
976 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
977
Robert Horvath34cba142022-01-27 19:52:43 +0100978 /**
979 * Firewall chain used for low power standby.
980 * Allowlist of apps that have access in low power standby.
981 * @hide
982 */
983 @SystemApi(client = MODULE_LIBRARIES)
984 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
985
Motomu Utsumib08654c2022-05-11 05:56:26 +0000986 /**
Motomu Utsumid9801492022-06-01 13:57:27 +0000987 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +0900988 *
989 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
990 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
991 *
992 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
993 * independent of the others. The chains can be enabled and disabled independently, and apps can
994 * be added and removed from each chain independently.
995 *
996 * @see #FIREWALL_CHAIN_OEM_DENY_2
997 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +0000998 * @hide
999 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001000 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001001 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1002
1003 /**
1004 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001005 *
1006 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1007 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1008 *
1009 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1010 * independent of the others. The chains can be enabled and disabled independently, and apps can
1011 * be added and removed from each chain independently.
1012 *
1013 * @see #FIREWALL_CHAIN_OEM_DENY_1
1014 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001015 * @hide
1016 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001017 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001018 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1019
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001020 /**
1021 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001022 *
1023 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1024 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1025 *
1026 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1027 * independent of the others. The chains can be enabled and disabled independently, and apps can
1028 * be added and removed from each chain independently.
1029 *
1030 * @see #FIREWALL_CHAIN_OEM_DENY_1
1031 * @see #FIREWALL_CHAIN_OEM_DENY_2
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001032 * @hide
1033 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001034 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001035 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1036
markchiene1561fa2021-12-09 22:00:56 +08001037 /** @hide */
1038 @Retention(RetentionPolicy.SOURCE)
1039 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1040 FIREWALL_CHAIN_DOZABLE,
1041 FIREWALL_CHAIN_STANDBY,
1042 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001043 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001044 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Motomu Utsumid9801492022-06-01 13:57:27 +00001045 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001046 FIREWALL_CHAIN_OEM_DENY_2,
1047 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001048 })
1049 public @interface FirewallChain {}
Robert Horvathd945bf02022-01-27 19:55:16 +01001050 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
markchiene1561fa2021-12-09 22:00:56 +08001051
1052 /**
markchien011a7f52022-03-29 01:07:22 +08001053 * A firewall rule which allows or drops packets depending on existing policy.
1054 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1055 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001056 * @hide
1057 */
1058 @SystemApi(client = MODULE_LIBRARIES)
1059 public static final int FIREWALL_RULE_DEFAULT = 0;
1060
1061 /**
markchien011a7f52022-03-29 01:07:22 +08001062 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1063 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001064 * @hide
1065 */
1066 @SystemApi(client = MODULE_LIBRARIES)
1067 public static final int FIREWALL_RULE_ALLOW = 1;
1068
1069 /**
markchien011a7f52022-03-29 01:07:22 +08001070 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1071 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001072 * @hide
1073 */
1074 @SystemApi(client = MODULE_LIBRARIES)
1075 public static final int FIREWALL_RULE_DENY = 2;
1076
1077 /** @hide */
1078 @Retention(RetentionPolicy.SOURCE)
1079 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1080 FIREWALL_RULE_DEFAULT,
1081 FIREWALL_RULE_ALLOW,
1082 FIREWALL_RULE_DENY
1083 })
1084 public @interface FirewallRule {}
1085
1086 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001087 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1088 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1089 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1090 * methods that take a Context argument.
1091 */
1092 private static ConnectivityManager sInstance;
1093
1094 private final Context mContext;
1095
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001096 @GuardedBy("mTetheringEventCallbacks")
1097 private TetheringManager mTetheringManager;
1098
1099 private TetheringManager getTetheringManager() {
1100 synchronized (mTetheringEventCallbacks) {
1101 if (mTetheringManager == null) {
1102 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1103 }
1104 return mTetheringManager;
1105 }
1106 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001107
1108 /**
1109 * Tests if a given integer represents a valid network type.
1110 * @param networkType the type to be tested
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001111 * @return {@code true} if the type is valid, else {@code false}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001112 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1113 * validate a network type.
1114 */
1115 @Deprecated
1116 public static boolean isNetworkTypeValid(int networkType) {
1117 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1118 }
1119
1120 /**
1121 * Returns a non-localized string representing a given network type.
1122 * ONLY used for debugging output.
1123 * @param type the type needing naming
1124 * @return a String for the given type, or a string version of the type ("87")
1125 * if no name is known.
1126 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1127 * {@hide}
1128 */
1129 @Deprecated
1130 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1131 public static String getNetworkTypeName(int type) {
1132 switch (type) {
1133 case TYPE_NONE:
1134 return "NONE";
1135 case TYPE_MOBILE:
1136 return "MOBILE";
1137 case TYPE_WIFI:
1138 return "WIFI";
1139 case TYPE_MOBILE_MMS:
1140 return "MOBILE_MMS";
1141 case TYPE_MOBILE_SUPL:
1142 return "MOBILE_SUPL";
1143 case TYPE_MOBILE_DUN:
1144 return "MOBILE_DUN";
1145 case TYPE_MOBILE_HIPRI:
1146 return "MOBILE_HIPRI";
1147 case TYPE_WIMAX:
1148 return "WIMAX";
1149 case TYPE_BLUETOOTH:
1150 return "BLUETOOTH";
1151 case TYPE_DUMMY:
1152 return "DUMMY";
1153 case TYPE_ETHERNET:
1154 return "ETHERNET";
1155 case TYPE_MOBILE_FOTA:
1156 return "MOBILE_FOTA";
1157 case TYPE_MOBILE_IMS:
1158 return "MOBILE_IMS";
1159 case TYPE_MOBILE_CBS:
1160 return "MOBILE_CBS";
1161 case TYPE_WIFI_P2P:
1162 return "WIFI_P2P";
1163 case TYPE_MOBILE_IA:
1164 return "MOBILE_IA";
1165 case TYPE_MOBILE_EMERGENCY:
1166 return "MOBILE_EMERGENCY";
1167 case TYPE_PROXY:
1168 return "PROXY";
1169 case TYPE_VPN:
1170 return "VPN";
Junyu Laic9f1ca62022-07-25 16:31:59 +08001171 case TYPE_TEST:
1172 return "TEST";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001173 default:
1174 return Integer.toString(type);
1175 }
1176 }
1177
1178 /**
1179 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001180 */
lucaslin10774b72021-03-17 14:16:01 +08001181 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001182 public void systemReady() {
1183 try {
1184 mService.systemReady();
1185 } catch (RemoteException e) {
1186 throw e.rethrowFromSystemServer();
1187 }
1188 }
1189
1190 /**
1191 * Checks if a given type uses the cellular data connection.
1192 * This should be replaced in the future by a network property.
1193 * @param networkType the type to check
1194 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1195 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1196 * {@hide}
1197 */
1198 @Deprecated
1199 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1200 public static boolean isNetworkTypeMobile(int networkType) {
1201 switch (networkType) {
1202 case TYPE_MOBILE:
1203 case TYPE_MOBILE_MMS:
1204 case TYPE_MOBILE_SUPL:
1205 case TYPE_MOBILE_DUN:
1206 case TYPE_MOBILE_HIPRI:
1207 case TYPE_MOBILE_FOTA:
1208 case TYPE_MOBILE_IMS:
1209 case TYPE_MOBILE_CBS:
1210 case TYPE_MOBILE_IA:
1211 case TYPE_MOBILE_EMERGENCY:
1212 return true;
1213 default:
1214 return false;
1215 }
1216 }
1217
1218 /**
1219 * Checks if the given network type is backed by a Wi-Fi radio.
1220 *
1221 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1222 * @hide
1223 */
1224 @Deprecated
1225 public static boolean isNetworkTypeWifi(int networkType) {
1226 switch (networkType) {
1227 case TYPE_WIFI:
1228 case TYPE_WIFI_P2P:
1229 return true;
1230 default:
1231 return false;
1232 }
1233 }
1234
1235 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001236 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001237 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Junyu Lai35665cc2022-12-19 17:37:48 +08001238 * Specify that the traffic for this user should by follow the default rules:
1239 * applications in the profile designated by the UserHandle behave like any
1240 * other application and use the system default network as their default
1241 * network. Compare other PROFILE_NETWORK_PREFERENCE_* settings.
Chalard Jeanad565e22021-02-25 17:23:40 +09001242 * @hide
1243 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001244 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001245 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1246
1247 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001248 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001249 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001250 * Specify that the traffic for this user should by default go on a network with
1251 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1252 * if no such network is available.
1253 * @hide
1254 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001255 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001256 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1257
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001258 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001259 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001260 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001261 * Specify that the traffic for this user should by default go on a network with
1262 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
Junyu Lai35665cc2022-12-19 17:37:48 +08001263 * should not have a default network at all (that is, network accesses that
1264 * do not specify a network explicitly terminate with an error), even if there
1265 * is a system default network available to apps outside this preference.
1266 * The apps can still use a non-enterprise network if they request it explicitly
1267 * provided that specific network doesn't require any specific permission they
1268 * do not hold.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001269 * @hide
1270 */
1271 @SystemApi(client = MODULE_LIBRARIES)
1272 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1273
Junyu Lai35665cc2022-12-19 17:37:48 +08001274 /**
1275 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
1276 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1277 * Specify that the traffic for this user should by default go on a network with
1278 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}.
1279 * If there is no such network, the apps will have no default
1280 * network at all, even if there are available non-enterprise networks on the
1281 * device (that is, network accesses that do not specify a network explicitly
1282 * terminate with an error). Additionally, the designated apps should be
1283 * blocked from using any non-enterprise network even if they specify it
1284 * explicitly, unless they hold specific privilege overriding this (see
1285 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS}).
1286 * @hide
1287 */
1288 @SystemApi(client = MODULE_LIBRARIES)
1289 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING = 3;
1290
Chalard Jeanad565e22021-02-25 17:23:40 +09001291 /** @hide */
1292 @Retention(RetentionPolicy.SOURCE)
1293 @IntDef(value = {
1294 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001295 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1296 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001297 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001298 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001299 }
1300
1301 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001302 * Specifies the preferred network type. When the device has more
1303 * than one type available the preferred network type will be used.
1304 *
1305 * @param preference the network type to prefer over all others. It is
1306 * unspecified what happens to the old preferred network in the
1307 * overall ordering.
1308 * @deprecated Functionality has been removed as it no longer makes sense,
1309 * with many more than two networks - we'd need an array to express
1310 * preference. Instead we use dynamic network properties of
1311 * the networks to describe their precedence.
1312 */
1313 @Deprecated
1314 public void setNetworkPreference(int preference) {
1315 }
1316
1317 /**
1318 * Retrieves the current preferred network type.
1319 *
1320 * @return an integer representing the preferred network type
1321 *
1322 * @deprecated Functionality has been removed as it no longer makes sense,
1323 * with many more than two networks - we'd need an array to express
1324 * preference. Instead we use dynamic network properties of
1325 * the networks to describe their precedence.
1326 */
1327 @Deprecated
1328 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1329 public int getNetworkPreference() {
1330 return TYPE_NONE;
1331 }
1332
1333 /**
1334 * Returns details about the currently active default data network. When
1335 * connected, this network is the default route for outgoing connections.
1336 * You should always check {@link NetworkInfo#isConnected()} before initiating
1337 * network traffic. This may return {@code null} when there is no default
1338 * network.
1339 * Note that if the default network is a VPN, this method will return the
1340 * NetworkInfo for one of its underlying networks instead, or null if the
1341 * VPN agent did not specify any. Apps interested in learning about VPNs
1342 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1343 *
1344 * @return a {@link NetworkInfo} object for the current default network
1345 * or {@code null} if no default network is currently active
1346 * @deprecated See {@link NetworkInfo}.
1347 */
1348 @Deprecated
1349 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1350 @Nullable
1351 public NetworkInfo getActiveNetworkInfo() {
1352 try {
1353 return mService.getActiveNetworkInfo();
1354 } catch (RemoteException e) {
1355 throw e.rethrowFromSystemServer();
1356 }
1357 }
1358
1359 /**
1360 * Returns a {@link Network} object corresponding to the currently active
1361 * default data network. In the event that the current active default data
1362 * network disconnects, the returned {@code Network} object will no longer
1363 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001364 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001365 *
1366 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001367 * {@code null} if no default network is currently active or if
1368 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001369 */
1370 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1371 @Nullable
1372 public Network getActiveNetwork() {
1373 try {
1374 return mService.getActiveNetwork();
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 for a specific UID. In the event that the 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
1385 * network for the UID.
1386 *
1387 * @return a {@link Network} object for the current default network for the
1388 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001389 *
1390 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001391 */
1392 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1393 @Nullable
1394 public Network getActiveNetworkForUid(int uid) {
1395 return getActiveNetworkForUid(uid, false);
1396 }
1397
1398 /** {@hide} */
1399 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1400 try {
1401 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1402 } catch (RemoteException e) {
1403 throw e.rethrowFromSystemServer();
1404 }
1405 }
1406
lucaslin3ba7cc22022-12-19 02:35:33 +00001407 private static UidRange[] getUidRangeArray(@NonNull Collection<Range<Integer>> ranges) {
1408 Objects.requireNonNull(ranges);
1409 final UidRange[] rangesArray = new UidRange[ranges.size()];
1410 int index = 0;
1411 for (Range<Integer> range : ranges) {
1412 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1413 }
1414
1415 return rangesArray;
1416 }
1417
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001418 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001419 * Adds or removes a requirement for given UID ranges to use the VPN.
1420 *
1421 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1422 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1423 * otherwise have permission to bypass the VPN (e.g., because they have the
1424 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1425 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1426 * set to {@code false}, a previously-added restriction is removed.
1427 * <p>
1428 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1429 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1430 * remove a previously-added range, the exact range must be removed as is.
1431 * <p>
1432 * The changes are applied asynchronously and may not have been applied by the time the method
1433 * returns. Apps will be notified about any changes that apply to them via
1434 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1435 * effect.
1436 * <p>
lucaslin3ba7cc22022-12-19 02:35:33 +00001437 * This method will block the specified UIDs from accessing non-VPN networks, but does not
1438 * affect what the UIDs get as their default network.
1439 * Compare {@link #setVpnDefaultForUids(String, Collection)}, which declares that the UIDs
1440 * should only have a VPN as their default network, but does not block them from accessing other
1441 * networks if they request them explicitly with the {@link Network} API.
1442 * <p>
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001443 * This method should be called only by the VPN code.
1444 *
1445 * @param ranges the UID ranges to restrict
1446 * @param requireVpn whether the specified UID ranges must use a VPN
1447 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001448 * @hide
1449 */
1450 @RequiresPermission(anyOf = {
1451 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001452 android.Manifest.permission.NETWORK_STACK,
1453 android.Manifest.permission.NETWORK_SETTINGS})
1454 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001455 public void setRequireVpnForUids(boolean requireVpn,
1456 @NonNull Collection<Range<Integer>> ranges) {
1457 Objects.requireNonNull(ranges);
1458 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1459 // This method is not necessarily expected to be used outside the system server, so
1460 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1461 // stack process, or by tests.
lucaslin3ba7cc22022-12-19 02:35:33 +00001462 final UidRange[] rangesArray = getUidRangeArray(ranges);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001463 try {
1464 mService.setRequireVpnForUids(requireVpn, rangesArray);
1465 } catch (RemoteException e) {
1466 throw e.rethrowFromSystemServer();
1467 }
1468 }
1469
1470 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001471 * Inform the system that this VPN session should manage the passed UIDs.
1472 *
1473 * A VPN with the specified session ID may call this method to inform the system that the UIDs
1474 * in the specified range are subject to a VPN.
1475 * When this is called, the system will only choose a VPN for the default network of the UIDs in
1476 * the specified ranges.
1477 *
1478 * This method declares that the UIDs in the range will only have a VPN for their default
1479 * network, but does not block the UIDs from accessing other networks (permissions allowing) by
1480 * explicitly requesting it with the {@link Network} API.
1481 * Compare {@link #setRequireVpnForUids(boolean, Collection)}, which does not affect what
1482 * network the UIDs get as default, but will block them from accessing non-VPN networks.
1483 *
1484 * @param session The VPN session which manages the passed UIDs.
1485 * @param ranges The uid ranges which will treat VPN as their only default network.
1486 *
1487 * @hide
1488 */
1489 @RequiresPermission(anyOf = {
1490 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1491 android.Manifest.permission.NETWORK_STACK,
1492 android.Manifest.permission.NETWORK_SETTINGS})
1493 @SystemApi(client = MODULE_LIBRARIES)
1494 public void setVpnDefaultForUids(@NonNull String session,
1495 @NonNull Collection<Range<Integer>> ranges) {
1496 Objects.requireNonNull(ranges);
1497 final UidRange[] rangesArray = getUidRangeArray(ranges);
1498 try {
1499 mService.setVpnNetworkPreference(session, rangesArray);
1500 } catch (RemoteException e) {
1501 throw e.rethrowFromSystemServer();
1502 }
1503 }
1504
1505 /**
chiachangwange0192a72023-02-06 13:25:01 +00001506 * Temporarily set automaticOnOff keeplaive TCP polling alarm timer to 1 second.
1507 *
1508 * TODO: Remove this when the TCP polling design is replaced with callback.
Jean Chalard17cbf062023-02-13 05:07:48 +00001509 * @param timeMs The time of expiry, with System.currentTimeMillis() base. The value should be
1510 * set no more than 5 minutes in the future.
chiachangwange0192a72023-02-06 13:25:01 +00001511 * @hide
1512 */
1513 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
1514 try {
1515 mService.setTestLowTcpPollingTimerForKeepalive(timeMs);
1516 } catch (RemoteException e) {
1517 throw e.rethrowFromSystemServer();
1518 }
1519 }
1520
1521 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001522 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1523 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1524 * but is still supported for backwards compatibility.
1525 * <p>
1526 * This type of VPN is assumed always to use the system default network, and must always declare
1527 * exactly one underlying network, which is the network that was the default when the VPN
1528 * connected.
1529 * <p>
1530 * Calling this method with {@code true} enables legacy behaviour, specifically:
1531 * <ul>
1532 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1533 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1534 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1535 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1536 * underlying the VPN.</li>
1537 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1538 * similarly replaced by the VPN network state.</li>
1539 * <li>Information on current network interfaces passed to NetworkStatsService will not
1540 * include any VPN interfaces.</li>
1541 * </ul>
1542 *
1543 * @param enabled whether legacy lockdown VPN is enabled or disabled
1544 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001545 * @hide
1546 */
1547 @RequiresPermission(anyOf = {
1548 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001549 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001550 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001551 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001552 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1553 try {
1554 mService.setLegacyLockdownVpnEnabled(enabled);
1555 } catch (RemoteException e) {
1556 throw e.rethrowFromSystemServer();
1557 }
1558 }
1559
1560 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001561 * Returns details about the currently active default data network for a given uid.
1562 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001563 *
1564 * @return a {@link NetworkInfo} object for the current default network
1565 * for the given uid or {@code null} if no default network is
1566 * available for the specified uid.
1567 *
1568 * {@hide}
1569 */
1570 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1571 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1572 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1573 return getActiveNetworkInfoForUid(uid, false);
1574 }
1575
1576 /** {@hide} */
1577 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1578 try {
1579 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1580 } catch (RemoteException e) {
1581 throw e.rethrowFromSystemServer();
1582 }
1583 }
1584
1585 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001586 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001587 *
1588 * @param networkType integer specifying which networkType in
1589 * which you're interested.
1590 * @return a {@link NetworkInfo} object for the requested
1591 * network type or {@code null} if the type is not
1592 * supported by the device. If {@code networkType} is
1593 * TYPE_VPN and a VPN is active for the calling app,
1594 * then this method will try to return one of the
1595 * underlying networks for the VPN or null if the
1596 * VPN agent didn't specify any.
1597 *
1598 * @deprecated This method does not support multiple connected networks
1599 * of the same type. Use {@link #getAllNetworks} and
1600 * {@link #getNetworkInfo(android.net.Network)} instead.
1601 */
1602 @Deprecated
1603 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1604 @Nullable
1605 public NetworkInfo getNetworkInfo(int networkType) {
1606 try {
1607 return mService.getNetworkInfo(networkType);
1608 } catch (RemoteException e) {
1609 throw e.rethrowFromSystemServer();
1610 }
1611 }
1612
1613 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001614 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001615 *
1616 * @param network {@link Network} specifying which network
1617 * in which you're interested.
1618 * @return a {@link NetworkInfo} object for the requested
1619 * network or {@code null} if the {@code Network}
1620 * is not valid.
1621 * @deprecated See {@link NetworkInfo}.
1622 */
1623 @Deprecated
1624 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1625 @Nullable
1626 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1627 return getNetworkInfoForUid(network, Process.myUid(), false);
1628 }
1629
1630 /** {@hide} */
1631 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1632 try {
1633 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1634 } catch (RemoteException e) {
1635 throw e.rethrowFromSystemServer();
1636 }
1637 }
1638
1639 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001640 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001641 *
1642 * @return an array of {@link NetworkInfo} objects. Check each
1643 * {@link NetworkInfo#getType} for which type each applies.
1644 *
1645 * @deprecated This method does not support multiple connected networks
1646 * of the same type. Use {@link #getAllNetworks} and
1647 * {@link #getNetworkInfo(android.net.Network)} instead.
1648 */
1649 @Deprecated
1650 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1651 @NonNull
1652 public NetworkInfo[] getAllNetworkInfo() {
1653 try {
1654 return mService.getAllNetworkInfo();
1655 } catch (RemoteException e) {
1656 throw e.rethrowFromSystemServer();
1657 }
1658 }
1659
1660 /**
junyulaib1211372021-03-03 12:09:05 +08001661 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1662 * connected.
1663 * @hide
1664 */
1665 @SystemApi(client = MODULE_LIBRARIES)
1666 @RequiresPermission(anyOf = {
1667 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1668 android.Manifest.permission.NETWORK_STACK,
1669 android.Manifest.permission.NETWORK_SETTINGS})
1670 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001671 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001672 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001673 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001674 } catch (RemoteException e) {
1675 throw e.rethrowFromSystemServer();
1676 }
1677 }
1678
1679 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001680 * Returns the {@link Network} object currently serving a given type, or
1681 * null if the given type is not connected.
1682 *
1683 * @hide
1684 * @deprecated This method does not support multiple connected networks
1685 * of the same type. Use {@link #getAllNetworks} and
1686 * {@link #getNetworkInfo(android.net.Network)} instead.
1687 */
1688 @Deprecated
1689 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1690 @UnsupportedAppUsage
1691 public Network getNetworkForType(int networkType) {
1692 try {
1693 return mService.getNetworkForType(networkType);
1694 } catch (RemoteException e) {
1695 throw e.rethrowFromSystemServer();
1696 }
1697 }
1698
1699 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001700 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001701 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001702 * @deprecated This method does not provide any notification of network state changes, forcing
1703 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1704 * Apps should use methods such as
1705 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1706 * Apps that desire to obtain information about networks that do not apply to them
1707 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1708 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001709 * @return an array of {@link Network} objects.
1710 */
1711 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1712 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001713 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001714 public Network[] getAllNetworks() {
1715 try {
1716 return mService.getAllNetworks();
1717 } catch (RemoteException e) {
1718 throw e.rethrowFromSystemServer();
1719 }
1720 }
1721
1722 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001723 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001724 * the Networks that applications run by the given user will use by default.
1725 * @hide
1726 */
1727 @UnsupportedAppUsage
1728 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1729 try {
1730 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001731 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001732 } catch (RemoteException e) {
1733 throw e.rethrowFromSystemServer();
1734 }
1735 }
1736
1737 /**
1738 * Returns the IP information for the current default network.
1739 *
1740 * @return a {@link LinkProperties} object describing the IP info
1741 * for the current default network, or {@code null} if there
1742 * is no current default network.
1743 *
1744 * {@hide}
1745 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1746 * value of {@link #getActiveNetwork()} instead. In particular,
1747 * this method will return non-null LinkProperties even if the
1748 * app is blocked by policy from using this network.
1749 */
1750 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1751 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1752 public LinkProperties getActiveLinkProperties() {
1753 try {
1754 return mService.getActiveLinkProperties();
1755 } catch (RemoteException e) {
1756 throw e.rethrowFromSystemServer();
1757 }
1758 }
1759
1760 /**
1761 * Returns the IP information for a given network type.
1762 *
1763 * @param networkType the network type of interest.
1764 * @return a {@link LinkProperties} object describing the IP info
1765 * for the given networkType, or {@code null} if there is
1766 * no current default network.
1767 *
1768 * {@hide}
1769 * @deprecated This method does not support multiple connected networks
1770 * of the same type. Use {@link #getAllNetworks},
1771 * {@link #getNetworkInfo(android.net.Network)}, and
1772 * {@link #getLinkProperties(android.net.Network)} instead.
1773 */
1774 @Deprecated
1775 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1776 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1777 public LinkProperties getLinkProperties(int networkType) {
1778 try {
1779 return mService.getLinkPropertiesForType(networkType);
1780 } catch (RemoteException e) {
1781 throw e.rethrowFromSystemServer();
1782 }
1783 }
1784
1785 /**
1786 * Get the {@link LinkProperties} for the given {@link Network}. This
1787 * will return {@code null} if the network is unknown.
1788 *
1789 * @param network The {@link Network} object identifying the network in question.
1790 * @return The {@link LinkProperties} for the network, or {@code null}.
1791 */
1792 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1793 @Nullable
1794 public LinkProperties getLinkProperties(@Nullable Network network) {
1795 try {
1796 return mService.getLinkProperties(network);
1797 } catch (RemoteException e) {
1798 throw e.rethrowFromSystemServer();
1799 }
1800 }
1801
1802 /**
lucaslinc582d502022-01-27 09:07:00 +08001803 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001804 *
lucaslinc582d502022-01-27 09:07:00 +08001805 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1806 * given package, considering its permissions.
1807 *
1808 * @param lp A {@link LinkProperties} which will be redacted.
1809 * @param uid The target uid.
1810 * @param packageName The name of the package, for appops logging.
1811 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1812 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1813 * @hide
1814 */
1815 @RequiresPermission(anyOf = {
1816 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1817 android.Manifest.permission.NETWORK_STACK,
1818 android.Manifest.permission.NETWORK_SETTINGS})
1819 @SystemApi(client = MODULE_LIBRARIES)
1820 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001821 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001822 @NonNull String packageName) {
1823 try {
lucaslind2b06132022-03-02 10:56:57 +08001824 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001825 lp, uid, packageName, getAttributionTag());
1826 } catch (RemoteException e) {
1827 throw e.rethrowFromSystemServer();
1828 }
1829 }
1830
1831 /**
1832 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1833 *
1834 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1835 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1836 * sensitive information. To retrieve this location sensitive information (subject to
1837 * the caller's location permissions), use a {@link NetworkCallback} with the
1838 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1839 *
1840 * This method returns {@code null} if the network is unknown or if the |network| argument
1841 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001842 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001843 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001844 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001845 */
1846 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1847 @Nullable
1848 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1849 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001850 return mService.getNetworkCapabilities(
1851 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001852 } catch (RemoteException e) {
1853 throw e.rethrowFromSystemServer();
1854 }
1855 }
1856
1857 /**
lucaslinc582d502022-01-27 09:07:00 +08001858 * Redact {@link NetworkCapabilities} for a given package.
1859 *
1860 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001861 * to the given package, considering its permissions. If the passed capabilities contain
1862 * location-sensitive information, they will be redacted to the correct degree for the location
1863 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1864 * that level of location. If the UID holds no location permission, the returned object will
1865 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001866 *
1867 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1868 * @param uid The target uid.
1869 * @param packageName The name of the package, for appops logging.
1870 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1871 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1872 * @hide
1873 */
1874 @RequiresPermission(anyOf = {
1875 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1876 android.Manifest.permission.NETWORK_STACK,
1877 android.Manifest.permission.NETWORK_SETTINGS})
1878 @SystemApi(client = MODULE_LIBRARIES)
1879 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001880 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001881 @NonNull NetworkCapabilities nc,
1882 int uid, @NonNull String packageName) {
1883 try {
lucaslind2b06132022-03-02 10:56:57 +08001884 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001885 getAttributionTag());
1886 } catch (RemoteException e) {
1887 throw e.rethrowFromSystemServer();
1888 }
1889 }
1890
1891 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001892 * Gets a URL that can be used for resolving whether a captive portal is present.
1893 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1894 * portal is present.
1895 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1896 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1897 *
1898 * The system network validation may be using different strategies to detect captive portals,
1899 * so this method does not necessarily return a URL used by the system. It only returns a URL
1900 * that may be relevant for other components trying to detect captive portals.
1901 *
1902 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001903 * @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 +09001904 * system.
1905 */
1906 @Deprecated
1907 @SystemApi
1908 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1909 public String getCaptivePortalServerUrl() {
1910 try {
1911 return mService.getCaptivePortalServerUrl();
1912 } catch (RemoteException e) {
1913 throw e.rethrowFromSystemServer();
1914 }
1915 }
1916
1917 /**
1918 * Tells the underlying networking system that the caller wants to
1919 * begin using the named feature. The interpretation of {@code feature}
1920 * is completely up to each networking implementation.
1921 *
1922 * <p>This method requires the caller to hold either the
1923 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1924 * or the ability to modify system settings as determined by
1925 * {@link android.provider.Settings.System#canWrite}.</p>
1926 *
1927 * @param networkType specifies which network the request pertains to
1928 * @param feature the name of the feature to be used
1929 * @return an integer value representing the outcome of the request.
1930 * The interpretation of this value is specific to each networking
1931 * implementation+feature combination, except that the value {@code -1}
1932 * always indicates failure.
1933 *
1934 * @deprecated Deprecated in favor of the cleaner
1935 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1936 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1937 * throw {@code UnsupportedOperationException} if called.
1938 * @removed
1939 */
1940 @Deprecated
1941 public int startUsingNetworkFeature(int networkType, String feature) {
1942 checkLegacyRoutingApiAccess();
1943 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1944 if (netCap == null) {
1945 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1946 feature);
1947 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1948 }
1949
1950 NetworkRequest request = null;
1951 synchronized (sLegacyRequests) {
1952 LegacyRequest l = sLegacyRequests.get(netCap);
1953 if (l != null) {
1954 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1955 renewRequestLocked(l);
1956 if (l.currentNetwork != null) {
1957 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1958 } else {
1959 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1960 }
1961 }
1962
1963 request = requestNetworkForFeatureLocked(netCap);
1964 }
1965 if (request != null) {
1966 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1967 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1968 } else {
1969 Log.d(TAG, " request Failed");
1970 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1971 }
1972 }
1973
1974 /**
1975 * Tells the underlying networking system that the caller is finished
1976 * using the named feature. The interpretation of {@code feature}
1977 * is completely up to each networking implementation.
1978 *
1979 * <p>This method requires the caller to hold either the
1980 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1981 * or the ability to modify system settings as determined by
1982 * {@link android.provider.Settings.System#canWrite}.</p>
1983 *
1984 * @param networkType specifies which network the request pertains to
1985 * @param feature the name of the feature that is no longer needed
1986 * @return an integer value representing the outcome of the request.
1987 * The interpretation of this value is specific to each networking
1988 * implementation+feature combination, except that the value {@code -1}
1989 * always indicates failure.
1990 *
1991 * @deprecated Deprecated in favor of the cleaner
1992 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1993 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1994 * throw {@code UnsupportedOperationException} if called.
1995 * @removed
1996 */
1997 @Deprecated
1998 public int stopUsingNetworkFeature(int networkType, String feature) {
1999 checkLegacyRoutingApiAccess();
2000 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
2001 if (netCap == null) {
2002 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
2003 feature);
2004 return -1;
2005 }
2006
2007 if (removeRequestForFeature(netCap)) {
2008 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
2009 }
2010 return 1;
2011 }
2012
2013 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2014 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
2015 if (networkType == TYPE_MOBILE) {
2016 switch (feature) {
2017 case "enableCBS":
2018 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
2019 case "enableDUN":
2020 case "enableDUNAlways":
2021 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
2022 case "enableFOTA":
2023 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
2024 case "enableHIPRI":
2025 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
2026 case "enableIMS":
2027 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
2028 case "enableMMS":
2029 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
2030 case "enableSUPL":
2031 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
2032 default:
2033 return null;
2034 }
2035 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
2036 return networkCapabilitiesForType(TYPE_WIFI_P2P);
2037 }
2038 return null;
2039 }
2040
2041 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
2042 if (netCap == null) return TYPE_NONE;
2043 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
2044 return TYPE_MOBILE_CBS;
2045 }
2046 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2047 return TYPE_MOBILE_IMS;
2048 }
2049 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
2050 return TYPE_MOBILE_FOTA;
2051 }
2052 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
2053 return TYPE_MOBILE_DUN;
2054 }
2055 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
2056 return TYPE_MOBILE_SUPL;
2057 }
2058 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2059 return TYPE_MOBILE_MMS;
2060 }
2061 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
2062 return TYPE_MOBILE_HIPRI;
2063 }
2064 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
2065 return TYPE_WIFI_P2P;
2066 }
2067 return TYPE_NONE;
2068 }
2069
2070 private static class LegacyRequest {
2071 NetworkCapabilities networkCapabilities;
2072 NetworkRequest networkRequest;
2073 int expireSequenceNumber;
2074 Network currentNetwork;
2075 int delay = -1;
2076
2077 private void clearDnsBinding() {
2078 if (currentNetwork != null) {
2079 currentNetwork = null;
2080 setProcessDefaultNetworkForHostResolution(null);
2081 }
2082 }
2083
2084 NetworkCallback networkCallback = new NetworkCallback() {
2085 @Override
2086 public void onAvailable(Network network) {
2087 currentNetwork = network;
2088 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
2089 setProcessDefaultNetworkForHostResolution(network);
2090 }
2091 @Override
2092 public void onLost(Network network) {
2093 if (network.equals(currentNetwork)) clearDnsBinding();
2094 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2095 }
2096 };
2097 }
2098
2099 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2100 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2101 new HashMap<>();
2102
2103 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2104 synchronized (sLegacyRequests) {
2105 LegacyRequest l = sLegacyRequests.get(netCap);
2106 if (l != null) return l.networkRequest;
2107 }
2108 return null;
2109 }
2110
2111 private void renewRequestLocked(LegacyRequest l) {
2112 l.expireSequenceNumber++;
2113 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2114 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2115 }
2116
2117 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2118 int ourSeqNum = -1;
2119 synchronized (sLegacyRequests) {
2120 LegacyRequest l = sLegacyRequests.get(netCap);
2121 if (l == null) return;
2122 ourSeqNum = l.expireSequenceNumber;
2123 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2124 }
2125 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2126 }
2127
2128 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2129 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2130 int delay = -1;
2131 int type = legacyTypeForNetworkCapabilities(netCap);
2132 try {
2133 delay = mService.getRestoreDefaultNetworkDelay(type);
2134 } catch (RemoteException e) {
2135 throw e.rethrowFromSystemServer();
2136 }
2137 LegacyRequest l = new LegacyRequest();
2138 l.networkCapabilities = netCap;
2139 l.delay = delay;
2140 l.expireSequenceNumber = 0;
2141 l.networkRequest = sendRequestForNetwork(
2142 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2143 if (l.networkRequest == null) return null;
2144 sLegacyRequests.put(netCap, l);
2145 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2146 return l.networkRequest;
2147 }
2148
2149 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2150 if (delay >= 0) {
2151 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2152 CallbackHandler handler = getDefaultHandler();
2153 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2154 handler.sendMessageDelayed(msg, delay);
2155 }
2156 }
2157
2158 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2159 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2160 final LegacyRequest l;
2161 synchronized (sLegacyRequests) {
2162 l = sLegacyRequests.remove(netCap);
2163 }
2164 if (l == null) return false;
2165 unregisterNetworkCallback(l.networkCallback);
2166 l.clearDnsBinding();
2167 return true;
2168 }
2169
2170 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2171 static {
2172 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2173 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2174 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2175 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2176 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2177 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2178 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2179 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2180 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2181 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2182 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2183 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2184 }
2185
2186 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2187 static {
2188 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2189 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2190 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2191 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2192 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2193 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2194 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2195 }
2196
2197 /**
2198 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2199 * instance suitable for registering a request or callback. Throws an
2200 * IllegalArgumentException if no mapping from the legacy type to
2201 * NetworkCapabilities is known.
2202 *
2203 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2204 * to find the network instead.
2205 * @hide
2206 */
2207 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2208 final NetworkCapabilities nc = new NetworkCapabilities();
2209
2210 // Map from type to transports.
2211 final int NOT_FOUND = -1;
2212 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002213 if (transport == NOT_FOUND) {
2214 throw new IllegalArgumentException("unknown legacy type: " + type);
2215 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002216 nc.addTransportType(transport);
2217
2218 // Map from type to capabilities.
2219 nc.addCapability(sLegacyTypeToCapability.get(
2220 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2221 nc.maybeMarkCapabilitiesRestricted();
2222 return nc;
2223 }
2224
2225 /** @hide */
2226 public static class PacketKeepaliveCallback {
2227 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2228 public PacketKeepaliveCallback() {
2229 }
2230 /** The requested keepalive was successfully started. */
2231 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2232 public void onStarted() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002233 /** The keepalive was resumed after being paused by the system. */
2234 public void onResumed() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002235 /** The keepalive was successfully stopped. */
2236 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2237 public void onStopped() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002238 /** The keepalive was paused automatically by the system. */
2239 public void onPaused() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002240 /** An error occurred. */
2241 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2242 public void onError(int error) {}
2243 }
2244
2245 /**
2246 * Allows applications to request that the system periodically send specific packets on their
2247 * behalf, using hardware offload to save battery power.
2248 *
2249 * To request that the system send keepalives, call one of the methods that return a
2250 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2251 * passing in a non-null callback. If the callback is successfully started, the callback's
2252 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2253 * specifying one of the {@code ERROR_*} constants in this class.
2254 *
2255 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2256 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2257 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2258 *
2259 * @deprecated Use {@link SocketKeepalive} instead.
2260 *
2261 * @hide
2262 */
2263 public class PacketKeepalive {
2264
2265 private static final String TAG = "PacketKeepalive";
2266
2267 /** @hide */
2268 public static final int SUCCESS = 0;
2269
2270 /** @hide */
2271 public static final int NO_KEEPALIVE = -1;
2272
2273 /** @hide */
2274 public static final int BINDER_DIED = -10;
2275
2276 /** The specified {@code Network} is not connected. */
2277 public static final int ERROR_INVALID_NETWORK = -20;
2278 /** The specified IP addresses are invalid. For example, the specified source IP address is
2279 * not configured on the specified {@code Network}. */
2280 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2281 /** The requested port is invalid. */
2282 public static final int ERROR_INVALID_PORT = -22;
2283 /** The packet length is invalid (e.g., too long). */
2284 public static final int ERROR_INVALID_LENGTH = -23;
2285 /** The packet transmission interval is invalid (e.g., too short). */
2286 public static final int ERROR_INVALID_INTERVAL = -24;
2287
2288 /** The hardware does not support this request. */
2289 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2290 /** The hardware returned an error. */
2291 public static final int ERROR_HARDWARE_ERROR = -31;
2292
2293 /** The NAT-T destination port for IPsec */
2294 public static final int NATT_PORT = 4500;
2295
2296 /** The minimum interval in seconds between keepalive packet transmissions */
2297 public static final int MIN_INTERVAL = 10;
2298
2299 private final Network mNetwork;
2300 private final ISocketKeepaliveCallback mCallback;
2301 private final ExecutorService mExecutor;
2302
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002303 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2304 public void stop() {
2305 try {
2306 mExecutor.execute(() -> {
2307 try {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002308 mService.stopKeepalive(mCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002309 } catch (RemoteException e) {
2310 Log.e(TAG, "Error stopping packet keepalive: ", e);
2311 throw e.rethrowFromSystemServer();
2312 }
2313 });
2314 } catch (RejectedExecutionException e) {
2315 // The internal executor has already stopped due to previous event.
2316 }
2317 }
2318
2319 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002320 Objects.requireNonNull(network, "network cannot be null");
2321 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002322 mNetwork = network;
2323 mExecutor = Executors.newSingleThreadExecutor();
2324 mCallback = new ISocketKeepaliveCallback.Stub() {
2325 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002326 public void onStarted() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002327 final long token = Binder.clearCallingIdentity();
2328 try {
2329 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002330 callback.onStarted();
2331 });
2332 } finally {
2333 Binder.restoreCallingIdentity(token);
2334 }
2335 }
2336
2337 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002338 public void onResumed() {
2339 final long token = Binder.clearCallingIdentity();
2340 try {
2341 mExecutor.execute(() -> {
2342 callback.onResumed();
2343 });
2344 } finally {
2345 Binder.restoreCallingIdentity(token);
2346 }
2347 }
2348
2349 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002350 public void onStopped() {
2351 final long token = Binder.clearCallingIdentity();
2352 try {
2353 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002354 callback.onStopped();
2355 });
2356 } finally {
2357 Binder.restoreCallingIdentity(token);
2358 }
2359 mExecutor.shutdown();
2360 }
2361
2362 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002363 public void onPaused() {
2364 final long token = Binder.clearCallingIdentity();
2365 try {
2366 mExecutor.execute(() -> {
2367 callback.onPaused();
2368 });
2369 } finally {
2370 Binder.restoreCallingIdentity(token);
2371 }
2372 mExecutor.shutdown();
2373 }
2374
2375 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002376 public void onError(int error) {
2377 final long token = Binder.clearCallingIdentity();
2378 try {
2379 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002380 callback.onError(error);
2381 });
2382 } finally {
2383 Binder.restoreCallingIdentity(token);
2384 }
2385 mExecutor.shutdown();
2386 }
2387
2388 @Override
2389 public void onDataReceived() {
2390 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2391 // this callback when data is received.
2392 }
2393 };
2394 }
2395 }
2396
2397 /**
2398 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2399 *
2400 * @deprecated Use {@link #createSocketKeepalive} instead.
2401 *
2402 * @hide
2403 */
2404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2405 public PacketKeepalive startNattKeepalive(
2406 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2407 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2408 final PacketKeepalive k = new PacketKeepalive(network, callback);
2409 try {
2410 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2411 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2412 } catch (RemoteException e) {
2413 Log.e(TAG, "Error starting packet keepalive: ", e);
2414 throw e.rethrowFromSystemServer();
2415 }
2416 return k;
2417 }
2418
2419 // Construct an invalid fd.
2420 private ParcelFileDescriptor createInvalidFd() {
2421 final int invalidFd = -1;
2422 return ParcelFileDescriptor.adoptFd(invalidFd);
2423 }
2424
2425 /**
2426 * Request that keepalives be started on a IPsec NAT-T socket.
2427 *
2428 * @param network The {@link Network} the socket is on.
2429 * @param socket The socket that needs to be kept alive.
2430 * @param source The source address of the {@link UdpEncapsulationSocket}.
2431 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2432 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2433 * must run callback sequentially, otherwise the order of callbacks cannot be
2434 * guaranteed.
2435 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2436 * changes. Must be extended by applications that use this API.
2437 *
2438 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2439 * given socket.
2440 **/
2441 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2442 @NonNull UdpEncapsulationSocket socket,
2443 @NonNull InetAddress source,
2444 @NonNull InetAddress destination,
2445 @NonNull @CallbackExecutor Executor executor,
2446 @NonNull Callback callback) {
2447 ParcelFileDescriptor dup;
2448 try {
2449 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2450 // which cannot be obtained by the app process.
2451 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2452 } catch (IOException ignored) {
2453 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2454 // ERROR_INVALID_SOCKET.
2455 dup = createInvalidFd();
2456 }
2457 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2458 destination, executor, callback);
2459 }
2460
2461 /**
2462 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2463 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2464 *
2465 * @param network The {@link Network} the socket is on.
2466 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2467 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2468 * from that port.
2469 * @param source The source address of the {@link UdpEncapsulationSocket}.
2470 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2471 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2472 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2473 * must run callback sequentially, otherwise the order of callbacks cannot be
2474 * guaranteed.
2475 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2476 * changes. Must be extended by applications that use this API.
2477 *
2478 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2479 * given socket.
2480 * @hide
2481 */
2482 @SystemApi
2483 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2484 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2485 @NonNull ParcelFileDescriptor pfd,
2486 @NonNull InetAddress source,
2487 @NonNull InetAddress destination,
2488 @NonNull @CallbackExecutor Executor executor,
2489 @NonNull Callback callback) {
2490 ParcelFileDescriptor dup;
2491 try {
2492 // TODO: Consider remove unnecessary dup.
2493 dup = pfd.dup();
2494 } catch (IOException ignored) {
2495 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2496 // ERROR_INVALID_SOCKET.
2497 dup = createInvalidFd();
2498 }
2499 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002500 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002501 }
2502
2503 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002504 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002505 *
2506 * @param network The {@link Network} the socket is on.
2507 * @param socket The socket that needs to be kept alive.
2508 * @param executor The executor on which callback will be invoked. This implementation assumes
2509 * the provided {@link Executor} runs the callbacks in sequence with no
2510 * concurrency. Failing this, no guarantee of correctness can be made. It is
2511 * the responsibility of the caller to ensure the executor provides this
2512 * guarantee. A simple way of creating such an executor is with the standard
2513 * tool {@code Executors.newSingleThreadExecutor}.
2514 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2515 * changes. Must be extended by applications that use this API.
2516 *
2517 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2518 * given socket.
2519 * @hide
2520 */
2521 @SystemApi
2522 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2523 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2524 @NonNull Socket socket,
Sherri Lin443b7182023-02-08 04:49:29 +01002525 @NonNull @CallbackExecutor Executor executor,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002526 @NonNull Callback callback) {
2527 ParcelFileDescriptor dup;
2528 try {
2529 dup = ParcelFileDescriptor.fromSocket(socket);
2530 } catch (UncheckedIOException ignored) {
2531 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2532 // ERROR_INVALID_SOCKET.
2533 dup = createInvalidFd();
2534 }
2535 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2536 }
2537
2538 /**
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +09002539 * Get the supported keepalive count for each transport configured in resource overlays.
2540 *
2541 * @return An array of supported keepalive count for each transport type.
2542 * @hide
2543 */
2544 @RequiresPermission(anyOf = { android.Manifest.permission.NETWORK_SETTINGS,
2545 // CTS 13 used QUERY_ALL_PACKAGES to get the resource value, which was implemented
2546 // as below in KeepaliveUtils. Also allow that permission so that KeepaliveUtils can
2547 // use this method and avoid breaking released CTS. Apps that have this permission
2548 // can query the resource themselves anyway.
2549 android.Manifest.permission.QUERY_ALL_PACKAGES })
2550 public int[] getSupportedKeepalives() {
2551 try {
2552 return mService.getSupportedKeepalives();
2553 } catch (RemoteException e) {
2554 throw e.rethrowFromSystemServer();
2555 }
2556 }
2557
2558 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002559 * Ensure that a network route exists to deliver traffic to the specified
2560 * host via the specified network interface. An attempt to add a route that
2561 * already exists is ignored, but treated as successful.
2562 *
2563 * <p>This method requires the caller to hold either the
2564 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2565 * or the ability to modify system settings as determined by
2566 * {@link android.provider.Settings.System#canWrite}.</p>
2567 *
2568 * @param networkType the type of the network over which traffic to the specified
2569 * host is to be routed
2570 * @param hostAddress the IP address of the host to which the route is desired
2571 * @return {@code true} on success, {@code false} on failure
2572 *
2573 * @deprecated Deprecated in favor of the
2574 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2575 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2576 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2577 * throw {@code UnsupportedOperationException} if called.
2578 * @removed
2579 */
2580 @Deprecated
2581 public boolean requestRouteToHost(int networkType, int hostAddress) {
2582 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2583 }
2584
2585 /**
2586 * Ensure that a network route exists to deliver traffic to the specified
2587 * host via the specified network interface. An attempt to add a route that
2588 * already exists is ignored, but treated as successful.
2589 *
2590 * <p>This method requires the caller to hold either the
2591 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2592 * or the ability to modify system settings as determined by
2593 * {@link android.provider.Settings.System#canWrite}.</p>
2594 *
2595 * @param networkType the type of the network over which traffic to the specified
2596 * host is to be routed
2597 * @param hostAddress the IP address of the host to which the route is desired
2598 * @return {@code true} on success, {@code false} on failure
2599 * @hide
2600 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2601 * {@link #bindProcessToNetwork} API.
2602 */
2603 @Deprecated
2604 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002605 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002606 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2607 checkLegacyRoutingApiAccess();
2608 try {
2609 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2610 mContext.getOpPackageName(), getAttributionTag());
2611 } catch (RemoteException e) {
2612 throw e.rethrowFromSystemServer();
2613 }
2614 }
2615
2616 /**
2617 * @return the context's attribution tag
2618 */
2619 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2620 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002621 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002622 }
2623
2624 /**
2625 * Returns the value of the setting for background data usage. If false,
2626 * applications should not use the network if the application is not in the
2627 * foreground. Developers should respect this setting, and check the value
2628 * of this before performing any background data operations.
2629 * <p>
2630 * All applications that have background services that use the network
2631 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2632 * <p>
2633 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2634 * background data depends on several combined factors, and this method will
2635 * always return {@code true}. Instead, when background data is unavailable,
2636 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2637 *
2638 * @return Whether background data usage is allowed.
2639 */
2640 @Deprecated
2641 public boolean getBackgroundDataSetting() {
2642 // assume that background data is allowed; final authority is
2643 // NetworkInfo which may be blocked.
2644 return true;
2645 }
2646
2647 /**
2648 * Sets the value of the setting for background data usage.
2649 *
2650 * @param allowBackgroundData Whether an application should use data while
2651 * it is in the background.
2652 *
2653 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2654 * @see #getBackgroundDataSetting()
2655 * @hide
2656 */
2657 @Deprecated
2658 @UnsupportedAppUsage
2659 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2660 // ignored
2661 }
2662
2663 /**
2664 * @hide
2665 * @deprecated Talk to TelephonyManager directly
2666 */
2667 @Deprecated
2668 @UnsupportedAppUsage
2669 public boolean getMobileDataEnabled() {
2670 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2671 if (tm != null) {
2672 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2673 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2674 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2675 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2676 + " retVal=" + retVal);
2677 return retVal;
2678 }
2679 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2680 return false;
2681 }
2682
2683 /**
2684 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2685 * to find out when the system default network has gone in to a high power state.
2686 */
2687 public interface OnNetworkActiveListener {
2688 /**
2689 * Called on the main thread of the process to report that the current data network
2690 * has become active, and it is now a good time to perform any pending network
2691 * operations. Note that this listener only tells you when the network becomes
2692 * active; if at any other time you want to know whether it is active (and thus okay
2693 * to initiate network traffic), you can retrieve its instantaneous state with
2694 * {@link ConnectivityManager#isDefaultNetworkActive}.
2695 */
2696 void onNetworkActive();
2697 }
2698
Chiachang Wang2de41682021-09-23 10:46:03 +08002699 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002700 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2701 mNetworkActivityListeners = new ArrayMap<>();
2702
2703 /**
2704 * Start listening to reports when the system's default data network is active, meaning it is
2705 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2706 * to determine the current state of the system's default network after registering the
2707 * listener.
2708 * <p>
2709 * If the process default network has been set with
2710 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2711 * reflect the process's default, but the system default.
2712 *
2713 * @param l The listener to be told when the network is active.
2714 */
2715 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002716 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002717 @Override
2718 public void onNetworkActive() throws RemoteException {
2719 l.onNetworkActive();
2720 }
2721 };
2722
Chiachang Wang2de41682021-09-23 10:46:03 +08002723 synchronized (mNetworkActivityListeners) {
2724 try {
2725 mService.registerNetworkActivityListener(rl);
2726 mNetworkActivityListeners.put(l, rl);
2727 } catch (RemoteException e) {
2728 throw e.rethrowFromSystemServer();
2729 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002730 }
2731 }
2732
2733 /**
2734 * Remove network active listener previously registered with
2735 * {@link #addDefaultNetworkActiveListener}.
2736 *
2737 * @param l Previously registered listener.
2738 */
2739 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002740 synchronized (mNetworkActivityListeners) {
2741 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2742 if (rl == null) {
2743 throw new IllegalArgumentException("Listener was not registered.");
2744 }
2745 try {
2746 mService.unregisterNetworkActivityListener(rl);
2747 mNetworkActivityListeners.remove(l);
2748 } catch (RemoteException e) {
2749 throw e.rethrowFromSystemServer();
2750 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002751 }
2752 }
2753
2754 /**
2755 * Return whether the data network is currently active. An active network means that
2756 * it is currently in a high power state for performing data transmission. On some
2757 * types of networks, it may be expensive to move and stay in such a state, so it is
2758 * more power efficient to batch network traffic together when the radio is already in
2759 * this state. This method tells you whether right now is currently a good time to
2760 * initiate network traffic, as the network is already active.
2761 */
2762 public boolean isDefaultNetworkActive() {
2763 try {
lucaslin709eb842021-01-21 02:04:15 +08002764 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002765 } catch (RemoteException e) {
2766 throw e.rethrowFromSystemServer();
2767 }
2768 }
2769
2770 /**
2771 * {@hide}
2772 */
2773 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002774 this(context, service, true /* newStatic */);
2775 }
2776
2777 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002778 mContext = Objects.requireNonNull(context, "missing context");
2779 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002780 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2781 // different ConnectivityManager, but that's still OK considering its usage.
2782 if (sInstance == null && newStatic) {
2783 final Context appContext = mContext.getApplicationContext();
2784 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2785 // If the application context is null, we're either in the system process or
2786 // it's the application context very early in app initialization. In both these
2787 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2788 // service. http://b/27532714 .
2789 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2790 false /* newStatic */);
2791 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002792 }
2793
2794 /** {@hide} */
2795 @UnsupportedAppUsage
2796 public static ConnectivityManager from(Context context) {
2797 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2798 }
2799
2800 /** @hide */
2801 public NetworkRequest getDefaultRequest() {
2802 try {
2803 // This is not racy as the default request is final in ConnectivityService.
2804 return mService.getDefaultRequest();
2805 } catch (RemoteException e) {
2806 throw e.rethrowFromSystemServer();
2807 }
2808 }
2809
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002810 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002811 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002812 * happened.
2813 *
2814 * @return {@code true} iff the package is allowed to write settings.
2815 */
2816 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2817 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2818 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2819 boolean throwException) {
2820 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002821 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002822 }
2823
2824 /**
2825 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2826 * situations where a Context pointer is unavailable.
2827 * @hide
2828 */
2829 @Deprecated
2830 static ConnectivityManager getInstanceOrNull() {
2831 return sInstance;
2832 }
2833
2834 /**
2835 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2836 * situations where a Context pointer is unavailable.
2837 * @hide
2838 */
2839 @Deprecated
2840 @UnsupportedAppUsage
2841 private static ConnectivityManager getInstance() {
2842 if (getInstanceOrNull() == null) {
2843 throw new IllegalStateException("No ConnectivityManager yet constructed");
2844 }
2845 return getInstanceOrNull();
2846 }
2847
2848 /**
2849 * Get the set of tetherable, available interfaces. This list is limited by
2850 * device configuration and current interface existence.
2851 *
2852 * @return an array of 0 or more Strings of tetherable interface names.
2853 *
2854 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2855 * {@hide}
2856 */
2857 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2858 @UnsupportedAppUsage
2859 @Deprecated
2860 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002861 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002862 }
2863
2864 /**
2865 * Get the set of tethered interfaces.
2866 *
2867 * @return an array of 0 or more String of currently tethered interface names.
2868 *
2869 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2870 * {@hide}
2871 */
2872 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2873 @UnsupportedAppUsage
2874 @Deprecated
2875 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002876 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002877 }
2878
2879 /**
2880 * Get the set of interface names which attempted to tether but
2881 * failed. Re-attempting to tether may cause them to reset to the Tethered
2882 * state. Alternatively, causing the interface to be destroyed and recreated
2883 * may cause them to reset to the available state.
2884 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2885 * information on the cause of the errors.
2886 *
2887 * @return an array of 0 or more String indicating the interface names
2888 * which failed to tether.
2889 *
2890 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2891 * {@hide}
2892 */
2893 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2894 @UnsupportedAppUsage
2895 @Deprecated
2896 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002897 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002898 }
2899
2900 /**
2901 * Get the set of tethered dhcp ranges.
2902 *
2903 * @deprecated This method is not supported.
2904 * TODO: remove this function when all of clients are removed.
2905 * {@hide}
2906 */
2907 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2908 @Deprecated
2909 public String[] getTetheredDhcpRanges() {
2910 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2911 }
2912
2913 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002914 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002915 * on the interface, forward and NAT IP packets and forward DNS requests
2916 * to the best active upstream network interface. Note that if no upstream
2917 * IP network interface is available, dhcp will still run and traffic will be
2918 * allowed between the tethered devices and this device, though upstream net
2919 * access will of course fail until an upstream network interface becomes
2920 * active.
2921 *
2922 * <p>This method requires the caller to hold either the
2923 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2924 * or the ability to modify system settings as determined by
2925 * {@link android.provider.Settings.System#canWrite}.</p>
2926 *
2927 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2928 * and WifiStateMachine which need direct access. All other clients should use
2929 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2930 * logic.</p>
2931 *
2932 * @param iface the interface name to tether.
2933 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2934 * @deprecated Use {@link TetheringManager#startTethering} instead
2935 *
2936 * {@hide}
2937 */
2938 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2939 @Deprecated
2940 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002941 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002942 }
2943
2944 /**
2945 * Stop tethering the named interface.
2946 *
2947 * <p>This method requires the caller to hold either the
2948 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2949 * or the ability to modify system settings as determined by
2950 * {@link android.provider.Settings.System#canWrite}.</p>
2951 *
2952 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2953 * and WifiStateMachine which need direct access. All other clients should use
2954 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2955 * logic.</p>
2956 *
2957 * @param iface the interface name to untether.
2958 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2959 *
2960 * {@hide}
2961 */
2962 @UnsupportedAppUsage
2963 @Deprecated
2964 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002965 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002966 }
2967
2968 /**
2969 * Check if the device allows for tethering. It may be disabled via
2970 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2971 * due to device configuration.
2972 *
2973 * <p>If this app does not have permission to use this API, it will always
2974 * return false rather than throw an exception.</p>
2975 *
2976 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2977 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2978 *
2979 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2980 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2981 *
2982 * @return a boolean - {@code true} indicating Tethering is supported.
2983 *
2984 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2985 * {@hide}
2986 */
2987 @SystemApi
2988 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2989 android.Manifest.permission.WRITE_SETTINGS})
2990 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002991 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002992 }
2993
2994 /**
2995 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2996 *
2997 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2998 * @hide
2999 */
3000 @SystemApi
3001 @Deprecated
3002 public static abstract class OnStartTetheringCallback {
3003 /**
3004 * Called when tethering has been successfully started.
3005 */
3006 public void onTetheringStarted() {}
3007
3008 /**
3009 * Called when starting tethering failed.
3010 */
3011 public void onTetheringFailed() {}
3012 }
3013
3014 /**
3015 * Convenient overload for
3016 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
3017 * handler to run on the current thread's {@link Looper}.
3018 *
3019 * @deprecated Use {@link TetheringManager#startTethering} instead.
3020 * @hide
3021 */
3022 @SystemApi
3023 @Deprecated
3024 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3025 public void startTethering(int type, boolean showProvisioningUi,
3026 final OnStartTetheringCallback callback) {
3027 startTethering(type, showProvisioningUi, callback, null);
3028 }
3029
3030 /**
3031 * Runs tether provisioning for the given type if needed and then starts tethering if
3032 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
3033 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
3034 * schedules tether provisioning re-checks if appropriate.
3035 *
3036 * @param type The type of tethering to start. Must be one of
3037 * {@link ConnectivityManager.TETHERING_WIFI},
3038 * {@link ConnectivityManager.TETHERING_USB}, or
3039 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3040 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
3041 * is one. This should be true the first time this function is called and also any time
3042 * the user can see this UI. It gives users information from their carrier about the
3043 * check failing and how they can sign up for tethering if possible.
3044 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
3045 * of the result of trying to tether.
3046 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3047 *
3048 * @deprecated Use {@link TetheringManager#startTethering} instead.
3049 * @hide
3050 */
3051 @SystemApi
3052 @Deprecated
3053 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3054 public void startTethering(int type, boolean showProvisioningUi,
3055 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003056 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003057
3058 final Executor executor = new Executor() {
3059 @Override
3060 public void execute(Runnable command) {
3061 if (handler == null) {
3062 command.run();
3063 } else {
3064 handler.post(command);
3065 }
3066 }
3067 };
3068
3069 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
3070 @Override
3071 public void onTetheringStarted() {
3072 callback.onTetheringStarted();
3073 }
3074
3075 @Override
3076 public void onTetheringFailed(final int error) {
3077 callback.onTetheringFailed();
3078 }
3079 };
3080
3081 final TetheringRequest request = new TetheringRequest.Builder(type)
3082 .setShouldShowEntitlementUi(showProvisioningUi).build();
3083
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003084 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003085 }
3086
3087 /**
3088 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
3089 * applicable.
3090 *
3091 * @param type The type of tethering to stop. Must be one of
3092 * {@link ConnectivityManager.TETHERING_WIFI},
3093 * {@link ConnectivityManager.TETHERING_USB}, or
3094 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3095 *
3096 * @deprecated Use {@link TetheringManager#stopTethering} instead.
3097 * @hide
3098 */
3099 @SystemApi
3100 @Deprecated
3101 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3102 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003103 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003104 }
3105
3106 /**
3107 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
3108 * upstream status.
3109 *
3110 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
3111 * @hide
3112 */
3113 @SystemApi
3114 @Deprecated
3115 public abstract static class OnTetheringEventCallback {
3116
3117 /**
3118 * Called when tethering upstream changed. This can be called multiple times and can be
3119 * called any time.
3120 *
3121 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
3122 * have any upstream.
3123 */
3124 public void onUpstreamChanged(@Nullable Network network) {}
3125 }
3126
3127 @GuardedBy("mTetheringEventCallbacks")
3128 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
3129 mTetheringEventCallbacks = new ArrayMap<>();
3130
3131 /**
3132 * Start listening to tethering change events. Any new added callback will receive the last
3133 * tethering status right away. If callback is registered when tethering has no upstream or
3134 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3135 * with a null argument. The same callback object cannot be registered twice.
3136 *
3137 * @param executor the executor on which callback will be invoked.
3138 * @param callback the callback to be called when tethering has change events.
3139 *
3140 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3141 * @hide
3142 */
3143 @SystemApi
3144 @Deprecated
3145 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3146 public void registerTetheringEventCallback(
3147 @NonNull @CallbackExecutor Executor executor,
3148 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003149 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003150
3151 final TetheringEventCallback tetherCallback =
3152 new TetheringEventCallback() {
3153 @Override
3154 public void onUpstreamChanged(@Nullable Network network) {
3155 callback.onUpstreamChanged(network);
3156 }
3157 };
3158
3159 synchronized (mTetheringEventCallbacks) {
3160 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003161 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003162 }
3163 }
3164
3165 /**
3166 * Remove tethering event callback previously registered with
3167 * {@link #registerTetheringEventCallback}.
3168 *
3169 * @param callback previously registered callback.
3170 *
3171 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3172 * @hide
3173 */
3174 @SystemApi
3175 @Deprecated
3176 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3177 public void unregisterTetheringEventCallback(
3178 @NonNull final OnTetheringEventCallback callback) {
3179 Objects.requireNonNull(callback, "The callback must be non-null");
3180 synchronized (mTetheringEventCallbacks) {
3181 final TetheringEventCallback tetherCallback =
3182 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003183 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003184 }
3185 }
3186
3187
3188 /**
3189 * Get the list of regular expressions that define any tetherable
3190 * USB network interfaces. If USB tethering is not supported by the
3191 * device, this list should be empty.
3192 *
3193 * @return an array of 0 or more regular expression Strings defining
3194 * what interfaces are considered tetherable usb interfaces.
3195 *
3196 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3197 * {@hide}
3198 */
3199 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3200 @UnsupportedAppUsage
3201 @Deprecated
3202 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003203 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003204 }
3205
3206 /**
3207 * Get the list of regular expressions that define any tetherable
3208 * Wifi network interfaces. If Wifi tethering is not supported by the
3209 * device, this list should be empty.
3210 *
3211 * @return an array of 0 or more regular expression Strings defining
3212 * what interfaces are considered tetherable wifi interfaces.
3213 *
3214 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3215 * {@hide}
3216 */
3217 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3218 @UnsupportedAppUsage
3219 @Deprecated
3220 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003221 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003222 }
3223
3224 /**
3225 * Get the list of regular expressions that define any tetherable
3226 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3227 * device, this list should be empty.
3228 *
3229 * @return an array of 0 or more regular expression Strings defining
3230 * what interfaces are considered tetherable bluetooth interfaces.
3231 *
3232 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3233 *TetheringManager.TetheringInterfaceRegexps)} instead.
3234 * {@hide}
3235 */
3236 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3237 @UnsupportedAppUsage
3238 @Deprecated
3239 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003240 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003241 }
3242
3243 /**
3244 * Attempt to both alter the mode of USB and Tethering of USB. A
3245 * utility method to deal with some of the complexity of USB - will
3246 * attempt to switch to Rndis and subsequently tether the resulting
3247 * interface on {@code true} or turn off tethering and switch off
3248 * Rndis on {@code false}.
3249 *
3250 * <p>This method requires the caller to hold either the
3251 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3252 * or the ability to modify system settings as determined by
3253 * {@link android.provider.Settings.System#canWrite}.</p>
3254 *
3255 * @param enable a boolean - {@code true} to enable tethering
3256 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3257 * @deprecated Use {@link TetheringManager#startTethering} instead
3258 *
3259 * {@hide}
3260 */
3261 @UnsupportedAppUsage
3262 @Deprecated
3263 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003264 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003265 }
3266
3267 /**
3268 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3269 * {@hide}
3270 */
3271 @SystemApi
3272 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003273 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003274 /**
3275 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3276 * {@hide}
3277 */
3278 @Deprecated
3279 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3280 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3281 /**
3282 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3283 * {@hide}
3284 */
3285 @Deprecated
3286 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3287 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3288 /**
3289 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3290 * {@hide}
3291 */
3292 @Deprecated
3293 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3294 /**
3295 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3296 * {@hide}
3297 */
3298 @Deprecated
3299 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3300 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3301 /**
3302 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3303 * {@hide}
3304 */
3305 @Deprecated
3306 public static final int TETHER_ERROR_MASTER_ERROR =
3307 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3308 /**
3309 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3310 * {@hide}
3311 */
3312 @Deprecated
3313 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3314 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3315 /**
3316 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3317 * {@hide}
3318 */
3319 @Deprecated
3320 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3321 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3322 /**
3323 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3324 * {@hide}
3325 */
3326 @Deprecated
3327 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3328 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3329 /**
3330 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3331 * {@hide}
3332 */
3333 @Deprecated
3334 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3335 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3336 /**
3337 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3338 * {@hide}
3339 */
3340 @Deprecated
3341 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3342 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3343 /**
3344 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3345 * {@hide}
3346 */
3347 @SystemApi
3348 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003349 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003350 /**
3351 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3352 * {@hide}
3353 */
3354 @Deprecated
3355 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3356 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3357 /**
3358 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3359 * {@hide}
3360 */
3361 @SystemApi
3362 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003363 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003364
3365 /**
3366 * Get a more detailed error code after a Tethering or Untethering
3367 * request asynchronously failed.
3368 *
3369 * @param iface The name of the interface of interest
3370 * @return error The error code of the last error tethering or untethering the named
3371 * interface
3372 *
3373 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3374 * {@hide}
3375 */
3376 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3377 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3378 @Deprecated
3379 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003380 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003381 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3382 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3383 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3384 // instead.
3385 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3386 }
3387 return error;
3388 }
3389
3390 /** @hide */
3391 @Retention(RetentionPolicy.SOURCE)
3392 @IntDef(value = {
3393 TETHER_ERROR_NO_ERROR,
3394 TETHER_ERROR_PROVISION_FAILED,
3395 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3396 })
3397 public @interface EntitlementResultCode {
3398 }
3399
3400 /**
3401 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3402 * entitlement succeeded.
3403 *
3404 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3405 * @hide
3406 */
3407 @SystemApi
3408 @Deprecated
3409 public interface OnTetheringEntitlementResultListener {
3410 /**
3411 * Called to notify entitlement result.
3412 *
3413 * @param resultCode an int value of entitlement result. It may be one of
3414 * {@link #TETHER_ERROR_NO_ERROR},
3415 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3416 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3417 */
3418 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3419 }
3420
3421 /**
3422 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003423 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3424 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003425 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003426 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003427 * any reason will update the cached value.
3428 *
3429 * @param type the downstream type of tethering. Must be one of
3430 * {@link #TETHERING_WIFI},
3431 * {@link #TETHERING_USB}, or
3432 * {@link #TETHERING_BLUETOOTH}.
3433 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3434 * @param executor the executor on which callback will be invoked.
3435 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3436 * notify the caller of the result of entitlement check. The listener may be called zero
3437 * or one time.
3438 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3439 * {@hide}
3440 */
3441 @SystemApi
3442 @Deprecated
3443 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3444 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3445 @NonNull @CallbackExecutor Executor executor,
3446 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003447 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003448 ResultReceiver wrappedListener = new ResultReceiver(null) {
3449 @Override
3450 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003451 final long token = Binder.clearCallingIdentity();
3452 try {
3453 executor.execute(() -> {
3454 listener.onTetheringEntitlementResult(resultCode);
3455 });
3456 } finally {
3457 Binder.restoreCallingIdentity(token);
3458 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003459 }
3460 };
3461
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003462 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003463 showEntitlementUi);
3464 }
3465
3466 /**
3467 * Report network connectivity status. This is currently used only
3468 * to alter status bar UI.
3469 * <p>This method requires the caller to hold the permission
3470 * {@link android.Manifest.permission#STATUS_BAR}.
3471 *
3472 * @param networkType The type of network you want to report on
3473 * @param percentage The quality of the connection 0 is bad, 100 is good
3474 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3475 * {@hide}
3476 */
3477 public void reportInetCondition(int networkType, int percentage) {
3478 printStackTrace();
3479 try {
3480 mService.reportInetCondition(networkType, percentage);
3481 } catch (RemoteException e) {
3482 throw e.rethrowFromSystemServer();
3483 }
3484 }
3485
3486 /**
3487 * Report a problem network to the framework. This provides a hint to the system
3488 * that there might be connectivity problems on this network and may cause
3489 * the framework to re-evaluate network connectivity and/or switch to another
3490 * network.
3491 *
3492 * @param network The {@link Network} the application was attempting to use
3493 * or {@code null} to indicate the current default network.
3494 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3495 * working and non-working connectivity.
3496 */
3497 @Deprecated
3498 public void reportBadNetwork(@Nullable Network network) {
3499 printStackTrace();
3500 try {
3501 // One of these will be ignored because it matches system's current state.
3502 // The other will trigger the necessary reevaluation.
3503 mService.reportNetworkConnectivity(network, true);
3504 mService.reportNetworkConnectivity(network, false);
3505 } catch (RemoteException e) {
3506 throw e.rethrowFromSystemServer();
3507 }
3508 }
3509
3510 /**
3511 * Report to the framework whether a network has working connectivity.
3512 * This provides a hint to the system that a particular network is providing
3513 * working connectivity or not. In response the framework may re-evaluate
3514 * the network's connectivity and might take further action thereafter.
3515 *
3516 * @param network The {@link Network} the application was attempting to use
3517 * or {@code null} to indicate the current default network.
3518 * @param hasConnectivity {@code true} if the application was able to successfully access the
3519 * Internet using {@code network} or {@code false} if not.
3520 */
3521 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3522 printStackTrace();
3523 try {
3524 mService.reportNetworkConnectivity(network, hasConnectivity);
3525 } catch (RemoteException e) {
3526 throw e.rethrowFromSystemServer();
3527 }
3528 }
3529
3530 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003531 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003532 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003533 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3534 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3535 * accessing any network, regardless of what the settings for that network are.
3536 *
3537 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3538 * proxy is likely to break networking on multiple networks. This method is only meant
3539 * for device policy clients looking to do general internal filtering or similar use cases.
3540 *
chiachangwang9473c592022-07-15 02:25:52 +00003541 * @see #getGlobalProxy
3542 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003543 *
3544 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3545 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003546 * @hide
3547 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003548 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003549 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003550 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003551 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003552 try {
3553 mService.setGlobalProxy(p);
3554 } catch (RemoteException e) {
3555 throw e.rethrowFromSystemServer();
3556 }
3557 }
3558
3559 /**
3560 * Retrieve any network-independent global HTTP proxy.
3561 *
3562 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3563 * if no global HTTP proxy is set.
3564 * @hide
3565 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003566 @SystemApi(client = MODULE_LIBRARIES)
3567 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003568 public ProxyInfo getGlobalProxy() {
3569 try {
3570 return mService.getGlobalProxy();
3571 } catch (RemoteException e) {
3572 throw e.rethrowFromSystemServer();
3573 }
3574 }
3575
3576 /**
3577 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3578 * network-specific HTTP proxy. If {@code network} is null, the
3579 * network-specific proxy returned is the proxy of the default active
3580 * network.
3581 *
3582 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3583 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3584 * or when {@code network} is {@code null},
3585 * the {@code ProxyInfo} for the default active network. Returns
3586 * {@code null} when no proxy applies or the caller doesn't have
3587 * permission to use {@code network}.
3588 * @hide
3589 */
3590 public ProxyInfo getProxyForNetwork(Network network) {
3591 try {
3592 return mService.getProxyForNetwork(network);
3593 } catch (RemoteException e) {
3594 throw e.rethrowFromSystemServer();
3595 }
3596 }
3597
3598 /**
3599 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3600 * otherwise if this process is bound to a {@link Network} using
3601 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3602 * the default network's proxy is returned.
3603 *
3604 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3605 * HTTP proxy is active.
3606 */
3607 @Nullable
3608 public ProxyInfo getDefaultProxy() {
3609 return getProxyForNetwork(getBoundNetworkForProcess());
3610 }
3611
3612 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003613 * Returns whether the hardware supports the given network type.
3614 *
3615 * This doesn't indicate there is coverage or such a network is available, just whether the
3616 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3617 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003618 *
3619 * @param networkType The network type we'd like to check
3620 * @return {@code true} if supported, else {@code false}
3621 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3622 * @hide
3623 */
3624 @Deprecated
3625 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3626 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3627 public boolean isNetworkSupported(int networkType) {
3628 try {
3629 return mService.isNetworkSupported(networkType);
3630 } catch (RemoteException e) {
3631 throw e.rethrowFromSystemServer();
3632 }
3633 }
3634
3635 /**
3636 * Returns if the currently active data network is metered. A network is
3637 * classified as metered when the user is sensitive to heavy data usage on
3638 * that connection due to monetary costs, data limitations or
3639 * battery/performance issues. You should check this before doing large
3640 * data transfers, and warn the user or delay the operation until another
3641 * network is available.
3642 *
3643 * @return {@code true} if large transfers should be avoided, otherwise
3644 * {@code false}.
3645 */
3646 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3647 public boolean isActiveNetworkMetered() {
3648 try {
3649 return mService.isActiveNetworkMetered();
3650 } catch (RemoteException e) {
3651 throw e.rethrowFromSystemServer();
3652 }
3653 }
3654
3655 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003656 * Set sign in error notification to visible or invisible
3657 *
3658 * @hide
3659 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3660 */
3661 @Deprecated
3662 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3663 String action) {
3664 try {
3665 mService.setProvisioningNotificationVisible(visible, networkType, action);
3666 } catch (RemoteException e) {
3667 throw e.rethrowFromSystemServer();
3668 }
3669 }
3670
3671 /**
3672 * Set the value for enabling/disabling airplane mode
3673 *
3674 * @param enable whether to enable airplane mode or not
3675 *
3676 * @hide
3677 */
3678 @RequiresPermission(anyOf = {
3679 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3680 android.Manifest.permission.NETWORK_SETTINGS,
3681 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3682 android.Manifest.permission.NETWORK_STACK})
3683 @SystemApi
3684 public void setAirplaneMode(boolean enable) {
3685 try {
3686 mService.setAirplaneMode(enable);
3687 } catch (RemoteException e) {
3688 throw e.rethrowFromSystemServer();
3689 }
3690 }
3691
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003692 /**
3693 * Registers the specified {@link NetworkProvider}.
3694 * Each listener must only be registered once. The listener can be unregistered with
3695 * {@link #unregisterNetworkProvider}.
3696 *
3697 * @param provider the provider to register
3698 * @return the ID of the provider. This ID must be used by the provider when registering
3699 * {@link android.net.NetworkAgent}s.
3700 * @hide
3701 */
3702 @SystemApi
3703 @RequiresPermission(anyOf = {
3704 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3705 android.Manifest.permission.NETWORK_FACTORY})
3706 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3707 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3708 throw new IllegalStateException("NetworkProviders can only be registered once");
3709 }
3710
3711 try {
3712 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3713 provider.getName());
3714 provider.setProviderId(providerId);
3715 } catch (RemoteException e) {
3716 throw e.rethrowFromSystemServer();
3717 }
3718 return provider.getProviderId();
3719 }
3720
3721 /**
3722 * Unregisters the specified NetworkProvider.
3723 *
3724 * @param provider the provider to unregister
3725 * @hide
3726 */
3727 @SystemApi
3728 @RequiresPermission(anyOf = {
3729 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3730 android.Manifest.permission.NETWORK_FACTORY})
3731 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3732 try {
3733 mService.unregisterNetworkProvider(provider.getMessenger());
3734 } catch (RemoteException e) {
3735 throw e.rethrowFromSystemServer();
3736 }
3737 provider.setProviderId(NetworkProvider.ID_NONE);
3738 }
3739
Chalard Jeand1b498b2021-01-05 08:40:09 +09003740 /**
3741 * Register or update a network offer with ConnectivityService.
3742 *
3743 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003744 * them to networking requests made by apps or the system. A callback identifies an offer
3745 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3746 * score and the capabilities of the network it might be able to bring up ; these act as
3747 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003748 * provider.
3749 *
3750 * The provider is under no obligation to be able to bring up the network it offers at any
3751 * given time. Instead, this mechanism is meant to limit requests received by providers
3752 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3753 * the quality of the network satisfying a given request to their own offer.
3754 *
3755 * An offer can be updated by calling this again with the same callback object. This is
3756 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3757 * provider with the changes caused by the changes in the offer.
3758 *
3759 * @param provider The provider making this offer.
3760 * @param score The prospective score of the network.
3761 * @param caps The prospective capabilities of the network.
3762 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003763 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003764 */
3765 @RequiresPermission(anyOf = {
3766 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3767 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003768 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003769 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3770 @NonNull final INetworkOfferCallback callback) {
3771 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003772 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003773 Objects.requireNonNull(score, "null score"),
3774 Objects.requireNonNull(caps, "null caps"),
3775 Objects.requireNonNull(callback, "null callback"));
3776 } catch (RemoteException e) {
3777 throw e.rethrowFromSystemServer();
3778 }
3779 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003780
Chalard Jeand1b498b2021-01-05 08:40:09 +09003781 /**
3782 * Withdraw a network offer made with {@link #offerNetwork}.
3783 *
3784 * @param callback The callback passed at registration time. This must be the same object
3785 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003786 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003787 */
3788 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3789 try {
3790 mService.unofferNetwork(Objects.requireNonNull(callback));
3791 } catch (RemoteException e) {
3792 throw e.rethrowFromSystemServer();
3793 }
3794 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003795 /** @hide exposed via the NetworkProvider class. */
3796 @RequiresPermission(anyOf = {
3797 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3798 android.Manifest.permission.NETWORK_FACTORY})
3799 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3800 try {
3801 mService.declareNetworkRequestUnfulfillable(request);
3802 } catch (RemoteException e) {
3803 throw e.rethrowFromSystemServer();
3804 }
3805 }
3806
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003807 /**
3808 * @hide
3809 * Register a NetworkAgent with ConnectivityService.
3810 * @return Network corresponding to NetworkAgent.
3811 */
3812 @RequiresPermission(anyOf = {
3813 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3814 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003815 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3816 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3817 @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId) {
3818 return registerNetworkAgent(na, ni, lp, nc, null /* localNetworkConfig */, score, config,
3819 providerId);
3820 }
3821
3822 /**
3823 * @hide
3824 * Register a NetworkAgent with ConnectivityService.
3825 * @return Network corresponding to NetworkAgent.
3826 */
3827 @RequiresPermission(anyOf = {
3828 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3829 android.Manifest.permission.NETWORK_FACTORY})
3830 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3831 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3832 @Nullable LocalNetworkConfig localNetworkConfig, @NonNull NetworkScore score,
3833 @NonNull NetworkAgentConfig config, int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003834 try {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003835 return mService.registerNetworkAgent(na, ni, lp, nc, score, localNetworkConfig, config,
3836 providerId);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003837 } catch (RemoteException e) {
3838 throw e.rethrowFromSystemServer();
3839 }
3840 }
3841
3842 /**
3843 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3844 * changes. Should be extended by applications wanting notifications.
3845 *
3846 * A {@code NetworkCallback} is registered by calling
3847 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3848 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3849 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3850 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3851 * A {@code NetworkCallback} should be registered at most once at any time.
3852 * A {@code NetworkCallback} that has been unregistered can be registered again.
3853 */
3854 public static class NetworkCallback {
3855 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003856 * No flags associated with this callback.
3857 * @hide
3858 */
3859 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003860
Roshan Piuse08bc182020-12-22 15:10:42 -08003861 /**
lucaslinc582d502022-01-27 09:07:00 +08003862 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3863 *
3864 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3865 * Prior to Android 12, this information is always returned to apps holding the appropriate
3866 * permission, possibly noting that the app has used location.
3867 * <p>In Android 12 and above, by default the sent objects do not contain any location
3868 * information, even if the app holds the necessary permissions, and the system does not
3869 * take note of location usage by the app. Apps can request that location information is
3870 * included, in which case the system will check location permission and the location
3871 * toggle state, and take note of location usage by the app if any such information is
3872 * returned.
3873 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003874 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3875 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3876 * <p>
3877 * These include:
3878 * <li> Some transport info instances (retrieved via
3879 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3880 * contain location sensitive information.
3881 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003882 * sensitive for wifi suggestor apps (i.e using
3883 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003884 * </p>
3885 * <p>
3886 * Note:
3887 * <li> Retrieving this location sensitive information (subject to app's location
3888 * permissions) will be noted by system. </li>
3889 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003890 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003891 */
Roshan Pius189d0092021-03-11 21:16:44 -08003892 // Note: Some existing fields which are location sensitive may still be included without
3893 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003894 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3895
3896 /** @hide */
3897 @Retention(RetentionPolicy.SOURCE)
3898 @IntDef(flag = true, prefix = "FLAG_", value = {
3899 FLAG_NONE,
3900 FLAG_INCLUDE_LOCATION_INFO
3901 })
3902 public @interface Flag { }
3903
3904 /**
3905 * All the valid flags for error checking.
3906 */
3907 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3908
3909 public NetworkCallback() {
3910 this(FLAG_NONE);
3911 }
3912
3913 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003914 if ((flags & VALID_FLAGS) != flags) {
3915 throw new IllegalArgumentException("Invalid flags");
3916 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003917 mFlags = flags;
3918 }
3919
3920 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003921 * Called when the framework connects to a new network to evaluate whether it satisfies this
3922 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3923 * callback. There is no guarantee that this new network will satisfy any requests, or that
3924 * the network will stay connected for longer than the time necessary to evaluate it.
3925 * <p>
3926 * Most applications <b>should not</b> act on this callback, and should instead use
3927 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3928 * the framework in properly evaluating the network &mdash; for example, an application that
3929 * can automatically log in to a captive portal without user intervention.
3930 *
3931 * @param network The {@link Network} of the network that is being evaluated.
3932 *
3933 * @hide
3934 */
3935 public void onPreCheck(@NonNull Network network) {}
3936
3937 /**
3938 * Called when the framework connects and has declared a new network ready for use.
3939 * This callback may be called more than once if the {@link Network} that is
3940 * satisfying the request changes.
3941 *
3942 * @param network The {@link Network} of the satisfying network.
3943 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3944 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3945 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3946 * @hide
3947 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003948 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003949 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003950 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003951 // Internally only this method is called when a new network is available, and
3952 // it calls the callback in the same way and order that older versions used
3953 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003954 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3955 onBlockedStatusChanged(network, blocked);
3956 }
3957
3958 /**
3959 * Legacy variant of onAvailable that takes a boolean blocked reason.
3960 *
3961 * This method has never been public API, but it's not final, so there may be apps that
3962 * implemented it and rely on it being called. Do our best not to break them.
3963 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3964 * this method is called. There does not seem to be a way to avoid this.
3965 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3966 *
3967 * @hide
3968 */
3969 public void onAvailable(@NonNull Network network,
3970 @NonNull NetworkCapabilities networkCapabilities,
3971 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003972 onAvailable(network);
3973 if (!networkCapabilities.hasCapability(
3974 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3975 onNetworkSuspended(network);
3976 }
3977 onCapabilitiesChanged(network, networkCapabilities);
3978 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003979 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003980 }
3981
3982 /**
3983 * Called when the framework connects and has declared a new network ready for use.
3984 *
3985 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3986 * be available at the same time, and onAvailable will be called for each of these as they
3987 * appear.
3988 *
3989 * <p>For callbacks registered with {@link #requestNetwork} and
3990 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3991 * is the new best network for this request and is now tracked by this callback ; this
3992 * callback will no longer receive method calls about other networks that may have been
3993 * passed to this method previously. The previously-best network may have disconnected, or
3994 * it may still be around and the newly-best network may simply be better.
3995 *
3996 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3997 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3998 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3999 * to {@link #onBlockedStatusChanged(Network, boolean)}.
4000 *
4001 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4002 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4003 * this callback as this is prone to race conditions (there is no guarantee the objects
4004 * returned by these methods will be current). Instead, wait for a call to
4005 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
4006 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
4007 * to be well-ordered with respect to other callbacks.
4008 *
4009 * @param network The {@link Network} of the satisfying network.
4010 */
4011 public void onAvailable(@NonNull Network network) {}
4012
4013 /**
4014 * Called when the network is about to be lost, typically because there are no outstanding
4015 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
4016 * with the new replacement network for graceful handover. This method is not guaranteed
4017 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
4018 * network is suddenly disconnected.
4019 *
4020 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4021 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4022 * this callback as this is prone to race conditions ; calling these methods while in a
4023 * callback may return an outdated or even a null object.
4024 *
4025 * @param network The {@link Network} that is about to be lost.
4026 * @param maxMsToLive The time in milliseconds the system intends to keep the network
4027 * connected for graceful handover; note that the network may still
4028 * suffer a hard loss at any time.
4029 */
4030 public void onLosing(@NonNull Network network, int maxMsToLive) {}
4031
4032 /**
4033 * Called when a network disconnects or otherwise no longer satisfies this request or
4034 * callback.
4035 *
4036 * <p>If the callback was registered with requestNetwork() or
4037 * registerDefaultNetworkCallback(), it will only be invoked against the last network
4038 * returned by onAvailable() when that network is lost and no other network satisfies
4039 * the criteria of the request.
4040 *
4041 * <p>If the callback was registered with registerNetworkCallback() it will be called for
4042 * each network which no longer satisfies the criteria of the callback.
4043 *
4044 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4045 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4046 * this callback as this is prone to race conditions ; calling these methods while in a
4047 * callback may return an outdated or even a null object.
4048 *
4049 * @param network The {@link Network} lost.
4050 */
4051 public void onLost(@NonNull Network network) {}
4052
4053 /**
4054 * Called if no network is found within the timeout time specified in
4055 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
4056 * requested network request cannot be fulfilled (whether or not a timeout was
4057 * specified). When this callback is invoked the associated
4058 * {@link NetworkRequest} will have already been removed and released, as if
4059 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
4060 */
4061 public void onUnavailable() {}
4062
4063 /**
4064 * Called when the network corresponding to this request changes capabilities but still
4065 * satisfies the requested criteria.
4066 *
4067 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4068 * to be called immediately after {@link #onAvailable}.
4069 *
4070 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
4071 * ConnectivityManager methods in this callback as this is prone to race conditions :
4072 * calling these methods while in a callback may return an outdated or even a null object.
4073 *
4074 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08004075 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004076 * network.
4077 */
4078 public void onCapabilitiesChanged(@NonNull Network network,
4079 @NonNull NetworkCapabilities networkCapabilities) {}
4080
4081 /**
4082 * Called when the network corresponding to this request changes {@link LinkProperties}.
4083 *
4084 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4085 * to be called immediately after {@link #onAvailable}.
4086 *
4087 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
4088 * ConnectivityManager methods in this callback as this is prone to race conditions :
4089 * calling these methods while in a callback may return an outdated or even a null object.
4090 *
4091 * @param network The {@link Network} whose link properties have changed.
4092 * @param linkProperties The new {@link LinkProperties} for this network.
4093 */
4094 public void onLinkPropertiesChanged(@NonNull Network network,
4095 @NonNull LinkProperties linkProperties) {}
4096
4097 /**
4098 * Called when the network the framework connected to for this request suspends data
4099 * transmission temporarily.
4100 *
4101 * <p>This generally means that while the TCP connections are still live temporarily
4102 * network data fails to transfer. To give a specific example, this is used on cellular
4103 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4104 * means read operations on sockets on this network will block once the buffers are
4105 * drained, and write operations will block once the buffers are full.
4106 *
4107 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4108 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4109 * this callback as this is prone to race conditions (there is no guarantee the objects
4110 * returned by these methods will be current).
4111 *
4112 * @hide
4113 */
4114 public void onNetworkSuspended(@NonNull Network network) {}
4115
4116 /**
4117 * Called when the network the framework connected to for this request
4118 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4119 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4120
4121 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4122 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4123 * this callback as this is prone to race conditions : calling these methods while in a
4124 * callback may return an outdated or even a null object.
4125 *
4126 * @hide
4127 */
4128 public void onNetworkResumed(@NonNull Network network) {}
4129
4130 /**
4131 * Called when access to the specified network is blocked or unblocked.
4132 *
4133 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4134 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4135 * this callback as this is prone to race conditions : calling these methods while in a
4136 * callback may return an outdated or even a null object.
4137 *
4138 * @param network The {@link Network} whose blocked status has changed.
4139 * @param blocked The blocked status of this {@link Network}.
4140 */
4141 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4142
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004143 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004144 * Called when access to the specified network is blocked or unblocked, or the reason for
4145 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004146 *
4147 * If a NetworkCallback object implements this method,
4148 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4149 *
4150 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4151 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4152 * this callback as this is prone to race conditions : calling these methods while in a
4153 * callback may return an outdated or even a null object.
4154 *
4155 * @param network The {@link Network} whose blocked status has changed.
4156 * @param blocked The blocked status of this {@link Network}.
4157 * @hide
4158 */
4159 @SystemApi(client = MODULE_LIBRARIES)
4160 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4161 onBlockedStatusChanged(network, blocked != 0);
4162 }
4163
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004164 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004165 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004166 }
4167
4168 /**
4169 * Constant error codes used by ConnectivityService to communicate about failures and errors
4170 * across a Binder boundary.
4171 * @hide
4172 */
4173 public interface Errors {
4174 int TOO_MANY_REQUESTS = 1;
4175 }
4176
4177 /** @hide */
4178 public static class TooManyRequestsException extends RuntimeException {}
4179
4180 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4181 switch (e.errorCode) {
4182 case Errors.TOO_MANY_REQUESTS:
4183 return new TooManyRequestsException();
4184 default:
4185 Log.w(TAG, "Unknown service error code " + e.errorCode);
4186 return new RuntimeException(e);
4187 }
4188 }
4189
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004190 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004191 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004192 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004193 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004194 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004195 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004196 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004197 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004198 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004199 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004200 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004201 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004202 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004203 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004204 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004205 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004206 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004207 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004208 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004209 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004210 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004211 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004212
4213 /** @hide */
4214 public static String getCallbackName(int whichCallback) {
4215 switch (whichCallback) {
4216 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4217 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4218 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4219 case CALLBACK_LOST: return "CALLBACK_LOST";
4220 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4221 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4222 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4223 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4224 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4225 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4226 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4227 default:
4228 return Integer.toString(whichCallback);
4229 }
4230 }
4231
zhujiatai79b0de92022-09-22 15:44:02 +08004232 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004233 private static final String TAG = "ConnectivityManager.CallbackHandler";
4234 private static final boolean DBG = false;
4235
4236 CallbackHandler(Looper looper) {
4237 super(looper);
4238 }
4239
4240 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004241 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004242 }
4243
4244 @Override
4245 public void handleMessage(Message message) {
4246 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004247 // the sInstance can't be null because to send this message a ConnectivityManager
4248 // instance must have been created prior to creating the thread on which this
4249 // Handler is running.
4250 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004251 return;
4252 }
4253
4254 final NetworkRequest request = getObject(message, NetworkRequest.class);
4255 final Network network = getObject(message, Network.class);
4256 final NetworkCallback callback;
4257 synchronized (sCallbacks) {
4258 callback = sCallbacks.get(request);
4259 if (callback == null) {
4260 Log.w(TAG,
4261 "callback not found for " + getCallbackName(message.what) + " message");
4262 return;
4263 }
4264 if (message.what == CALLBACK_UNAVAIL) {
4265 sCallbacks.remove(request);
4266 callback.networkRequest = ALREADY_UNREGISTERED;
4267 }
4268 }
4269 if (DBG) {
4270 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4271 }
4272
4273 switch (message.what) {
4274 case CALLBACK_PRECHECK: {
4275 callback.onPreCheck(network);
4276 break;
4277 }
4278 case CALLBACK_AVAILABLE: {
4279 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4280 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004281 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004282 break;
4283 }
4284 case CALLBACK_LOSING: {
4285 callback.onLosing(network, message.arg1);
4286 break;
4287 }
4288 case CALLBACK_LOST: {
4289 callback.onLost(network);
4290 break;
4291 }
4292 case CALLBACK_UNAVAIL: {
4293 callback.onUnavailable();
4294 break;
4295 }
4296 case CALLBACK_CAP_CHANGED: {
4297 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4298 callback.onCapabilitiesChanged(network, cap);
4299 break;
4300 }
4301 case CALLBACK_IP_CHANGED: {
4302 LinkProperties lp = getObject(message, LinkProperties.class);
4303 callback.onLinkPropertiesChanged(network, lp);
4304 break;
4305 }
4306 case CALLBACK_SUSPENDED: {
4307 callback.onNetworkSuspended(network);
4308 break;
4309 }
4310 case CALLBACK_RESUMED: {
4311 callback.onNetworkResumed(network);
4312 break;
4313 }
4314 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004315 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004316 }
4317 }
4318 }
4319
4320 private <T> T getObject(Message msg, Class<T> c) {
4321 return (T) msg.getData().getParcelable(c.getSimpleName());
4322 }
4323 }
4324
4325 private CallbackHandler getDefaultHandler() {
4326 synchronized (sCallbacks) {
4327 if (sCallbackHandler == null) {
4328 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4329 }
4330 return sCallbackHandler;
4331 }
4332 }
4333
4334 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4335 private static CallbackHandler sCallbackHandler;
4336
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004337 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4338 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4339 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004340 printStackTrace();
4341 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004342 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4343 throw new IllegalArgumentException("null NetworkCapabilities");
4344 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004345 final NetworkRequest request;
4346 final String callingPackageName = mContext.getOpPackageName();
4347 try {
4348 synchronized(sCallbacks) {
4349 if (callback.networkRequest != null
4350 && callback.networkRequest != ALREADY_UNREGISTERED) {
4351 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4352 // and requests (http://b/20701525).
4353 Log.e(TAG, "NetworkCallback was already registered");
4354 }
4355 Messenger messenger = new Messenger(handler);
4356 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004357 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004358 if (reqType == LISTEN) {
4359 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004360 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004361 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004362 } else {
4363 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004364 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4365 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004366 }
4367 if (request != null) {
4368 sCallbacks.put(request, callback);
4369 }
4370 callback.networkRequest = request;
4371 }
4372 } catch (RemoteException e) {
4373 throw e.rethrowFromSystemServer();
4374 } catch (ServiceSpecificException e) {
4375 throw convertServiceException(e);
4376 }
4377 return request;
4378 }
4379
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004380 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4381 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4382 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4383 legacyType, handler);
4384 }
4385
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004386 /**
4387 * Helper function to request a network with a particular legacy type.
4388 *
4389 * This API is only for use in internal system code that requests networks with legacy type and
4390 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4391 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4392 *
4393 * @param request {@link NetworkRequest} describing this request.
4394 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4395 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4396 * be a positive value (i.e. >0).
4397 * @param legacyType to specify the network type(#TYPE_*).
4398 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4399 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4400 * the callback must not be shared - it uniquely specifies this request.
4401 *
4402 * @hide
4403 */
4404 @SystemApi
4405 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4406 public void requestNetwork(@NonNull NetworkRequest request,
4407 int timeoutMs, int legacyType, @NonNull Handler handler,
4408 @NonNull NetworkCallback networkCallback) {
4409 if (legacyType == TYPE_NONE) {
4410 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4411 }
4412 CallbackHandler cbHandler = new CallbackHandler(handler);
4413 NetworkCapabilities nc = request.networkCapabilities;
4414 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4415 }
4416
4417 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004418 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004419 *
4420 * <p>This method will attempt to find the best network that matches the passed
4421 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4422 * criteria. The platform will evaluate which network is the best at its own discretion.
4423 * Throughput, latency, cost per byte, policy, user preference and other considerations
4424 * may be factored in the decision of what is considered the best network.
4425 *
4426 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4427 * matching this request, while always attempting to match the request to a better network if
4428 * possible. If a better match is found, the platform will switch this request to the now-best
4429 * network and inform the app of the newly best network by invoking
4430 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4431 * will not try to maintain any other network than the best one currently matching the request:
4432 * a network not matching any network request may be disconnected at any time.
4433 *
4434 * <p>For example, an application could use this method to obtain a connected cellular network
4435 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4436 * radio to consume additional power. Or, an application could inform the system that it wants
4437 * a network supporting sending MMSes and have the system let it know about the currently best
4438 * MMS-supporting network through the provided {@link NetworkCallback}.
4439 *
4440 * <p>The status of the request can be followed by listening to the various callbacks described
4441 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4442 * used to direct traffic to the network (although accessing some networks may be subject to
4443 * holding specific permissions). Callers will learn about the specific characteristics of the
4444 * network through
4445 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4446 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4447 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4448 * matching the request at any given time; therefore when a better network matching the request
4449 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4450 * with the new network after which no further updates are given about the previously-best
4451 * network, unless it becomes the best again at some later time. All callbacks are invoked
4452 * in order on the same thread, which by default is a thread created by the framework running
4453 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004454 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004455 * callbacks are invoked.
4456 *
4457 * <p>This{@link NetworkRequest} will live until released via
4458 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4459 * which point the system may let go of the network at any time.
4460 *
4461 * <p>A version of this method which takes a timeout is
4462 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4463 * wait for a limited amount of time for the network to become unavailable.
4464 *
4465 * <p>It is presently unsupported to request a network with mutable
4466 * {@link NetworkCapabilities} such as
4467 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4468 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4469 * as these {@code NetworkCapabilities} represent states that a particular
4470 * network may never attain, and whether a network will attain these states
4471 * is unknown prior to bringing up the network so the framework does not
4472 * know how to go about satisfying a request with these capabilities.
4473 *
4474 * <p>This method requires the caller to hold either the
4475 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4476 * or the ability to modify system settings as determined by
4477 * {@link android.provider.Settings.System#canWrite}.</p>
4478 *
4479 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4480 * number of outstanding requests to 100 per app (identified by their UID), shared with
4481 * all variants of this method, of {@link #registerNetworkCallback} as well as
4482 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4483 * Requesting a network with this method will count toward this limit. If this limit is
4484 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4485 * make sure to unregister the callbacks with
4486 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4487 *
4488 * @param request {@link NetworkRequest} describing this request.
4489 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4490 * the callback must not be shared - it uniquely specifies this request.
4491 * The callback is invoked on the default internal Handler.
4492 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4493 * @throws SecurityException if missing the appropriate permissions.
4494 * @throws RuntimeException if the app already has too many callbacks registered.
4495 */
4496 public void requestNetwork(@NonNull NetworkRequest request,
4497 @NonNull NetworkCallback networkCallback) {
4498 requestNetwork(request, networkCallback, getDefaultHandler());
4499 }
4500
4501 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004502 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004503 *
4504 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4505 * but runs all the callbacks on the passed Handler.
4506 *
4507 * <p>This method has the same permission requirements as
4508 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4509 * and throws the same exceptions in the same conditions.
4510 *
4511 * @param request {@link NetworkRequest} describing this request.
4512 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4513 * the callback must not be shared - it uniquely specifies this request.
4514 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4515 */
4516 public void requestNetwork(@NonNull NetworkRequest request,
4517 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4518 CallbackHandler cbHandler = new CallbackHandler(handler);
4519 NetworkCapabilities nc = request.networkCapabilities;
4520 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4521 }
4522
4523 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004524 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004525 * by a timeout.
4526 *
4527 * This function behaves identically to the non-timed-out version
4528 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4529 * is not found within the given time (in milliseconds) the
4530 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4531 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4532 * not have to be released if timed-out (it is automatically released). Unregistering a
4533 * request that timed out is not an error.
4534 *
4535 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4536 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4537 * for that purpose. Calling this method will attempt to bring up the requested network.
4538 *
4539 * <p>This method has the same permission requirements as
4540 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4541 * and throws the same exceptions in the same conditions.
4542 *
4543 * @param request {@link NetworkRequest} describing this request.
4544 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4545 * the callback must not be shared - it uniquely specifies this request.
4546 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4547 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4548 * be a positive value (i.e. >0).
4549 */
4550 public void requestNetwork(@NonNull NetworkRequest request,
4551 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4552 checkTimeout(timeoutMs);
4553 NetworkCapabilities nc = request.networkCapabilities;
4554 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4555 getDefaultHandler());
4556 }
4557
4558 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004559 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004560 * by a timeout.
4561 *
4562 * This method behaves identically to
4563 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4564 * on the passed Handler.
4565 *
4566 * <p>This method has the same permission requirements as
4567 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4568 * and throws the same exceptions in the same conditions.
4569 *
4570 * @param request {@link NetworkRequest} describing this request.
4571 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4572 * the callback must not be shared - it uniquely specifies this request.
4573 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4574 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4575 * before {@link NetworkCallback#onUnavailable} is called.
4576 */
4577 public void requestNetwork(@NonNull NetworkRequest request,
4578 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4579 checkTimeout(timeoutMs);
4580 CallbackHandler cbHandler = new CallbackHandler(handler);
4581 NetworkCapabilities nc = request.networkCapabilities;
4582 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4583 }
4584
4585 /**
4586 * The lookup key for a {@link Network} object included with the intent after
4587 * successfully finding a network for the applications request. Retrieve it with
4588 * {@link android.content.Intent#getParcelableExtra(String)}.
4589 * <p>
4590 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4591 * then you must get a ConnectivityManager instance before doing so.
4592 */
4593 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4594
4595 /**
4596 * The lookup key for a {@link NetworkRequest} object included with the intent after
4597 * successfully finding a network for the applications request. Retrieve it with
4598 * {@link android.content.Intent#getParcelableExtra(String)}.
4599 */
4600 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4601
4602
4603 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004604 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004605 *
4606 * This function behaves identically to the version that takes a NetworkCallback, but instead
4607 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4608 * the request may outlive the calling application and get called back when a suitable
4609 * network is found.
4610 * <p>
4611 * The operation is an Intent broadcast that goes to a broadcast receiver that
4612 * you registered with {@link Context#registerReceiver} or through the
4613 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4614 * <p>
4615 * The operation Intent is delivered with two extras, a {@link Network} typed
4616 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4617 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4618 * the original requests parameters. It is important to create a new,
4619 * {@link NetworkCallback} based request before completing the processing of the
4620 * Intent to reserve the network or it will be released shortly after the Intent
4621 * is processed.
4622 * <p>
4623 * If there is already a request for this Intent registered (with the equality of
4624 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4625 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4626 * <p>
4627 * The request may be released normally by calling
4628 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4629 * <p>It is presently unsupported to request a network with either
4630 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4631 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4632 * as these {@code NetworkCapabilities} represent states that a particular
4633 * network may never attain, and whether a network will attain these states
4634 * is unknown prior to bringing up the network so the framework does not
4635 * know how to go about satisfying a request with these capabilities.
4636 *
4637 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4638 * number of outstanding requests to 100 per app (identified by their UID), shared with
4639 * all variants of this method, of {@link #registerNetworkCallback} as well as
4640 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4641 * Requesting a network with this method will count toward this limit. If this limit is
4642 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4643 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4644 * or {@link #releaseNetworkRequest(PendingIntent)}.
4645 *
4646 * <p>This method requires the caller to hold either the
4647 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4648 * or the ability to modify system settings as determined by
4649 * {@link android.provider.Settings.System#canWrite}.</p>
4650 *
4651 * @param request {@link NetworkRequest} describing this request.
4652 * @param operation Action to perform when the network is available (corresponds
4653 * to the {@link NetworkCallback#onAvailable} call. Typically
4654 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4655 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4656 * @throws SecurityException if missing the appropriate permissions.
4657 * @throws RuntimeException if the app already has too many callbacks registered.
4658 */
4659 public void requestNetwork(@NonNull NetworkRequest request,
4660 @NonNull PendingIntent operation) {
4661 printStackTrace();
4662 checkPendingIntentNotNull(operation);
4663 try {
4664 mService.pendingRequestForNetwork(
4665 request.networkCapabilities, operation, mContext.getOpPackageName(),
4666 getAttributionTag());
4667 } catch (RemoteException e) {
4668 throw e.rethrowFromSystemServer();
4669 } catch (ServiceSpecificException e) {
4670 throw convertServiceException(e);
4671 }
4672 }
4673
4674 /**
4675 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4676 * <p>
4677 * This method has the same behavior as
4678 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4679 * releasing network resources and disconnecting.
4680 *
4681 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4682 * PendingIntent passed to
4683 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4684 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4685 */
4686 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4687 printStackTrace();
4688 checkPendingIntentNotNull(operation);
4689 try {
4690 mService.releasePendingNetworkRequest(operation);
4691 } catch (RemoteException e) {
4692 throw e.rethrowFromSystemServer();
4693 }
4694 }
4695
4696 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004697 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004698 }
4699
4700 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004701 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004702 }
4703
4704 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004705 if (timeoutMs <= 0) {
4706 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4707 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004708 }
4709
4710 /**
4711 * Registers to receive notifications about all networks which satisfy the given
4712 * {@link NetworkRequest}. The callbacks will continue to be called until
4713 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4714 * called.
4715 *
4716 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4717 * number of outstanding requests to 100 per app (identified by their UID), shared with
4718 * all variants of this method, of {@link #requestNetwork} as well as
4719 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4720 * Requesting a network with this method will count toward this limit. If this limit is
4721 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4722 * make sure to unregister the callbacks with
4723 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4724 *
4725 * @param request {@link NetworkRequest} describing this request.
4726 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4727 * networks change state.
4728 * The callback is invoked on the default internal Handler.
4729 * @throws RuntimeException if the app already has too many callbacks registered.
4730 */
4731 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4732 public void registerNetworkCallback(@NonNull NetworkRequest request,
4733 @NonNull NetworkCallback networkCallback) {
4734 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4735 }
4736
4737 /**
4738 * Registers to receive notifications about all networks which satisfy the given
4739 * {@link NetworkRequest}. The callbacks will continue to be called until
4740 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4741 * called.
4742 *
4743 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4744 * number of outstanding requests to 100 per app (identified by their UID), shared with
4745 * all variants of this method, of {@link #requestNetwork} as well as
4746 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4747 * Requesting a network with this method will count toward this limit. If this limit is
4748 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4749 * make sure to unregister the callbacks with
4750 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4751 *
4752 *
4753 * @param request {@link NetworkRequest} describing this request.
4754 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4755 * networks change state.
4756 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4757 * @throws RuntimeException if the app already has too many callbacks registered.
4758 */
4759 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4760 public void registerNetworkCallback(@NonNull NetworkRequest request,
4761 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4762 CallbackHandler cbHandler = new CallbackHandler(handler);
4763 NetworkCapabilities nc = request.networkCapabilities;
4764 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4765 }
4766
4767 /**
4768 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4769 * {@link NetworkRequest}.
4770 *
4771 * This function behaves identically to the version that takes a NetworkCallback, but instead
4772 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4773 * the request may outlive the calling application and get called back when a suitable
4774 * network is found.
4775 * <p>
4776 * The operation is an Intent broadcast that goes to a broadcast receiver that
4777 * you registered with {@link Context#registerReceiver} or through the
4778 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4779 * <p>
4780 * The operation Intent is delivered with two extras, a {@link Network} typed
4781 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4782 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4783 * the original requests parameters.
4784 * <p>
4785 * If there is already a request for this Intent registered (with the equality of
4786 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4787 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4788 * <p>
4789 * The request may be released normally by calling
4790 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
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 {@link #unregisterNetworkCallback(PendingIntent)}
4799 * or {@link #releaseNetworkRequest(PendingIntent)}.
4800 *
4801 * @param request {@link NetworkRequest} describing this request.
4802 * @param operation Action to perform when the network is available (corresponds
4803 * to the {@link NetworkCallback#onAvailable} call. Typically
4804 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4805 * @throws RuntimeException if the app already has too many callbacks registered.
4806 */
4807 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4808 public void registerNetworkCallback(@NonNull NetworkRequest request,
4809 @NonNull PendingIntent operation) {
4810 printStackTrace();
4811 checkPendingIntentNotNull(operation);
4812 try {
4813 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004814 request.networkCapabilities, operation, mContext.getOpPackageName(),
4815 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004816 } catch (RemoteException e) {
4817 throw e.rethrowFromSystemServer();
4818 } catch (ServiceSpecificException e) {
4819 throw convertServiceException(e);
4820 }
4821 }
4822
4823 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004824 * Registers to receive notifications about changes in the application's default network. This
4825 * may be a physical network or a virtual network, such as a VPN that applies to the
4826 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004827 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4828 *
4829 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4830 * number of outstanding requests to 100 per app (identified by their UID), shared with
4831 * all variants of this method, of {@link #requestNetwork} as well as
4832 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4833 * Requesting a network with this method will count toward this limit. If this limit is
4834 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4835 * make sure to unregister the callbacks with
4836 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4837 *
4838 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004839 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004840 * The callback is invoked on the default internal Handler.
4841 * @throws RuntimeException if the app already has too many callbacks registered.
4842 */
4843 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4844 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4845 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4846 }
4847
4848 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004849 * Registers to receive notifications about changes in the application's default network. This
4850 * may be a physical network or a virtual network, such as a VPN that applies to the
4851 * application. The callbacks will continue to be called until either the application exits or
4852 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4853 *
4854 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4855 * number of outstanding requests to 100 per app (identified by their UID), shared with
4856 * all variants of this method, of {@link #requestNetwork} as well as
4857 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4858 * Requesting a network with this method will count toward this limit. If this limit is
4859 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4860 * make sure to unregister the callbacks with
4861 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4862 *
4863 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4864 * application's default network changes.
4865 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4866 * @throws RuntimeException if the app already has too many callbacks registered.
4867 */
4868 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4869 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4870 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004871 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004872 }
4873
4874 /**
4875 * Registers to receive notifications about changes in the default network for the specified
4876 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4877 * UID. The callbacks will continue to be called until either the application exits or
4878 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4879 *
4880 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4881 * number of outstanding requests to 100 per app (identified by their UID), shared with
4882 * all variants of this method, of {@link #requestNetwork} as well as
4883 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4884 * Requesting a network with this method will count toward this limit. If this limit is
4885 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4886 * make sure to unregister the callbacks with
4887 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4888 *
4889 * @param uid the UID for which to track default network changes.
4890 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4891 * UID's default network changes.
4892 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4893 * @throws RuntimeException if the app already has too many callbacks registered.
4894 * @hide
4895 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004896 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004897 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4898 @RequiresPermission(anyOf = {
4899 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4900 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004901 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004902 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004903 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004904 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004905 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4906 }
4907
4908 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004909 * Registers to receive notifications about changes in the system default network. The callbacks
4910 * will continue to be called until either the application exits or
4911 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4912 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004913 * This method should not be used to determine networking state seen by applications, because in
4914 * many cases, most or even all application traffic may not use the default network directly,
4915 * and traffic from different applications may go on different networks by default. As an
4916 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4917 * and not onto the system default network. Applications or system components desiring to do
4918 * determine network state as seen by applications should use other methods such as
4919 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4920 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004921 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4922 * number of outstanding requests to 100 per app (identified by their UID), shared with
4923 * all variants of this method, of {@link #requestNetwork} as well as
4924 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4925 * Requesting a network with this method will count toward this limit. If this limit is
4926 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4927 * make sure to unregister the callbacks with
4928 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4929 *
4930 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4931 * system default network changes.
4932 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4933 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004934 *
4935 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004936 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004937 @SystemApi(client = MODULE_LIBRARIES)
4938 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4939 @RequiresPermission(anyOf = {
4940 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004941 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00004942 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004943 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004944 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004945 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004946 CallbackHandler cbHandler = new CallbackHandler(handler);
4947 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004948 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004949 }
4950
4951 /**
junyulaibd123062021-03-15 11:48:48 +08004952 * Registers to receive notifications about the best matching network which satisfy the given
4953 * {@link NetworkRequest}. The callbacks will continue to be called until
4954 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4955 * called.
4956 *
4957 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4958 * number of outstanding requests to 100 per app (identified by their UID), shared with
4959 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4960 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4961 * Requesting a network with this method will count toward this limit. If this limit is
4962 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4963 * make sure to unregister the callbacks with
4964 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4965 *
4966 *
4967 * @param request {@link NetworkRequest} describing this request.
4968 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4969 * networks change state.
4970 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4971 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004972 */
junyulai5a5c99b2021-03-05 15:51:17 +08004973 @SuppressLint("ExecutorRegistration")
4974 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4975 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4976 final NetworkCapabilities nc = request.networkCapabilities;
4977 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004978 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004979 }
4980
4981 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004982 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4983 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4984 * network connection for updated bandwidth information. The caller will be notified via
4985 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4986 * method assumes that the caller has previously called
4987 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4988 * changes.
4989 *
4990 * @param network {@link Network} specifying which network you're interested.
4991 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4992 */
4993 public boolean requestBandwidthUpdate(@NonNull Network network) {
4994 try {
4995 return mService.requestBandwidthUpdate(network);
4996 } catch (RemoteException e) {
4997 throw e.rethrowFromSystemServer();
4998 }
4999 }
5000
5001 /**
5002 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
5003 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
5004 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005005 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
5006 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005007 *
5008 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
5009 * triggering it as soon as this call returns.
5010 *
5011 * @param networkCallback The {@link NetworkCallback} used when making the request.
5012 */
5013 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
5014 printStackTrace();
5015 checkCallbackNotNull(networkCallback);
5016 final List<NetworkRequest> reqs = new ArrayList<>();
5017 // Find all requests associated to this callback and stop callback triggers immediately.
5018 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
5019 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00005020 if (networkCallback.networkRequest == null) {
5021 throw new IllegalArgumentException("NetworkCallback was not registered");
5022 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005023 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
5024 Log.d(TAG, "NetworkCallback was already unregistered");
5025 return;
5026 }
5027 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
5028 if (e.getValue() == networkCallback) {
5029 reqs.add(e.getKey());
5030 }
5031 }
5032 // TODO: throw exception if callback was registered more than once (http://b/20701525).
5033 for (NetworkRequest r : reqs) {
5034 try {
5035 mService.releaseNetworkRequest(r);
5036 } catch (RemoteException e) {
5037 throw e.rethrowFromSystemServer();
5038 }
5039 // Only remove mapping if rpc was successful.
5040 sCallbacks.remove(r);
5041 }
5042 networkCallback.networkRequest = ALREADY_UNREGISTERED;
5043 }
5044 }
5045
5046 /**
5047 * Unregisters a callback previously registered via
5048 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5049 *
5050 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
5051 * PendingIntent passed to
5052 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5053 * Cannot be null.
5054 */
5055 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
5056 releaseNetworkRequest(operation);
5057 }
5058
5059 /**
5060 * Informs the system whether it should switch to {@code network} regardless of whether it is
5061 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
5062 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
5063 * the system default network regardless of any other network that's currently connected. If
5064 * {@code always} is true, then the choice is remembered, so that the next time the user
5065 * connects to this network, the system will switch to it.
5066 *
5067 * @param network The network to accept.
5068 * @param accept Whether to accept the network even if unvalidated.
5069 * @param always Whether to remember this choice in the future.
5070 *
5071 * @hide
5072 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005073 @SystemApi(client = MODULE_LIBRARIES)
5074 @RequiresPermission(anyOf = {
5075 android.Manifest.permission.NETWORK_SETTINGS,
5076 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5077 android.Manifest.permission.NETWORK_STACK,
5078 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5079 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005080 try {
5081 mService.setAcceptUnvalidated(network, accept, always);
5082 } catch (RemoteException e) {
5083 throw e.rethrowFromSystemServer();
5084 }
5085 }
5086
5087 /**
5088 * Informs the system whether it should consider the network as validated even if it only has
5089 * partial connectivity. If {@code accept} is true, then the network will be considered as
5090 * validated even if connectivity is only partial. If {@code always} is true, then the choice
5091 * is remembered, so that the next time the user connects to this network, the system will
5092 * switch to it.
5093 *
5094 * @param network The network to accept.
5095 * @param accept Whether to consider the network as validated even if it has partial
5096 * connectivity.
5097 * @param always Whether to remember this choice in the future.
5098 *
5099 * @hide
5100 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005101 @SystemApi(client = MODULE_LIBRARIES)
5102 @RequiresPermission(anyOf = {
5103 android.Manifest.permission.NETWORK_SETTINGS,
5104 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5105 android.Manifest.permission.NETWORK_STACK,
5106 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5107 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5108 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005109 try {
5110 mService.setAcceptPartialConnectivity(network, accept, always);
5111 } catch (RemoteException e) {
5112 throw e.rethrowFromSystemServer();
5113 }
5114 }
5115
5116 /**
5117 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5118 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5119 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5120 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5121 *
5122 * @param network The network to accept.
5123 *
5124 * @hide
5125 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005126 @SystemApi(client = MODULE_LIBRARIES)
5127 @RequiresPermission(anyOf = {
5128 android.Manifest.permission.NETWORK_SETTINGS,
5129 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5130 android.Manifest.permission.NETWORK_STACK,
5131 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5132 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005133 try {
5134 mService.setAvoidUnvalidated(network);
5135 } catch (RemoteException e) {
5136 throw e.rethrowFromSystemServer();
5137 }
5138 }
5139
5140 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005141 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005142 *
5143 * @param timeMs The expired current time. The value should be set within a limited time from
5144 * now.
5145 *
5146 * @hide
5147 */
5148 public void setTestAllowBadWifiUntil(long timeMs) {
5149 try {
5150 mService.setTestAllowBadWifiUntil(timeMs);
5151 } catch (RemoteException e) {
5152 throw e.rethrowFromSystemServer();
5153 }
5154 }
5155
5156 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005157 * Requests that the system open the captive portal app on the specified network.
5158 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005159 * <p>This is to be used on networks where a captive portal was detected, as per
5160 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5161 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005162 * @param network The network to log into.
5163 *
5164 * @hide
5165 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005166 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5167 @RequiresPermission(anyOf = {
5168 android.Manifest.permission.NETWORK_SETTINGS,
5169 android.Manifest.permission.NETWORK_STACK,
5170 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5171 })
5172 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005173 try {
5174 mService.startCaptivePortalApp(network);
5175 } catch (RemoteException e) {
5176 throw e.rethrowFromSystemServer();
5177 }
5178 }
5179
5180 /**
5181 * Requests that the system open the captive portal app with the specified extras.
5182 *
5183 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5184 * corresponding permission.
5185 * @param network Network on which the captive portal was detected.
5186 * @param appExtras Extras to include in the app start intent.
5187 * @hide
5188 */
5189 @SystemApi
5190 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5191 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5192 try {
5193 mService.startCaptivePortalAppInternal(network, appExtras);
5194 } catch (RemoteException e) {
5195 throw e.rethrowFromSystemServer();
5196 }
5197 }
5198
5199 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005200 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005201 * @hide
5202 */
5203 @SystemApi
5204 @RequiresPermission(anyOf = {
5205 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5206 android.Manifest.permission.NETWORK_STACK})
5207 public boolean shouldAvoidBadWifi() {
5208 try {
5209 return mService.shouldAvoidBadWifi();
5210 } catch (RemoteException e) {
5211 throw e.rethrowFromSystemServer();
5212 }
5213 }
5214
5215 /**
5216 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5217 * time-sensitive user-facing operations when the system default network is temporarily
5218 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5219 * this method), and the operation should be infrequent to ensure that data usage is limited.
5220 *
5221 * An example of such an operation might be a time-sensitive foreground activity, such as a
5222 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5223 */
5224 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5225
5226 /**
5227 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5228 * a backup channel for traffic that is primarily going over another network.
5229 *
5230 * An example might be maintaining backup connections to peers or servers for the purpose of
5231 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5232 * on backup paths should be negligible compared to the traffic on the main path.
5233 */
5234 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5235
5236 /**
5237 * It is acceptable to use metered data to improve network latency and performance.
5238 */
5239 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5240
5241 /**
5242 * Return value to use for unmetered networks. On such networks we currently set all the flags
5243 * to true.
5244 * @hide
5245 */
5246 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5247 MULTIPATH_PREFERENCE_HANDOVER |
5248 MULTIPATH_PREFERENCE_RELIABILITY |
5249 MULTIPATH_PREFERENCE_PERFORMANCE;
5250
Aaron Huangcff22942021-05-27 16:31:26 +08005251 /** @hide */
5252 @Retention(RetentionPolicy.SOURCE)
5253 @IntDef(flag = true, value = {
5254 MULTIPATH_PREFERENCE_HANDOVER,
5255 MULTIPATH_PREFERENCE_RELIABILITY,
5256 MULTIPATH_PREFERENCE_PERFORMANCE,
5257 })
5258 public @interface MultipathPreference {
5259 }
5260
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005261 /**
5262 * Provides a hint to the calling application on whether it is desirable to use the
5263 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5264 * for multipath data transfer on this network when it is not the system default network.
5265 * Applications desiring to use multipath network protocols should call this method before
5266 * each such operation.
5267 *
5268 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005269 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005270 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005271 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005272 */
5273 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5274 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5275 try {
5276 return mService.getMultipathPreference(network);
5277 } catch (RemoteException e) {
5278 throw e.rethrowFromSystemServer();
5279 }
5280 }
5281
5282 /**
5283 * Resets all connectivity manager settings back to factory defaults.
5284 * @hide
5285 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005286 @SystemApi(client = MODULE_LIBRARIES)
5287 @RequiresPermission(anyOf = {
5288 android.Manifest.permission.NETWORK_SETTINGS,
5289 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005290 public void factoryReset() {
5291 try {
5292 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005293 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005294 } catch (RemoteException e) {
5295 throw e.rethrowFromSystemServer();
5296 }
5297 }
5298
5299 /**
5300 * Binds the current process to {@code network}. All Sockets created in the future
5301 * (and not explicitly bound via a bound SocketFactory from
5302 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5303 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5304 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5305 * work and all host name resolutions will fail. This is by design so an application doesn't
5306 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5307 * To clear binding pass {@code null} for {@code network}. Using individually bound
5308 * Sockets created by Network.getSocketFactory().createSocket() and
5309 * performing network-specific host name resolutions via
5310 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5311 * {@code bindProcessToNetwork}.
5312 *
5313 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5314 * the current binding.
5315 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5316 */
5317 public boolean bindProcessToNetwork(@Nullable Network network) {
5318 // Forcing callers to call through non-static function ensures ConnectivityManager
5319 // instantiated.
5320 return setProcessDefaultNetwork(network);
5321 }
5322
5323 /**
5324 * Binds the current process to {@code network}. All Sockets created in the future
5325 * (and not explicitly bound via a bound SocketFactory from
5326 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5327 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5328 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5329 * work and all host name resolutions will fail. This is by design so an application doesn't
5330 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5331 * To clear binding pass {@code null} for {@code network}. Using individually bound
5332 * Sockets created by Network.getSocketFactory().createSocket() and
5333 * performing network-specific host name resolutions via
5334 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5335 * {@code setProcessDefaultNetwork}.
5336 *
5337 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5338 * the current binding.
5339 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5340 * @deprecated This function can throw {@link IllegalStateException}. Use
5341 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5342 * is a direct replacement.
5343 */
5344 @Deprecated
5345 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5346 int netId = (network == null) ? NETID_UNSET : network.netId;
5347 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5348
5349 if (netId != NETID_UNSET) {
5350 netId = network.getNetIdForResolv();
5351 }
5352
5353 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5354 return false;
5355 }
5356
5357 if (!isSameNetId) {
5358 // Set HTTP proxy system properties to match network.
5359 // TODO: Deprecate this static method and replace it with a non-static version.
5360 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005361 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005362 } catch (SecurityException e) {
5363 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5364 Log.e(TAG, "Can't set proxy properties", e);
5365 }
5366 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005367 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005368 // Must flush socket pool as idle sockets will be bound to previous network and may
5369 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005370 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005371 }
5372
5373 return true;
5374 }
5375
5376 /**
5377 * Returns the {@link Network} currently bound to this process via
5378 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5379 *
5380 * @return {@code Network} to which this process is bound, or {@code null}.
5381 */
5382 @Nullable
5383 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005384 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005385 // instantiated.
5386 return getProcessDefaultNetwork();
5387 }
5388
5389 /**
5390 * Returns the {@link Network} currently bound to this process via
5391 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5392 *
5393 * @return {@code Network} to which this process is bound, or {@code null}.
5394 * @deprecated Using this function can lead to other functions throwing
5395 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5396 * {@code getBoundNetworkForProcess} is a direct replacement.
5397 */
5398 @Deprecated
5399 @Nullable
5400 public static Network getProcessDefaultNetwork() {
5401 int netId = NetworkUtils.getBoundNetworkForProcess();
5402 if (netId == NETID_UNSET) return null;
5403 return new Network(netId);
5404 }
5405
5406 private void unsupportedStartingFrom(int version) {
5407 if (Process.myUid() == Process.SYSTEM_UID) {
5408 // The getApplicationInfo() call we make below is not supported in system context. Let
5409 // the call through here, and rely on the fact that ConnectivityService will refuse to
5410 // allow the system to use these APIs anyway.
5411 return;
5412 }
5413
5414 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5415 throw new UnsupportedOperationException(
5416 "This method is not supported in target SDK version " + version + " and above");
5417 }
5418 }
5419
5420 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5421 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5422 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5423 // remove these exemptions. Note that this check is not secure, and apps can still access these
5424 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5425 // so is unsupported and may break in the future. http://b/22728205
5426 private void checkLegacyRoutingApiAccess() {
5427 unsupportedStartingFrom(VERSION_CODES.M);
5428 }
5429
5430 /**
5431 * Binds host resolutions performed by this process to {@code network}.
5432 * {@link #bindProcessToNetwork} takes precedence over this setting.
5433 *
5434 * @param network The {@link Network} to bind host resolutions from the current process to, or
5435 * {@code null} to clear the current binding.
5436 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5437 * @hide
5438 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5439 */
5440 @Deprecated
5441 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5442 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5443 return NetworkUtils.bindProcessToNetworkForHostResolution(
5444 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5445 }
5446
5447 /**
5448 * Device is not restricting metered network activity while application is running on
5449 * background.
5450 */
5451 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5452
5453 /**
5454 * Device is restricting metered network activity while application is running on background,
5455 * but application is allowed to bypass it.
5456 * <p>
5457 * In this state, application should take action to mitigate metered network access.
5458 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5459 */
5460 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5461
5462 /**
5463 * Device is restricting metered network activity while application is running on background.
5464 * <p>
5465 * In this state, application should not try to use the network while running on background,
5466 * because it would be denied.
5467 */
5468 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5469
5470 /**
5471 * A change in the background metered network activity restriction has occurred.
5472 * <p>
5473 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5474 * applies to them.
5475 * <p>
5476 * This is only sent to registered receivers, not manifest receivers.
5477 */
5478 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5479 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5480 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5481
Aaron Huangcff22942021-05-27 16:31:26 +08005482 /** @hide */
5483 @Retention(RetentionPolicy.SOURCE)
5484 @IntDef(flag = false, value = {
5485 RESTRICT_BACKGROUND_STATUS_DISABLED,
5486 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5487 RESTRICT_BACKGROUND_STATUS_ENABLED,
5488 })
5489 public @interface RestrictBackgroundStatus {
5490 }
5491
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005492 /**
5493 * Determines if the calling application is subject to metered network restrictions while
5494 * running on background.
5495 *
5496 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5497 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5498 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5499 */
5500 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5501 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005502 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005503 } catch (RemoteException e) {
5504 throw e.rethrowFromSystemServer();
5505 }
5506 }
5507
5508 /**
5509 * The network watchlist is a list of domains and IP addresses that are associated with
5510 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5511 * currently used by the system for validation purposes.
5512 *
5513 * @return Hash of network watchlist config file. Null if config does not exist.
5514 */
5515 @Nullable
5516 public byte[] getNetworkWatchlistConfigHash() {
5517 try {
5518 return mService.getNetworkWatchlistConfigHash();
5519 } catch (RemoteException e) {
5520 Log.e(TAG, "Unable to get watchlist config hash");
5521 throw e.rethrowFromSystemServer();
5522 }
5523 }
5524
5525 /**
5526 * Returns the {@code uid} of the owner of a network connection.
5527 *
5528 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5529 * IPPROTO_UDP} currently supported.
5530 * @param local The local {@link InetSocketAddress} of a connection.
5531 * @param remote The remote {@link InetSocketAddress} of a connection.
5532 * @return {@code uid} if the connection is found and the app has permission to observe it
5533 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5534 * android.os.Process#INVALID_UID} if the connection is not found.
Sherri Lin443b7182023-02-08 04:49:29 +01005535 * @throws SecurityException if the caller is not the active VpnService for the current
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005536 * user.
Sherri Lin443b7182023-02-08 04:49:29 +01005537 * @throws IllegalArgumentException if an unsupported protocol is requested.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005538 */
5539 public int getConnectionOwnerUid(
5540 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5541 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5542 try {
5543 return mService.getConnectionOwnerUid(connectionInfo);
5544 } catch (RemoteException e) {
5545 throw e.rethrowFromSystemServer();
5546 }
5547 }
5548
5549 private void printStackTrace() {
5550 if (DEBUG) {
5551 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5552 final StringBuffer sb = new StringBuffer();
5553 for (int i = 3; i < callStack.length; i++) {
5554 final String stackTrace = callStack[i].toString();
5555 if (stackTrace == null || stackTrace.contains("android.os")) {
5556 break;
5557 }
5558 sb.append(" [").append(stackTrace).append("]");
5559 }
5560 Log.d(TAG, "StackLog:" + sb.toString());
5561 }
5562 }
5563
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005564 /** @hide */
5565 public TestNetworkManager startOrGetTestNetworkManager() {
5566 final IBinder tnBinder;
5567 try {
5568 tnBinder = mService.startOrGetTestNetworkService();
5569 } catch (RemoteException e) {
5570 throw e.rethrowFromSystemServer();
5571 }
5572
5573 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5574 }
5575
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005576 /** @hide */
5577 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5578 return new ConnectivityDiagnosticsManager(mContext, mService);
5579 }
5580
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005581 /**
5582 * Simulates a Data Stall for the specified Network.
5583 *
5584 * <p>This method should only be used for tests.
5585 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005586 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5587 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005588 *
5589 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005590 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5591 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5592 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005593 * @param network The Network for which a Data Stall is being simluated.
5594 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5595 * @throws SecurityException if the caller is not the owner of the given network.
5596 * @hide
5597 */
5598 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5599 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5600 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005601 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005602 @NonNull Network network, @NonNull PersistableBundle extras) {
5603 try {
5604 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5605 } catch (RemoteException e) {
5606 e.rethrowFromSystemServer();
5607 }
5608 }
5609
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005610 @NonNull
5611 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5612
5613 /**
5614 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5615 * receive available QoS events related to the {@link Network} and local ip + port
5616 * specified within socketInfo.
5617 * <p/>
5618 * The same {@link QosCallback} must be unregistered before being registered a second time,
5619 * otherwise {@link QosCallbackRegistrationException} is thrown.
5620 * <p/>
5621 * This API does not, in itself, require any permission if called with a network that is not
5622 * restricted. However, the underlying implementation currently only supports the IMS network,
5623 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5624 * useful, because they'd never be called back on networks that they would have access to.
5625 *
5626 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5627 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5628 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5629 * @throws RuntimeException if the app already has too many callbacks registered.
5630 *
5631 * Exceptions after the time of registration is passed through
5632 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5633 *
5634 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005635 * @param executor The executor on which the callback will be invoked. The provided
5636 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005637 * callbacks cannot be guaranteed.onQosCallbackRegistered
5638 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005639 *
5640 * @hide
5641 */
5642 @SystemApi
5643 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005644 @CallbackExecutor @NonNull final Executor executor,
5645 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005646 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005647 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005648 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005649
5650 try {
5651 synchronized (mQosCallbackConnections) {
5652 if (getQosCallbackConnection(callback) == null) {
5653 final QosCallbackConnection connection =
5654 new QosCallbackConnection(this, callback, executor);
5655 mQosCallbackConnections.add(connection);
5656 mService.registerQosSocketCallback(socketInfo, connection);
5657 } else {
5658 Log.e(TAG, "registerQosCallback: Callback already registered");
5659 throw new QosCallbackRegistrationException();
5660 }
5661 }
5662 } catch (final RemoteException e) {
5663 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5664
5665 // The same unregister method method is called for consistency even though nothing
5666 // will be sent to the ConnectivityService since the callback was never successfully
5667 // registered.
5668 unregisterQosCallback(callback);
5669 e.rethrowFromSystemServer();
5670 } catch (final ServiceSpecificException e) {
5671 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5672 unregisterQosCallback(callback);
5673 throw convertServiceException(e);
5674 }
5675 }
5676
5677 /**
5678 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5679 * events once unregistered and can be registered a second time.
5680 * <p/>
5681 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5682 *
5683 * @param callback the callback being unregistered
5684 *
5685 * @hide
5686 */
5687 @SystemApi
5688 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5689 Objects.requireNonNull(callback, "The callback must be non-null");
5690 try {
5691 synchronized (mQosCallbackConnections) {
5692 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5693 if (connection != null) {
5694 connection.stopReceivingMessages();
5695 mService.unregisterQosCallback(connection);
5696 mQosCallbackConnections.remove(connection);
5697 } else {
5698 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5699 }
5700 }
5701 } catch (final RemoteException e) {
5702 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5703 e.rethrowFromSystemServer();
5704 }
5705 }
5706
5707 /**
5708 * Gets the connection related to the callback.
5709 *
5710 * @param callback the callback to look up
5711 * @return the related connection
5712 */
5713 @Nullable
5714 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5715 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5716 // Checking by reference here is intentional
5717 if (connection.getCallback() == callback) {
5718 return connection;
5719 }
5720 }
5721 return null;
5722 }
5723
5724 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005725 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005726 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5727 * be used to request that the system provide a network without causing the network to be
5728 * in the foreground.
5729 *
5730 * <p>This method will attempt to find the best network that matches the passed
5731 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5732 * criteria. The platform will evaluate which network is the best at its own discretion.
5733 * Throughput, latency, cost per byte, policy, user preference and other considerations
5734 * may be factored in the decision of what is considered the best network.
5735 *
5736 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5737 * matching this request, while always attempting to match the request to a better network if
5738 * possible. If a better match is found, the platform will switch this request to the now-best
5739 * network and inform the app of the newly best network by invoking
5740 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5741 * will not try to maintain any other network than the best one currently matching the request:
5742 * a network not matching any network request may be disconnected at any time.
5743 *
5744 * <p>For example, an application could use this method to obtain a connected cellular network
5745 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5746 * radio to consume additional power. Or, an application could inform the system that it wants
5747 * a network supporting sending MMSes and have the system let it know about the currently best
5748 * MMS-supporting network through the provided {@link NetworkCallback}.
5749 *
5750 * <p>The status of the request can be followed by listening to the various callbacks described
5751 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5752 * used to direct traffic to the network (although accessing some networks may be subject to
5753 * holding specific permissions). Callers will learn about the specific characteristics of the
5754 * network through
5755 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5756 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5757 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5758 * matching the request at any given time; therefore when a better network matching the request
5759 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5760 * with the new network after which no further updates are given about the previously-best
5761 * network, unless it becomes the best again at some later time. All callbacks are invoked
5762 * in order on the same thread, which by default is a thread created by the framework running
5763 * in the app.
5764 *
5765 * <p>This{@link NetworkRequest} will live until released via
5766 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5767 * which point the system may let go of the network at any time.
5768 *
5769 * <p>It is presently unsupported to request a network with mutable
5770 * {@link NetworkCapabilities} such as
5771 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5772 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5773 * as these {@code NetworkCapabilities} represent states that a particular
5774 * network may never attain, and whether a network will attain these states
5775 * is unknown prior to bringing up the network so the framework does not
5776 * know how to go about satisfying a request with these capabilities.
5777 *
5778 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5779 * number of outstanding requests to 100 per app (identified by their UID), shared with
5780 * all variants of this method, of {@link #registerNetworkCallback} as well as
5781 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5782 * Requesting a network with this method will count toward this limit. If this limit is
5783 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5784 * make sure to unregister the callbacks with
5785 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5786 *
5787 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005788 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5789 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005790 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5791 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005792 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5793 * @throws SecurityException if missing the appropriate permissions.
5794 * @throws RuntimeException if the app already has too many callbacks registered.
5795 *
5796 * @hide
5797 */
5798 @SystemApi(client = MODULE_LIBRARIES)
5799 @SuppressLint("ExecutorRegistration")
5800 @RequiresPermission(anyOf = {
5801 android.Manifest.permission.NETWORK_SETTINGS,
5802 android.Manifest.permission.NETWORK_STACK,
5803 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5804 })
5805 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005806 @NonNull NetworkCallback networkCallback,
5807 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005808 final NetworkCapabilities nc = request.networkCapabilities;
5809 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005810 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005811 }
James Mattis12aeab82021-01-10 14:24:24 -08005812
5813 /**
James Mattis12aeab82021-01-10 14:24:24 -08005814 * Used by automotive devices to set the network preferences used to direct traffic at an
5815 * application level as per the given OemNetworkPreferences. An example use-case would be an
5816 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5817 * vehicle via a particular network.
5818 *
5819 * Calling this will overwrite the existing preference.
5820 *
5821 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5822 * @param executor the executor on which listener will be invoked.
5823 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5824 * communicate completion of setOemNetworkPreference(). This will only be
5825 * called once upon successful completion of setOemNetworkPreference().
5826 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5827 * @throws SecurityException if missing the appropriate permissions.
5828 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005829 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005830 */
James Mattis6e2d7022021-01-26 16:23:52 -08005831 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005832 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005833 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005834 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005835 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005836 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5837 if (null != listener) {
5838 Objects.requireNonNull(executor, "Executor must be non-null");
5839 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005840 final IOnCompleteListener listenerInternal = listener == null ? null :
5841 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005842 @Override
5843 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005844 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005845 }
5846 };
5847
5848 try {
5849 mService.setOemNetworkPreference(preference, listenerInternal);
5850 } catch (RemoteException e) {
5851 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5852 throw e.rethrowFromSystemServer();
5853 }
5854 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005855
Chalard Jeanad565e22021-02-25 17:23:40 +09005856 /**
5857 * Request that a user profile is put by default on a network matching a given preference.
5858 *
5859 * See the documentation for the individual preferences for a description of the supported
5860 * behaviors.
5861 *
5862 * @param profile the profile concerned.
5863 * @param preference the preference for this profile.
5864 * @param executor an executor to execute the listener on. Optional if listener is null.
5865 * @param listener an optional listener to listen for completion of the operation.
5866 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5867 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005868 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5869 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005870 * @hide
5871 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005872 // This function is for establishing per-profile default networking and can only be called by
5873 // the device policy manager, running as the system server. It would make no sense to call it
5874 // on a context for a user because it does not establish a setting on behalf of a user, rather
5875 // it establishes a setting for a user on behalf of the DPM.
5876 @SuppressLint({"UserHandle"})
5877 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005878 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005879 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005880 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005881 @ProfileNetworkPreferencePolicy final int preference,
5882 @Nullable @CallbackExecutor final Executor executor,
5883 @Nullable final Runnable listener) {
5884
5885 ProfileNetworkPreference.Builder preferenceBuilder =
5886 new ProfileNetworkPreference.Builder();
5887 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005888 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5889 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5890 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005891 setProfileNetworkPreferences(profile,
5892 List.of(preferenceBuilder.build()), executor, listener);
5893 }
5894
5895 /**
5896 * Set a list of default network selection policies for a user profile.
5897 *
5898 * Calling this API with a user handle defines the entire policy for that user handle.
5899 * It will overwrite any setting previously set for the same user profile,
5900 * and not affect previously set settings for other handles.
5901 *
5902 * Call this API with an empty list to remove settings for this user profile.
5903 *
5904 * See {@link ProfileNetworkPreference} for more details on each preference
5905 * parameter.
5906 *
5907 * @param profile the user profile for which the preference is being set.
5908 * @param profileNetworkPreferences the list of profile network preferences for the
5909 * provided profile.
5910 * @param executor an executor to execute the listener on. Optional if listener is null.
5911 * @param listener an optional listener to listen for completion of the operation.
5912 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5913 * @throws SecurityException if missing the appropriate permissions.
5914 * @hide
5915 */
5916 @SystemApi(client = MODULE_LIBRARIES)
5917 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5918 public void setProfileNetworkPreferences(
5919 @NonNull final UserHandle profile,
5920 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005921 @Nullable @CallbackExecutor final Executor executor,
5922 @Nullable final Runnable listener) {
5923 if (null != listener) {
5924 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5925 }
5926 final IOnCompleteListener proxy;
5927 if (null == listener) {
5928 proxy = null;
5929 } else {
5930 proxy = new IOnCompleteListener.Stub() {
5931 @Override
5932 public void onComplete() {
5933 executor.execute(listener::run);
5934 }
5935 };
5936 }
5937 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005938 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005939 } catch (RemoteException e) {
5940 throw e.rethrowFromSystemServer();
5941 }
5942 }
5943
lucaslin5cdbcfb2021-03-12 00:46:33 +08005944 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005945 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005946 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005947 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005948
5949 /**
5950 * Get the network ID range reserved for IPSec tunnel interfaces.
5951 *
5952 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5953 * @hide
5954 */
5955 @SystemApi(client = MODULE_LIBRARIES)
5956 @NonNull
5957 public static Range<Integer> getIpSecNetIdRange() {
5958 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5959 }
markchien738ad912021-12-09 18:15:45 +08005960
5961 /**
markchiene46042b2022-03-02 18:07:35 +08005962 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5963 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005964 *
5965 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005966 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005967 * @hide
5968 */
5969 @SystemApi(client = MODULE_LIBRARIES)
5970 @RequiresPermission(anyOf = {
5971 android.Manifest.permission.NETWORK_SETTINGS,
5972 android.Manifest.permission.NETWORK_STACK,
5973 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5974 })
markchiene46042b2022-03-02 18:07:35 +08005975 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005976 try {
markchiene46042b2022-03-02 18:07:35 +08005977 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08005978 } catch (RemoteException e) {
5979 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005980 }
5981 }
5982
5983 /**
markchiene46042b2022-03-02 18:07:35 +08005984 * Removes the specified UID from the list of UIDs that are allowed to use background data on
5985 * metered networks when background data is restricted. The deny list takes precedence over
5986 * the allow list.
5987 *
5988 * @param uid uid of target app
5989 * @throws IllegalStateException if updating allow list failed.
5990 * @hide
5991 */
5992 @SystemApi(client = MODULE_LIBRARIES)
5993 @RequiresPermission(anyOf = {
5994 android.Manifest.permission.NETWORK_SETTINGS,
5995 android.Manifest.permission.NETWORK_STACK,
5996 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5997 })
5998 public void removeUidFromMeteredNetworkAllowList(final int uid) {
5999 try {
6000 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
6001 } catch (RemoteException e) {
6002 throw e.rethrowFromSystemServer();
6003 }
6004 }
6005
6006 /**
6007 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
6008 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08006009 *
6010 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006011 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08006012 * @hide
6013 */
6014 @SystemApi(client = MODULE_LIBRARIES)
6015 @RequiresPermission(anyOf = {
6016 android.Manifest.permission.NETWORK_SETTINGS,
6017 android.Manifest.permission.NETWORK_STACK,
6018 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6019 })
markchiene46042b2022-03-02 18:07:35 +08006020 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006021 try {
markchiene46042b2022-03-02 18:07:35 +08006022 mService.updateMeteredNetworkDenyList(uid, true /* add */);
6023 } catch (RemoteException e) {
6024 throw e.rethrowFromSystemServer();
6025 }
6026 }
6027
6028 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09006029 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08006030 * networks if background data is not restricted. The deny list takes precedence over the
6031 * allow list.
6032 *
6033 * @param uid uid of target app
6034 * @throws IllegalStateException if updating deny list failed.
6035 * @hide
6036 */
6037 @SystemApi(client = MODULE_LIBRARIES)
6038 @RequiresPermission(anyOf = {
6039 android.Manifest.permission.NETWORK_SETTINGS,
6040 android.Manifest.permission.NETWORK_STACK,
6041 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6042 })
6043 public void removeUidFromMeteredNetworkDenyList(final int uid) {
6044 try {
6045 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08006046 } catch (RemoteException e) {
6047 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08006048 }
6049 }
6050
6051 /**
6052 * Sets a firewall rule for the specified UID on the specified chain.
6053 *
6054 * @param chain target chain.
6055 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08006056 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08006057 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08006058 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08006059 * @hide
6060 */
6061 @SystemApi(client = MODULE_LIBRARIES)
6062 @RequiresPermission(anyOf = {
6063 android.Manifest.permission.NETWORK_SETTINGS,
6064 android.Manifest.permission.NETWORK_STACK,
6065 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6066 })
markchien3c04e662022-03-22 16:29:56 +08006067 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
6068 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08006069 try {
markchien3c04e662022-03-22 16:29:56 +08006070 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08006071 } catch (RemoteException e) {
6072 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006073 }
6074 }
markchien98a6f952022-01-13 23:43:53 +08006075
6076 /**
Motomu Utsumi900b8062023-01-19 16:16:49 +09006077 * Get firewall rule of specified firewall chain on specified uid.
6078 *
6079 * @param chain target chain.
6080 * @param uid target uid
6081 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
6082 * @throws UnsupportedOperationException if called on pre-T devices.
6083 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6084 * cause of the failure.
6085 * @hide
6086 */
6087 @RequiresPermission(anyOf = {
6088 android.Manifest.permission.NETWORK_SETTINGS,
6089 android.Manifest.permission.NETWORK_STACK,
6090 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6091 })
6092 public int getUidFirewallRule(@FirewallChain final int chain, final int uid) {
6093 try {
6094 return mService.getUidFirewallRule(chain, uid);
6095 } catch (RemoteException e) {
6096 throw e.rethrowFromSystemServer();
6097 }
6098 }
6099
6100 /**
markchien98a6f952022-01-13 23:43:53 +08006101 * Enables or disables the specified firewall chain.
6102 *
6103 * @param chain target chain.
6104 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00006105 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08006106 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08006107 * @hide
6108 */
6109 @SystemApi(client = MODULE_LIBRARIES)
6110 @RequiresPermission(anyOf = {
6111 android.Manifest.permission.NETWORK_SETTINGS,
6112 android.Manifest.permission.NETWORK_STACK,
6113 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6114 })
6115 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
6116 try {
6117 mService.setFirewallChainEnabled(chain, enable);
6118 } catch (RemoteException e) {
6119 throw e.rethrowFromSystemServer();
6120 }
6121 }
markchien00a0bed2022-01-13 23:46:13 +08006122
6123 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00006124 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006125 *
6126 * @param chain target chain.
6127 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6128 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006129 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6130 * cause of the failure.
6131 * @hide
6132 */
6133 @RequiresPermission(anyOf = {
6134 android.Manifest.permission.NETWORK_SETTINGS,
6135 android.Manifest.permission.NETWORK_STACK,
6136 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6137 })
6138 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6139 try {
6140 return mService.getFirewallChainEnabled(chain);
6141 } catch (RemoteException e) {
6142 throw e.rethrowFromSystemServer();
6143 }
6144 }
6145
6146 /**
markchien00a0bed2022-01-13 23:46:13 +08006147 * Replaces the contents of the specified UID-based firewall chain.
6148 *
6149 * @param chain target chain to replace.
6150 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006151 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006152 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6153 * @hide
6154 */
6155 @SystemApi(client = MODULE_LIBRARIES)
6156 @RequiresPermission(anyOf = {
6157 android.Manifest.permission.NETWORK_SETTINGS,
6158 android.Manifest.permission.NETWORK_STACK,
6159 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6160 })
6161 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6162 Objects.requireNonNull(uids);
6163 try {
6164 mService.replaceFirewallChain(chain, uids);
6165 } catch (RemoteException e) {
6166 throw e.rethrowFromSystemServer();
6167 }
6168 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006169
6170 /** @hide */
6171 public IBinder getCompanionDeviceManagerProxyService() {
6172 try {
6173 return mService.getCompanionDeviceManagerProxyService();
6174 } catch (RemoteException e) {
6175 throw e.rethrowFromSystemServer();
6176 }
6177 }
Chalard Jean2fb66f12023-08-25 12:50:37 +09006178
6179 private static final Object sRoutingCoordinatorManagerLock = new Object();
6180 @GuardedBy("sRoutingCoordinatorManagerLock")
6181 private static RoutingCoordinatorManager sRoutingCoordinatorManager = null;
6182 /** @hide */
6183 @RequiresApi(Build.VERSION_CODES.S)
6184 public RoutingCoordinatorManager getRoutingCoordinatorManager() {
6185 try {
6186 synchronized (sRoutingCoordinatorManagerLock) {
6187 if (null == sRoutingCoordinatorManager) {
6188 sRoutingCoordinatorManager = new RoutingCoordinatorManager(mContext,
6189 IRoutingCoordinator.Stub.asInterface(
6190 mService.getRoutingCoordinatorService()));
6191 }
6192 return sRoutingCoordinatorManager;
6193 }
6194 } catch (RemoteException e) {
6195 throw e.rethrowFromSystemServer();
6196 }
6197 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006198}