blob: 4224da98ddd27054a32be5f7c4f9785a1b659816 [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;
32import android.annotation.RequiresPermission;
33import android.annotation.SdkConstant;
34import android.annotation.SdkConstant.SdkConstantType;
35import android.annotation.SuppressLint;
36import android.annotation.SystemApi;
37import android.annotation.SystemService;
38import android.app.PendingIntent;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090039import android.app.admin.DevicePolicyManager;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090040import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090041import android.content.ComponentName;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090042import android.content.Context;
43import android.content.Intent;
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +090044import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090045import android.net.IpSecManager.UdpEncapsulationSocket;
46import android.net.SocketKeepalive.Callback;
47import android.net.TetheringManager.StartTetheringCallback;
48import android.net.TetheringManager.TetheringEventCallback;
49import android.net.TetheringManager.TetheringRequest;
50import android.os.Binder;
51import android.os.Build;
52import android.os.Build.VERSION_CODES;
53import android.os.Bundle;
54import android.os.Handler;
55import android.os.IBinder;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090056import android.os.Looper;
57import android.os.Message;
58import android.os.Messenger;
59import android.os.ParcelFileDescriptor;
60import android.os.PersistableBundle;
61import android.os.Process;
62import android.os.RemoteException;
63import android.os.ResultReceiver;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090064import android.os.ServiceSpecificException;
Chalard Jeanad565e22021-02-25 17:23:40 +090065import android.os.UserHandle;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090066import android.provider.Settings;
67import android.telephony.SubscriptionManager;
68import android.telephony.TelephonyManager;
69import android.util.ArrayMap;
70import android.util.Log;
71import android.util.Range;
72import android.util.SparseIntArray;
73
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090074import com.android.internal.annotations.GuardedBy;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090075
76import libcore.net.event.NetworkEventDispatcher;
77
78import java.io.IOException;
79import java.io.UncheckedIOException;
80import java.lang.annotation.Retention;
81import java.lang.annotation.RetentionPolicy;
82import java.net.DatagramSocket;
83import java.net.InetAddress;
84import java.net.InetSocketAddress;
85import java.net.Socket;
86import java.util.ArrayList;
87import java.util.Collection;
88import java.util.HashMap;
89import java.util.List;
90import java.util.Map;
91import java.util.Objects;
92import java.util.concurrent.Executor;
93import java.util.concurrent.ExecutorService;
94import java.util.concurrent.Executors;
95import java.util.concurrent.RejectedExecutionException;
96
97/**
98 * Class that answers queries about the state of network connectivity. It also
99 * notifies applications when network connectivity changes.
100 * <p>
101 * The primary responsibilities of this class are to:
102 * <ol>
103 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
104 * <li>Send broadcast intents when network connectivity changes</li>
105 * <li>Attempt to "fail over" to another network when connectivity to a network
106 * is lost</li>
107 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
108 * state of the available networks</li>
109 * <li>Provide an API that allows applications to request and select networks for their data
110 * traffic</li>
111 * </ol>
112 */
113@SystemService(Context.CONNECTIVITY_SERVICE)
114public class ConnectivityManager {
115 private static final String TAG = "ConnectivityManager";
116 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
117
118 /**
119 * A change in network connectivity has occurred. A default connection has either
120 * been established or lost. The NetworkInfo for the affected network is
121 * sent as an extra; it should be consulted to see what kind of
122 * connectivity event occurred.
123 * <p/>
124 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
125 * broadcast if they declare the broadcast receiver in their manifest. Apps
126 * will still receive broadcasts if they register their
127 * {@link android.content.BroadcastReceiver} with
128 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
129 * and that context is still valid.
130 * <p/>
131 * If this is a connection that was the result of failing over from a
132 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
133 * set to true.
134 * <p/>
135 * For a loss of connectivity, if the connectivity manager is attempting
136 * to connect (or has already connected) to another network, the
137 * NetworkInfo for the new network is also passed as an extra. This lets
138 * any receivers of the broadcast know that they should not necessarily
139 * tell the user that no data traffic will be possible. Instead, the
140 * receiver should expect another broadcast soon, indicating either that
141 * the failover attempt succeeded (and so there is still overall data
142 * connectivity), or that the failover attempt failed, meaning that all
143 * connectivity has been lost.
144 * <p/>
145 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
146 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900147 * <p />
148 * Note that this broadcast is deprecated and generally tries to implement backwards
149 * compatibility with older versions of Android. As such, it may not reflect new
150 * capabilities of the system, like multiple networks being connected at the same
151 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900152 *
153 * @deprecated apps should use the more versatile {@link #requestNetwork},
154 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
155 * functions instead for faster and more detailed updates about the network
156 * changes they care about.
157 */
158 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
159 @Deprecated
160 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
161
162 /**
163 * The device has connected to a network that has presented a captive
164 * portal, which is blocking Internet connectivity. The user was presented
165 * with a notification that network sign in is required,
166 * and the user invoked the notification's action indicating they
167 * desire to sign in to the network. Apps handling this activity should
168 * facilitate signing in to the network. This action includes a
169 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
170 * the network presenting the captive portal; all communication with the
171 * captive portal must be done using this {@code Network} object.
172 * <p/>
173 * This activity includes a {@link CaptivePortal} extra named
174 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
175 * outcomes of the captive portal sign in to the system:
176 * <ul>
177 * <li> When the app handling this action believes the user has signed in to
178 * the network and the captive portal has been dismissed, the app should
179 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
180 * reevaluate the network. If reevaluation finds the network no longer
181 * subject to a captive portal, the network may become the default active
182 * data network.</li>
183 * <li> When the app handling this action believes the user explicitly wants
184 * to ignore the captive portal and the network, the app should call
185 * {@link CaptivePortal#ignoreNetwork}. </li>
186 * </ul>
187 */
188 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
189 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
190
191 /**
192 * The lookup key for a {@link NetworkInfo} object. Retrieve with
193 * {@link android.content.Intent#getParcelableExtra(String)}.
194 *
195 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
196 * can't accurately represent modern network characteristics.
197 * Please obtain information about networks from the {@link NetworkCapabilities}
198 * or {@link LinkProperties} objects instead.
199 */
200 @Deprecated
201 public static final String EXTRA_NETWORK_INFO = "networkInfo";
202
203 /**
204 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
205 *
206 * @see android.content.Intent#getIntExtra(String, int)
207 * @deprecated The network type is not rich enough to represent the characteristics
208 * of modern networks. Please use {@link NetworkCapabilities} instead,
209 * in particular the transports.
210 */
211 @Deprecated
212 public static final String EXTRA_NETWORK_TYPE = "networkType";
213
214 /**
215 * The lookup key for a boolean that indicates whether a connect event
216 * is for a network to which the connectivity manager was failing over
217 * following a disconnect on another network.
218 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
219 *
220 * @deprecated See {@link NetworkInfo}.
221 */
222 @Deprecated
223 public static final String EXTRA_IS_FAILOVER = "isFailover";
224 /**
225 * The lookup key for a {@link NetworkInfo} object. This is supplied when
226 * there is another network that it may be possible to connect to. Retrieve with
227 * {@link android.content.Intent#getParcelableExtra(String)}.
228 *
229 * @deprecated See {@link NetworkInfo}.
230 */
231 @Deprecated
232 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
233 /**
234 * The lookup key for a boolean that indicates whether there is a
235 * complete lack of connectivity, i.e., no network is available.
236 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
237 */
238 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
239 /**
240 * The lookup key for a string that indicates why an attempt to connect
241 * to a network failed. The string has no particular structure. It is
242 * intended to be used in notifications presented to users. Retrieve
243 * it with {@link android.content.Intent#getStringExtra(String)}.
244 */
245 public static final String EXTRA_REASON = "reason";
246 /**
247 * The lookup key for a string that provides optionally supplied
248 * extra information about the network state. The information
249 * may be passed up from the lower networking layers, and its
250 * meaning may be specific to a particular network type. Retrieve
251 * it with {@link android.content.Intent#getStringExtra(String)}.
252 *
253 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
254 */
255 @Deprecated
256 public static final String EXTRA_EXTRA_INFO = "extraInfo";
257 /**
258 * The lookup key for an int that provides information about
259 * our connection to the internet at large. 0 indicates no connection,
260 * 100 indicates a great connection. Retrieve it with
261 * {@link android.content.Intent#getIntExtra(String, int)}.
262 * {@hide}
263 */
264 public static final String EXTRA_INET_CONDITION = "inetCondition";
265 /**
266 * The lookup key for a {@link CaptivePortal} object included with the
267 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
268 * object can be used to either indicate to the system that the captive
269 * portal has been dismissed or that the user does not want to pursue
270 * signing in to captive portal. Retrieve it with
271 * {@link android.content.Intent#getParcelableExtra(String)}.
272 */
273 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
274
275 /**
276 * Key for passing a URL to the captive portal login activity.
277 */
278 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
279
280 /**
281 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
282 * portal login activity.
283 * {@hide}
284 */
285 @SystemApi
286 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
287 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
288
289 /**
290 * Key for passing a user agent string to the captive portal login activity.
291 * {@hide}
292 */
293 @SystemApi
294 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
295 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
296
297 /**
298 * Broadcast action to indicate the change of data activity status
299 * (idle or active) on a network in a recent period.
300 * The network becomes active when data transmission is started, or
301 * idle if there is no data transmission for a period of time.
302 * {@hide}
303 */
304 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
305 public static final String ACTION_DATA_ACTIVITY_CHANGE =
306 "android.net.conn.DATA_ACTIVITY_CHANGE";
307 /**
308 * The lookup key for an enum that indicates the network device type on which this data activity
309 * change happens.
310 * {@hide}
311 */
312 public static final String EXTRA_DEVICE_TYPE = "deviceType";
313 /**
314 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
315 * it is actively sending or receiving data and {@code false} means it is idle.
316 * {@hide}
317 */
318 public static final String EXTRA_IS_ACTIVE = "isActive";
319 /**
320 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
321 * {@hide}
322 */
323 public static final String EXTRA_REALTIME_NS = "tsNanos";
324
325 /**
326 * Broadcast Action: The setting for background data usage has changed
327 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
328 * <p>
329 * If an application uses the network in the background, it should listen
330 * for this broadcast and stop using the background data if the value is
331 * {@code false}.
332 * <p>
333 *
334 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
335 * of background data depends on several combined factors, and
336 * this broadcast is no longer sent. Instead, when background
337 * data is unavailable, {@link #getActiveNetworkInfo()} will now
338 * appear disconnected. During first boot after a platform
339 * upgrade, this broadcast will be sent once if
340 * {@link #getBackgroundDataSetting()} was {@code false} before
341 * the upgrade.
342 */
343 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
344 @Deprecated
345 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
346 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
347
348 /**
349 * Broadcast Action: The network connection may not be good
350 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
351 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
352 * the network and it's condition.
353 * @hide
354 */
355 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
356 @UnsupportedAppUsage
357 public static final String INET_CONDITION_ACTION =
358 "android.net.conn.INET_CONDITION_ACTION";
359
360 /**
361 * Broadcast Action: A tetherable connection has come or gone.
362 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
363 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
364 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
365 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
366 * the current state of tethering. Each include a list of
367 * interface names in that state (may be empty).
368 * @hide
369 */
370 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
371 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
372 public static final String ACTION_TETHER_STATE_CHANGED =
373 TetheringManager.ACTION_TETHER_STATE_CHANGED;
374
375 /**
376 * @hide
377 * gives a String[] listing all the interfaces configured for
378 * tethering and currently available for tethering.
379 */
380 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
381 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
382
383 /**
384 * @hide
385 * gives a String[] listing all the interfaces currently in local-only
386 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
387 */
388 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
389
390 /**
391 * @hide
392 * gives a String[] listing all the interfaces currently tethered
393 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
394 */
395 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
396 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
397
398 /**
399 * @hide
400 * gives a String[] listing all the interfaces we tried to tether and
401 * failed. Use {@link #getLastTetherError} to find the error code
402 * for any interfaces listed here.
403 */
404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
405 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
406
407 /**
408 * Broadcast Action: The captive portal tracker has finished its test.
409 * Sent only while running Setup Wizard, in lieu of showing a user
410 * notification.
411 * @hide
412 */
413 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
414 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
415 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
416 /**
417 * The lookup key for a boolean that indicates whether a captive portal was detected.
418 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
419 * @hide
420 */
421 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
422
423 /**
424 * Action used to display a dialog that asks the user whether to connect to a network that is
425 * not validated. This intent is used to start the dialog in settings via startActivity.
426 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800427 * This action includes a {@link Network} typed extra which is called
428 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
429 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900430 * @hide
431 */
lucaslincf6d4502021-03-04 17:09:51 +0800432 @SystemApi(client = MODULE_LIBRARIES)
433 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900434
435 /**
436 * Action used to display a dialog that asks the user whether to avoid a network that is no
437 * longer validated. This intent is used to start the dialog in settings via startActivity.
438 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800439 * This action includes a {@link Network} typed extra which is called
440 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
441 * validated.
442 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900443 * @hide
444 */
lucaslincf6d4502021-03-04 17:09:51 +0800445 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900446 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800447 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900448
449 /**
450 * Action used to display a dialog that asks the user whether to stay connected to a network
451 * that has not validated. This intent is used to start the dialog in settings via
452 * startActivity.
453 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800454 * This action includes a {@link Network} typed extra which is called
455 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
456 * connectivity.
457 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900458 * @hide
459 */
lucaslincf6d4502021-03-04 17:09:51 +0800460 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900461 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800462 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900463
464 /**
paulhub49c8422021-04-07 16:18:13 +0800465 * Clear DNS Cache Action: This is broadcast when networks have changed and old
466 * DNS entries should be cleared.
467 * @hide
468 */
469 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
470 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
471 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
472
473 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900474 * Invalid tethering type.
475 * @see #startTethering(int, boolean, OnStartTetheringCallback)
476 * @hide
477 */
478 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
479
480 /**
481 * Wifi tethering type.
482 * @see #startTethering(int, boolean, OnStartTetheringCallback)
483 * @hide
484 */
485 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900486 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900487
488 /**
489 * USB tethering type.
490 * @see #startTethering(int, boolean, OnStartTetheringCallback)
491 * @hide
492 */
493 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900494 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900495
496 /**
497 * Bluetooth tethering type.
498 * @see #startTethering(int, boolean, OnStartTetheringCallback)
499 * @hide
500 */
501 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900502 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900503
504 /**
505 * Wifi P2p tethering type.
506 * Wifi P2p tethering is set through events automatically, and don't
507 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
508 * @hide
509 */
510 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
511
512 /**
513 * Extra used for communicating with the TetherService. Includes the type of tethering to
514 * enable if any.
515 * @hide
516 */
517 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
518
519 /**
520 * Extra used for communicating with the TetherService. Includes the type of tethering for
521 * which to cancel provisioning.
522 * @hide
523 */
524 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
525
526 /**
527 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
528 * provisioning.
529 * @hide
530 */
531 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
532
533 /**
534 * Tells the TetherService to run a provision check now.
535 * @hide
536 */
537 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
538
539 /**
540 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
541 * which will receive provisioning results. Can be left empty.
542 * @hide
543 */
544 public static final String EXTRA_PROVISION_CALLBACK =
545 TetheringConstants.EXTRA_PROVISION_CALLBACK;
546
547 /**
548 * The absence of a connection type.
549 * @hide
550 */
551 @SystemApi
552 public static final int TYPE_NONE = -1;
553
554 /**
555 * A Mobile data connection. Devices may support more than one.
556 *
557 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
558 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000559 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900560 */
561 @Deprecated
562 public static final int TYPE_MOBILE = 0;
563
564 /**
565 * A WIFI data connection. Devices may support more than one.
566 *
567 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
568 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000569 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900570 */
571 @Deprecated
572 public static final int TYPE_WIFI = 1;
573
574 /**
575 * An MMS-specific Mobile data connection. This network type may use the
576 * same network interface as {@link #TYPE_MOBILE} or it may use a different
577 * one. This is used by applications needing to talk to the carrier's
578 * Multimedia Messaging Service servers.
579 *
580 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
581 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
582 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
583 */
584 @Deprecated
585 public static final int TYPE_MOBILE_MMS = 2;
586
587 /**
588 * A SUPL-specific Mobile data connection. This network type may use the
589 * same network interface as {@link #TYPE_MOBILE} or it may use a different
590 * one. This is used by applications needing to talk to the carrier's
591 * Secure User Plane Location servers for help locating the device.
592 *
593 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
594 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
595 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
596 */
597 @Deprecated
598 public static final int TYPE_MOBILE_SUPL = 3;
599
600 /**
601 * A DUN-specific Mobile data connection. This network type may use the
602 * same network interface as {@link #TYPE_MOBILE} or it may use a different
603 * one. This is sometimes by the system when setting up an upstream connection
604 * for tethering so that the carrier is aware of DUN traffic.
605 *
606 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
607 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
608 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
609 */
610 @Deprecated
611 public static final int TYPE_MOBILE_DUN = 4;
612
613 /**
614 * A High Priority Mobile data connection. This network type uses the
615 * same network interface as {@link #TYPE_MOBILE} but the routing setup
616 * is different.
617 *
618 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
619 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000620 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900621 */
622 @Deprecated
623 public static final int TYPE_MOBILE_HIPRI = 5;
624
625 /**
626 * A WiMAX data connection.
627 *
628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000630 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900631 */
632 @Deprecated
633 public static final int TYPE_WIMAX = 6;
634
635 /**
636 * A Bluetooth data connection.
637 *
638 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
639 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000640 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900641 */
642 @Deprecated
643 public static final int TYPE_BLUETOOTH = 7;
644
645 /**
646 * Fake data connection. This should not be used on shipping devices.
647 * @deprecated This is not used any more.
648 */
649 @Deprecated
650 public static final int TYPE_DUMMY = 8;
651
652 /**
653 * An Ethernet data connection.
654 *
655 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
656 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000657 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900658 */
659 @Deprecated
660 public static final int TYPE_ETHERNET = 9;
661
662 /**
663 * Over the air Administration.
664 * @deprecated Use {@link NetworkCapabilities} instead.
665 * {@hide}
666 */
667 @Deprecated
668 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
669 public static final int TYPE_MOBILE_FOTA = 10;
670
671 /**
672 * IP Multimedia Subsystem.
673 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
674 * {@hide}
675 */
676 @Deprecated
677 @UnsupportedAppUsage
678 public static final int TYPE_MOBILE_IMS = 11;
679
680 /**
681 * Carrier Branded Services.
682 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
683 * {@hide}
684 */
685 @Deprecated
686 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
687 public static final int TYPE_MOBILE_CBS = 12;
688
689 /**
690 * A Wi-Fi p2p connection. Only requesting processes will have access to
691 * the peers connected.
692 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
693 * {@hide}
694 */
695 @Deprecated
696 @SystemApi
697 public static final int TYPE_WIFI_P2P = 13;
698
699 /**
700 * The network to use for initially attaching to the network
701 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
702 * {@hide}
703 */
704 @Deprecated
705 @UnsupportedAppUsage
706 public static final int TYPE_MOBILE_IA = 14;
707
708 /**
709 * Emergency PDN connection for emergency services. This
710 * may include IMS and MMS in emergency situations.
711 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
712 * {@hide}
713 */
714 @Deprecated
715 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
716 public static final int TYPE_MOBILE_EMERGENCY = 15;
717
718 /**
719 * The network that uses proxy to achieve connectivity.
720 * @deprecated Use {@link NetworkCapabilities} instead.
721 * {@hide}
722 */
723 @Deprecated
724 @SystemApi
725 public static final int TYPE_PROXY = 16;
726
727 /**
728 * A virtual network using one or more native bearers.
729 * It may or may not be providing security services.
730 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
731 */
732 @Deprecated
733 public static final int TYPE_VPN = 17;
734
735 /**
736 * A network that is exclusively meant to be used for testing
737 *
738 * @deprecated Use {@link NetworkCapabilities} instead.
739 * @hide
740 */
741 @Deprecated
742 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
743
744 /**
745 * @deprecated Use {@link NetworkCapabilities} instead.
746 * @hide
747 */
748 @Deprecated
749 @Retention(RetentionPolicy.SOURCE)
750 @IntDef(prefix = { "TYPE_" }, value = {
751 TYPE_NONE,
752 TYPE_MOBILE,
753 TYPE_WIFI,
754 TYPE_MOBILE_MMS,
755 TYPE_MOBILE_SUPL,
756 TYPE_MOBILE_DUN,
757 TYPE_MOBILE_HIPRI,
758 TYPE_WIMAX,
759 TYPE_BLUETOOTH,
760 TYPE_DUMMY,
761 TYPE_ETHERNET,
762 TYPE_MOBILE_FOTA,
763 TYPE_MOBILE_IMS,
764 TYPE_MOBILE_CBS,
765 TYPE_WIFI_P2P,
766 TYPE_MOBILE_IA,
767 TYPE_MOBILE_EMERGENCY,
768 TYPE_PROXY,
769 TYPE_VPN,
770 TYPE_TEST
771 })
772 public @interface LegacyNetworkType {}
773
774 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
775 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
776 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
777 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
778 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
779
780 /** {@hide} */
781 public static final int MAX_RADIO_TYPE = TYPE_TEST;
782
783 /** {@hide} */
784 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
785
786 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
787
788 /**
789 * If you want to set the default network preference,you can directly
790 * change the networkAttributes array in framework's config.xml.
791 *
792 * @deprecated Since we support so many more networks now, the single
793 * network default network preference can't really express
794 * the hierarchy. Instead, the default is defined by the
795 * networkAttributes in config.xml. You can determine
796 * the current value by calling {@link #getNetworkPreference()}
797 * from an App.
798 */
799 @Deprecated
800 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
801
802 /**
803 * @hide
804 */
805 public static final int REQUEST_ID_UNSET = 0;
806
807 /**
808 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
809 * This allows to distinguish when unregistering NetworkCallbacks those that were never
810 * registered from those that were already unregistered.
811 * @hide
812 */
813 private static final NetworkRequest ALREADY_UNREGISTERED =
814 new NetworkRequest.Builder().clearCapabilities().build();
815
816 /**
817 * A NetID indicating no Network is selected.
818 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
819 * @hide
820 */
821 public static final int NETID_UNSET = 0;
822
823 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000824 * Flag to indicate that an app is not subject to any restrictions that could result in its
825 * network access blocked.
826 *
827 * @hide
828 */
829 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
830 public static final int BLOCKED_REASON_NONE = 0;
831
832 /**
833 * Flag to indicate that an app is subject to Battery saver restrictions that would
834 * result in its network access being blocked.
835 *
836 * @hide
837 */
838 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
839 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
840
841 /**
842 * Flag to indicate that an app is subject to Doze restrictions that would
843 * result in its network access being blocked.
844 *
845 * @hide
846 */
847 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
848 public static final int BLOCKED_REASON_DOZE = 1 << 1;
849
850 /**
851 * Flag to indicate that an app is subject to App Standby restrictions that would
852 * result in its network access being blocked.
853 *
854 * @hide
855 */
856 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
857 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
858
859 /**
860 * Flag to indicate that an app is subject to Restricted mode restrictions that would
861 * result in its network access being blocked.
862 *
863 * @hide
864 */
865 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
866 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
867
868 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900869 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
870 * is not currently connected.
871 *
872 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
873 *
874 * @hide
875 */
876 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
877 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
878
879 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100880 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
881 * result in its network access being blocked.
882 *
883 * @hide
884 */
885 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
886 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
887
888 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000889 * Flag to indicate that an app is subject to Data saver restrictions that would
890 * result in its metered network access being blocked.
891 *
892 * @hide
893 */
894 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
895 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
896
897 /**
898 * Flag to indicate that an app is subject to user restrictions that would
899 * result in its metered network access being blocked.
900 *
901 * @hide
902 */
903 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
904 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
905
906 /**
907 * Flag to indicate that an app is subject to Device admin restrictions that would
908 * result in its metered network access being blocked.
909 *
910 * @hide
911 */
912 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
913 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
914
915 /**
916 * @hide
917 */
918 @Retention(RetentionPolicy.SOURCE)
919 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
920 BLOCKED_REASON_NONE,
921 BLOCKED_REASON_BATTERY_SAVER,
922 BLOCKED_REASON_DOZE,
923 BLOCKED_REASON_APP_STANDBY,
924 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900925 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100926 BLOCKED_REASON_LOW_POWER_STANDBY,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000927 BLOCKED_METERED_REASON_DATA_SAVER,
928 BLOCKED_METERED_REASON_USER_RESTRICTED,
929 BLOCKED_METERED_REASON_ADMIN_DISABLED,
930 })
931 public @interface BlockedReason {}
932
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900933 /**
934 * Set of blocked reasons that are only applicable on metered networks.
935 *
936 * @hide
937 */
938 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
939 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
940
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900941 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
942 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900943
Robert Horvathd945bf02022-01-27 19:55:16 +0100944 // LINT.IfChange(firewall_chain)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900945 /**
markchiene1561fa2021-12-09 22:00:56 +0800946 * Firewall chain for device idle (doze mode).
947 * Allowlist of apps that have network access in device idle.
948 * @hide
949 */
950 @SystemApi(client = MODULE_LIBRARIES)
951 public static final int FIREWALL_CHAIN_DOZABLE = 1;
952
953 /**
954 * Firewall chain used for app standby.
955 * Denylist of apps that do not have network access.
956 * @hide
957 */
958 @SystemApi(client = MODULE_LIBRARIES)
959 public static final int FIREWALL_CHAIN_STANDBY = 2;
960
961 /**
962 * Firewall chain used for battery saver.
963 * Allowlist of apps that have network access when battery saver is on.
964 * @hide
965 */
966 @SystemApi(client = MODULE_LIBRARIES)
967 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
968
969 /**
970 * Firewall chain used for restricted networking mode.
971 * Allowlist of apps that have access in restricted networking mode.
972 * @hide
973 */
974 @SystemApi(client = MODULE_LIBRARIES)
975 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
976
Robert Horvath34cba142022-01-27 19:52:43 +0100977 /**
978 * Firewall chain used for low power standby.
979 * Allowlist of apps that have access in low power standby.
980 * @hide
981 */
982 @SystemApi(client = MODULE_LIBRARIES)
983 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
984
Motomu Utsumib08654c2022-05-11 05:56:26 +0000985 /**
Motomu Utsumid9801492022-06-01 13:57:27 +0000986 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +0900987 *
988 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
989 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
990 *
991 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
992 * independent of the others. The chains can be enabled and disabled independently, and apps can
993 * be added and removed from each chain independently.
994 *
995 * @see #FIREWALL_CHAIN_OEM_DENY_2
996 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +0000997 * @hide
998 */
Motomu Utsumi62385c82022-06-12 11:37:19 +0000999 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001000 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1001
1002 /**
1003 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001004 *
1005 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1006 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1007 *
1008 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1009 * independent of the others. The chains can be enabled and disabled independently, and apps can
1010 * be added and removed from each chain independently.
1011 *
1012 * @see #FIREWALL_CHAIN_OEM_DENY_1
1013 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001014 * @hide
1015 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001016 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001017 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1018
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001019 /**
1020 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001021 *
1022 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1023 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1024 *
1025 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1026 * independent of the others. The chains can be enabled and disabled independently, and apps can
1027 * be added and removed from each chain independently.
1028 *
1029 * @see #FIREWALL_CHAIN_OEM_DENY_1
1030 * @see #FIREWALL_CHAIN_OEM_DENY_2
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001031 * @hide
1032 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001033 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001034 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1035
markchiene1561fa2021-12-09 22:00:56 +08001036 /** @hide */
1037 @Retention(RetentionPolicy.SOURCE)
1038 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1039 FIREWALL_CHAIN_DOZABLE,
1040 FIREWALL_CHAIN_STANDBY,
1041 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001042 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001043 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Motomu Utsumid9801492022-06-01 13:57:27 +00001044 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001045 FIREWALL_CHAIN_OEM_DENY_2,
1046 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001047 })
1048 public @interface FirewallChain {}
Robert Horvathd945bf02022-01-27 19:55:16 +01001049 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
markchiene1561fa2021-12-09 22:00:56 +08001050
1051 /**
markchien011a7f52022-03-29 01:07:22 +08001052 * A firewall rule which allows or drops packets depending on existing policy.
1053 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1054 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001055 * @hide
1056 */
1057 @SystemApi(client = MODULE_LIBRARIES)
1058 public static final int FIREWALL_RULE_DEFAULT = 0;
1059
1060 /**
markchien011a7f52022-03-29 01:07:22 +08001061 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1062 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001063 * @hide
1064 */
1065 @SystemApi(client = MODULE_LIBRARIES)
1066 public static final int FIREWALL_RULE_ALLOW = 1;
1067
1068 /**
markchien011a7f52022-03-29 01:07:22 +08001069 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1070 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001071 * @hide
1072 */
1073 @SystemApi(client = MODULE_LIBRARIES)
1074 public static final int FIREWALL_RULE_DENY = 2;
1075
1076 /** @hide */
1077 @Retention(RetentionPolicy.SOURCE)
1078 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1079 FIREWALL_RULE_DEFAULT,
1080 FIREWALL_RULE_ALLOW,
1081 FIREWALL_RULE_DENY
1082 })
1083 public @interface FirewallRule {}
1084
1085 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001086 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1087 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1088 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1089 * methods that take a Context argument.
1090 */
1091 private static ConnectivityManager sInstance;
1092
1093 private final Context mContext;
1094
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001095 @GuardedBy("mTetheringEventCallbacks")
1096 private TetheringManager mTetheringManager;
1097
1098 private TetheringManager getTetheringManager() {
1099 synchronized (mTetheringEventCallbacks) {
1100 if (mTetheringManager == null) {
1101 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1102 }
1103 return mTetheringManager;
1104 }
1105 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001106
1107 /**
1108 * Tests if a given integer represents a valid network type.
1109 * @param networkType the type to be tested
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001110 * @return {@code true} if the type is valid, else {@code false}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001111 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1112 * validate a network type.
1113 */
1114 @Deprecated
1115 public static boolean isNetworkTypeValid(int networkType) {
1116 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1117 }
1118
1119 /**
1120 * Returns a non-localized string representing a given network type.
1121 * ONLY used for debugging output.
1122 * @param type the type needing naming
1123 * @return a String for the given type, or a string version of the type ("87")
1124 * if no name is known.
1125 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1126 * {@hide}
1127 */
1128 @Deprecated
1129 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1130 public static String getNetworkTypeName(int type) {
1131 switch (type) {
1132 case TYPE_NONE:
1133 return "NONE";
1134 case TYPE_MOBILE:
1135 return "MOBILE";
1136 case TYPE_WIFI:
1137 return "WIFI";
1138 case TYPE_MOBILE_MMS:
1139 return "MOBILE_MMS";
1140 case TYPE_MOBILE_SUPL:
1141 return "MOBILE_SUPL";
1142 case TYPE_MOBILE_DUN:
1143 return "MOBILE_DUN";
1144 case TYPE_MOBILE_HIPRI:
1145 return "MOBILE_HIPRI";
1146 case TYPE_WIMAX:
1147 return "WIMAX";
1148 case TYPE_BLUETOOTH:
1149 return "BLUETOOTH";
1150 case TYPE_DUMMY:
1151 return "DUMMY";
1152 case TYPE_ETHERNET:
1153 return "ETHERNET";
1154 case TYPE_MOBILE_FOTA:
1155 return "MOBILE_FOTA";
1156 case TYPE_MOBILE_IMS:
1157 return "MOBILE_IMS";
1158 case TYPE_MOBILE_CBS:
1159 return "MOBILE_CBS";
1160 case TYPE_WIFI_P2P:
1161 return "WIFI_P2P";
1162 case TYPE_MOBILE_IA:
1163 return "MOBILE_IA";
1164 case TYPE_MOBILE_EMERGENCY:
1165 return "MOBILE_EMERGENCY";
1166 case TYPE_PROXY:
1167 return "PROXY";
1168 case TYPE_VPN:
1169 return "VPN";
Junyu Laic9f1ca62022-07-25 16:31:59 +08001170 case TYPE_TEST:
1171 return "TEST";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001172 default:
1173 return Integer.toString(type);
1174 }
1175 }
1176
1177 /**
1178 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001179 */
lucaslin10774b72021-03-17 14:16:01 +08001180 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001181 public void systemReady() {
1182 try {
1183 mService.systemReady();
1184 } catch (RemoteException e) {
1185 throw e.rethrowFromSystemServer();
1186 }
1187 }
1188
1189 /**
1190 * Checks if a given type uses the cellular data connection.
1191 * This should be replaced in the future by a network property.
1192 * @param networkType the type to check
1193 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1194 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1195 * {@hide}
1196 */
1197 @Deprecated
1198 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1199 public static boolean isNetworkTypeMobile(int networkType) {
1200 switch (networkType) {
1201 case TYPE_MOBILE:
1202 case TYPE_MOBILE_MMS:
1203 case TYPE_MOBILE_SUPL:
1204 case TYPE_MOBILE_DUN:
1205 case TYPE_MOBILE_HIPRI:
1206 case TYPE_MOBILE_FOTA:
1207 case TYPE_MOBILE_IMS:
1208 case TYPE_MOBILE_CBS:
1209 case TYPE_MOBILE_IA:
1210 case TYPE_MOBILE_EMERGENCY:
1211 return true;
1212 default:
1213 return false;
1214 }
1215 }
1216
1217 /**
1218 * Checks if the given network type is backed by a Wi-Fi radio.
1219 *
1220 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1221 * @hide
1222 */
1223 @Deprecated
1224 public static boolean isNetworkTypeWifi(int networkType) {
1225 switch (networkType) {
1226 case TYPE_WIFI:
1227 case TYPE_WIFI_P2P:
1228 return true;
1229 default:
1230 return false;
1231 }
1232 }
1233
1234 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001235 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001236 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Junyu Lai35665cc2022-12-19 17:37:48 +08001237 * Specify that the traffic for this user should by follow the default rules:
1238 * applications in the profile designated by the UserHandle behave like any
1239 * other application and use the system default network as their default
1240 * network. Compare other PROFILE_NETWORK_PREFERENCE_* settings.
Chalard Jeanad565e22021-02-25 17:23:40 +09001241 * @hide
1242 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001243 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001244 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1245
1246 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001247 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001248 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001249 * Specify that the traffic for this user should by default go on a network with
1250 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1251 * if no such network is available.
1252 * @hide
1253 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001254 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001255 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1256
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001257 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001258 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001259 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001260 * Specify that the traffic for this user should by default go on a network with
1261 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
Junyu Lai35665cc2022-12-19 17:37:48 +08001262 * should not have a default network at all (that is, network accesses that
1263 * do not specify a network explicitly terminate with an error), even if there
1264 * is a system default network available to apps outside this preference.
1265 * The apps can still use a non-enterprise network if they request it explicitly
1266 * provided that specific network doesn't require any specific permission they
1267 * do not hold.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001268 * @hide
1269 */
1270 @SystemApi(client = MODULE_LIBRARIES)
1271 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1272
Junyu Lai35665cc2022-12-19 17:37:48 +08001273 /**
1274 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
1275 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1276 * Specify that the traffic for this user should by default go on a network with
1277 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}.
1278 * If there is no such network, the apps will have no default
1279 * network at all, even if there are available non-enterprise networks on the
1280 * device (that is, network accesses that do not specify a network explicitly
1281 * terminate with an error). Additionally, the designated apps should be
1282 * blocked from using any non-enterprise network even if they specify it
1283 * explicitly, unless they hold specific privilege overriding this (see
1284 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS}).
1285 * @hide
1286 */
1287 @SystemApi(client = MODULE_LIBRARIES)
1288 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING = 3;
1289
Chalard Jeanad565e22021-02-25 17:23:40 +09001290 /** @hide */
1291 @Retention(RetentionPolicy.SOURCE)
1292 @IntDef(value = {
1293 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001294 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1295 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001296 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001297 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001298 }
1299
1300 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001301 * Specifies the preferred network type. When the device has more
1302 * than one type available the preferred network type will be used.
1303 *
1304 * @param preference the network type to prefer over all others. It is
1305 * unspecified what happens to the old preferred network in the
1306 * overall ordering.
1307 * @deprecated Functionality has been removed as it no longer makes sense,
1308 * with many more than two networks - we'd need an array to express
1309 * preference. Instead we use dynamic network properties of
1310 * the networks to describe their precedence.
1311 */
1312 @Deprecated
1313 public void setNetworkPreference(int preference) {
1314 }
1315
1316 /**
1317 * Retrieves the current preferred network type.
1318 *
1319 * @return an integer representing the preferred network type
1320 *
1321 * @deprecated Functionality has been removed as it no longer makes sense,
1322 * with many more than two networks - we'd need an array to express
1323 * preference. Instead we use dynamic network properties of
1324 * the networks to describe their precedence.
1325 */
1326 @Deprecated
1327 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1328 public int getNetworkPreference() {
1329 return TYPE_NONE;
1330 }
1331
1332 /**
1333 * Returns details about the currently active default data network. When
1334 * connected, this network is the default route for outgoing connections.
1335 * You should always check {@link NetworkInfo#isConnected()} before initiating
1336 * network traffic. This may return {@code null} when there is no default
1337 * network.
1338 * Note that if the default network is a VPN, this method will return the
1339 * NetworkInfo for one of its underlying networks instead, or null if the
1340 * VPN agent did not specify any. Apps interested in learning about VPNs
1341 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1342 *
1343 * @return a {@link NetworkInfo} object for the current default network
1344 * or {@code null} if no default network is currently active
1345 * @deprecated See {@link NetworkInfo}.
1346 */
1347 @Deprecated
1348 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1349 @Nullable
1350 public NetworkInfo getActiveNetworkInfo() {
1351 try {
1352 return mService.getActiveNetworkInfo();
1353 } catch (RemoteException e) {
1354 throw e.rethrowFromSystemServer();
1355 }
1356 }
1357
1358 /**
1359 * Returns a {@link Network} object corresponding to the currently active
1360 * default data network. In the event that the current active default data
1361 * network disconnects, the returned {@code Network} object will no longer
1362 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001363 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001364 *
1365 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001366 * {@code null} if no default network is currently active or if
1367 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001368 */
1369 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1370 @Nullable
1371 public Network getActiveNetwork() {
1372 try {
1373 return mService.getActiveNetwork();
1374 } catch (RemoteException e) {
1375 throw e.rethrowFromSystemServer();
1376 }
1377 }
1378
1379 /**
1380 * Returns a {@link Network} object corresponding to the currently active
1381 * default data network for a specific UID. In the event that the default data
1382 * network disconnects, the returned {@code Network} object will no longer
1383 * be usable. This will return {@code null} when there is no default
1384 * network for the UID.
1385 *
1386 * @return a {@link Network} object for the current default network for the
1387 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001388 *
1389 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001390 */
1391 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1392 @Nullable
1393 public Network getActiveNetworkForUid(int uid) {
1394 return getActiveNetworkForUid(uid, false);
1395 }
1396
1397 /** {@hide} */
1398 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1399 try {
1400 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1401 } catch (RemoteException e) {
1402 throw e.rethrowFromSystemServer();
1403 }
1404 }
1405
lucaslin3ba7cc22022-12-19 02:35:33 +00001406 private static UidRange[] getUidRangeArray(@NonNull Collection<Range<Integer>> ranges) {
1407 Objects.requireNonNull(ranges);
1408 final UidRange[] rangesArray = new UidRange[ranges.size()];
1409 int index = 0;
1410 for (Range<Integer> range : ranges) {
1411 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1412 }
1413
1414 return rangesArray;
1415 }
1416
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001417 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001418 * Adds or removes a requirement for given UID ranges to use the VPN.
1419 *
1420 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1421 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1422 * otherwise have permission to bypass the VPN (e.g., because they have the
1423 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1424 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1425 * set to {@code false}, a previously-added restriction is removed.
1426 * <p>
1427 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1428 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1429 * remove a previously-added range, the exact range must be removed as is.
1430 * <p>
1431 * The changes are applied asynchronously and may not have been applied by the time the method
1432 * returns. Apps will be notified about any changes that apply to them via
1433 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1434 * effect.
1435 * <p>
lucaslin3ba7cc22022-12-19 02:35:33 +00001436 * This method will block the specified UIDs from accessing non-VPN networks, but does not
1437 * affect what the UIDs get as their default network.
1438 * Compare {@link #setVpnDefaultForUids(String, Collection)}, which declares that the UIDs
1439 * should only have a VPN as their default network, but does not block them from accessing other
1440 * networks if they request them explicitly with the {@link Network} API.
1441 * <p>
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001442 * This method should be called only by the VPN code.
1443 *
1444 * @param ranges the UID ranges to restrict
1445 * @param requireVpn whether the specified UID ranges must use a VPN
1446 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001447 * @hide
1448 */
1449 @RequiresPermission(anyOf = {
1450 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001451 android.Manifest.permission.NETWORK_STACK,
1452 android.Manifest.permission.NETWORK_SETTINGS})
1453 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001454 public void setRequireVpnForUids(boolean requireVpn,
1455 @NonNull Collection<Range<Integer>> ranges) {
1456 Objects.requireNonNull(ranges);
1457 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1458 // This method is not necessarily expected to be used outside the system server, so
1459 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1460 // stack process, or by tests.
lucaslin3ba7cc22022-12-19 02:35:33 +00001461 final UidRange[] rangesArray = getUidRangeArray(ranges);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001462 try {
1463 mService.setRequireVpnForUids(requireVpn, rangesArray);
1464 } catch (RemoteException e) {
1465 throw e.rethrowFromSystemServer();
1466 }
1467 }
1468
1469 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001470 * Inform the system that this VPN session should manage the passed UIDs.
1471 *
1472 * A VPN with the specified session ID may call this method to inform the system that the UIDs
1473 * in the specified range are subject to a VPN.
1474 * When this is called, the system will only choose a VPN for the default network of the UIDs in
1475 * the specified ranges.
1476 *
1477 * This method declares that the UIDs in the range will only have a VPN for their default
1478 * network, but does not block the UIDs from accessing other networks (permissions allowing) by
1479 * explicitly requesting it with the {@link Network} API.
1480 * Compare {@link #setRequireVpnForUids(boolean, Collection)}, which does not affect what
1481 * network the UIDs get as default, but will block them from accessing non-VPN networks.
1482 *
1483 * @param session The VPN session which manages the passed UIDs.
1484 * @param ranges The uid ranges which will treat VPN as their only default network.
1485 *
1486 * @hide
1487 */
1488 @RequiresPermission(anyOf = {
1489 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1490 android.Manifest.permission.NETWORK_STACK,
1491 android.Manifest.permission.NETWORK_SETTINGS})
1492 @SystemApi(client = MODULE_LIBRARIES)
1493 public void setVpnDefaultForUids(@NonNull String session,
1494 @NonNull Collection<Range<Integer>> ranges) {
1495 Objects.requireNonNull(ranges);
1496 final UidRange[] rangesArray = getUidRangeArray(ranges);
1497 try {
1498 mService.setVpnNetworkPreference(session, rangesArray);
1499 } catch (RemoteException e) {
1500 throw e.rethrowFromSystemServer();
1501 }
1502 }
1503
1504 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001505 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1506 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1507 * but is still supported for backwards compatibility.
1508 * <p>
1509 * This type of VPN is assumed always to use the system default network, and must always declare
1510 * exactly one underlying network, which is the network that was the default when the VPN
1511 * connected.
1512 * <p>
1513 * Calling this method with {@code true} enables legacy behaviour, specifically:
1514 * <ul>
1515 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1516 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1517 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1518 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1519 * underlying the VPN.</li>
1520 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1521 * similarly replaced by the VPN network state.</li>
1522 * <li>Information on current network interfaces passed to NetworkStatsService will not
1523 * include any VPN interfaces.</li>
1524 * </ul>
1525 *
1526 * @param enabled whether legacy lockdown VPN is enabled or disabled
1527 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001528 * @hide
1529 */
1530 @RequiresPermission(anyOf = {
1531 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001532 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001533 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001534 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001535 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1536 try {
1537 mService.setLegacyLockdownVpnEnabled(enabled);
1538 } catch (RemoteException e) {
1539 throw e.rethrowFromSystemServer();
1540 }
1541 }
1542
1543 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001544 * Returns details about the currently active default data network for a given uid.
1545 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001546 *
1547 * @return a {@link NetworkInfo} object for the current default network
1548 * for the given uid or {@code null} if no default network is
1549 * available for the specified uid.
1550 *
1551 * {@hide}
1552 */
1553 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1554 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1555 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1556 return getActiveNetworkInfoForUid(uid, false);
1557 }
1558
1559 /** {@hide} */
1560 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1561 try {
1562 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1563 } catch (RemoteException e) {
1564 throw e.rethrowFromSystemServer();
1565 }
1566 }
1567
1568 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001569 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001570 *
1571 * @param networkType integer specifying which networkType in
1572 * which you're interested.
1573 * @return a {@link NetworkInfo} object for the requested
1574 * network type or {@code null} if the type is not
1575 * supported by the device. If {@code networkType} is
1576 * TYPE_VPN and a VPN is active for the calling app,
1577 * then this method will try to return one of the
1578 * underlying networks for the VPN or null if the
1579 * VPN agent didn't specify any.
1580 *
1581 * @deprecated This method does not support multiple connected networks
1582 * of the same type. Use {@link #getAllNetworks} and
1583 * {@link #getNetworkInfo(android.net.Network)} instead.
1584 */
1585 @Deprecated
1586 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1587 @Nullable
1588 public NetworkInfo getNetworkInfo(int networkType) {
1589 try {
1590 return mService.getNetworkInfo(networkType);
1591 } catch (RemoteException e) {
1592 throw e.rethrowFromSystemServer();
1593 }
1594 }
1595
1596 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001597 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001598 *
1599 * @param network {@link Network} specifying which network
1600 * in which you're interested.
1601 * @return a {@link NetworkInfo} object for the requested
1602 * network or {@code null} if the {@code Network}
1603 * is not valid.
1604 * @deprecated See {@link NetworkInfo}.
1605 */
1606 @Deprecated
1607 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1608 @Nullable
1609 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1610 return getNetworkInfoForUid(network, Process.myUid(), false);
1611 }
1612
1613 /** {@hide} */
1614 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1615 try {
1616 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1617 } catch (RemoteException e) {
1618 throw e.rethrowFromSystemServer();
1619 }
1620 }
1621
1622 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001623 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001624 *
1625 * @return an array of {@link NetworkInfo} objects. Check each
1626 * {@link NetworkInfo#getType} for which type each applies.
1627 *
1628 * @deprecated This method does not support multiple connected networks
1629 * of the same type. Use {@link #getAllNetworks} and
1630 * {@link #getNetworkInfo(android.net.Network)} instead.
1631 */
1632 @Deprecated
1633 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1634 @NonNull
1635 public NetworkInfo[] getAllNetworkInfo() {
1636 try {
1637 return mService.getAllNetworkInfo();
1638 } catch (RemoteException e) {
1639 throw e.rethrowFromSystemServer();
1640 }
1641 }
1642
1643 /**
junyulaib1211372021-03-03 12:09:05 +08001644 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1645 * connected.
1646 * @hide
1647 */
1648 @SystemApi(client = MODULE_LIBRARIES)
1649 @RequiresPermission(anyOf = {
1650 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1651 android.Manifest.permission.NETWORK_STACK,
1652 android.Manifest.permission.NETWORK_SETTINGS})
1653 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001654 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001655 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001656 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001657 } catch (RemoteException e) {
1658 throw e.rethrowFromSystemServer();
1659 }
1660 }
1661
1662 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001663 * Returns the {@link Network} object currently serving a given type, or
1664 * null if the given type is not connected.
1665 *
1666 * @hide
1667 * @deprecated This method does not support multiple connected networks
1668 * of the same type. Use {@link #getAllNetworks} and
1669 * {@link #getNetworkInfo(android.net.Network)} instead.
1670 */
1671 @Deprecated
1672 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1673 @UnsupportedAppUsage
1674 public Network getNetworkForType(int networkType) {
1675 try {
1676 return mService.getNetworkForType(networkType);
1677 } catch (RemoteException e) {
1678 throw e.rethrowFromSystemServer();
1679 }
1680 }
1681
1682 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001683 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001684 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001685 * @deprecated This method does not provide any notification of network state changes, forcing
1686 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1687 * Apps should use methods such as
1688 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1689 * Apps that desire to obtain information about networks that do not apply to them
1690 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1691 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001692 * @return an array of {@link Network} objects.
1693 */
1694 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1695 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001696 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001697 public Network[] getAllNetworks() {
1698 try {
1699 return mService.getAllNetworks();
1700 } catch (RemoteException e) {
1701 throw e.rethrowFromSystemServer();
1702 }
1703 }
1704
1705 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001706 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001707 * the Networks that applications run by the given user will use by default.
1708 * @hide
1709 */
1710 @UnsupportedAppUsage
1711 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1712 try {
1713 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001714 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001715 } catch (RemoteException e) {
1716 throw e.rethrowFromSystemServer();
1717 }
1718 }
1719
1720 /**
1721 * Returns the IP information for the current default network.
1722 *
1723 * @return a {@link LinkProperties} object describing the IP info
1724 * for the current default network, or {@code null} if there
1725 * is no current default network.
1726 *
1727 * {@hide}
1728 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1729 * value of {@link #getActiveNetwork()} instead. In particular,
1730 * this method will return non-null LinkProperties even if the
1731 * app is blocked by policy from using this network.
1732 */
1733 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1734 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1735 public LinkProperties getActiveLinkProperties() {
1736 try {
1737 return mService.getActiveLinkProperties();
1738 } catch (RemoteException e) {
1739 throw e.rethrowFromSystemServer();
1740 }
1741 }
1742
1743 /**
1744 * Returns the IP information for a given network type.
1745 *
1746 * @param networkType the network type of interest.
1747 * @return a {@link LinkProperties} object describing the IP info
1748 * for the given networkType, or {@code null} if there is
1749 * no current default network.
1750 *
1751 * {@hide}
1752 * @deprecated This method does not support multiple connected networks
1753 * of the same type. Use {@link #getAllNetworks},
1754 * {@link #getNetworkInfo(android.net.Network)}, and
1755 * {@link #getLinkProperties(android.net.Network)} instead.
1756 */
1757 @Deprecated
1758 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1759 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1760 public LinkProperties getLinkProperties(int networkType) {
1761 try {
1762 return mService.getLinkPropertiesForType(networkType);
1763 } catch (RemoteException e) {
1764 throw e.rethrowFromSystemServer();
1765 }
1766 }
1767
1768 /**
1769 * Get the {@link LinkProperties} for the given {@link Network}. This
1770 * will return {@code null} if the network is unknown.
1771 *
1772 * @param network The {@link Network} object identifying the network in question.
1773 * @return The {@link LinkProperties} for the network, or {@code null}.
1774 */
1775 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1776 @Nullable
1777 public LinkProperties getLinkProperties(@Nullable Network network) {
1778 try {
1779 return mService.getLinkProperties(network);
1780 } catch (RemoteException e) {
1781 throw e.rethrowFromSystemServer();
1782 }
1783 }
1784
1785 /**
lucaslinc582d502022-01-27 09:07:00 +08001786 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001787 *
lucaslinc582d502022-01-27 09:07:00 +08001788 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1789 * given package, considering its permissions.
1790 *
1791 * @param lp A {@link LinkProperties} which will be redacted.
1792 * @param uid The target uid.
1793 * @param packageName The name of the package, for appops logging.
1794 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1795 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1796 * @hide
1797 */
1798 @RequiresPermission(anyOf = {
1799 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1800 android.Manifest.permission.NETWORK_STACK,
1801 android.Manifest.permission.NETWORK_SETTINGS})
1802 @SystemApi(client = MODULE_LIBRARIES)
1803 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001804 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001805 @NonNull String packageName) {
1806 try {
lucaslind2b06132022-03-02 10:56:57 +08001807 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001808 lp, uid, packageName, getAttributionTag());
1809 } catch (RemoteException e) {
1810 throw e.rethrowFromSystemServer();
1811 }
1812 }
1813
1814 /**
1815 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1816 *
1817 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1818 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1819 * sensitive information. To retrieve this location sensitive information (subject to
1820 * the caller's location permissions), use a {@link NetworkCallback} with the
1821 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1822 *
1823 * This method returns {@code null} if the network is unknown or if the |network| argument
1824 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001825 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001826 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001827 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001828 */
1829 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1830 @Nullable
1831 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1832 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001833 return mService.getNetworkCapabilities(
1834 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001835 } catch (RemoteException e) {
1836 throw e.rethrowFromSystemServer();
1837 }
1838 }
1839
1840 /**
lucaslinc582d502022-01-27 09:07:00 +08001841 * Redact {@link NetworkCapabilities} for a given package.
1842 *
1843 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001844 * to the given package, considering its permissions. If the passed capabilities contain
1845 * location-sensitive information, they will be redacted to the correct degree for the location
1846 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1847 * that level of location. If the UID holds no location permission, the returned object will
1848 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001849 *
1850 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1851 * @param uid The target uid.
1852 * @param packageName The name of the package, for appops logging.
1853 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1854 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1855 * @hide
1856 */
1857 @RequiresPermission(anyOf = {
1858 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1859 android.Manifest.permission.NETWORK_STACK,
1860 android.Manifest.permission.NETWORK_SETTINGS})
1861 @SystemApi(client = MODULE_LIBRARIES)
1862 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001863 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001864 @NonNull NetworkCapabilities nc,
1865 int uid, @NonNull String packageName) {
1866 try {
lucaslind2b06132022-03-02 10:56:57 +08001867 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001868 getAttributionTag());
1869 } catch (RemoteException e) {
1870 throw e.rethrowFromSystemServer();
1871 }
1872 }
1873
1874 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001875 * Gets a URL that can be used for resolving whether a captive portal is present.
1876 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1877 * portal is present.
1878 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1879 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1880 *
1881 * The system network validation may be using different strategies to detect captive portals,
1882 * so this method does not necessarily return a URL used by the system. It only returns a URL
1883 * that may be relevant for other components trying to detect captive portals.
1884 *
1885 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001886 * @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 +09001887 * system.
1888 */
1889 @Deprecated
1890 @SystemApi
1891 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1892 public String getCaptivePortalServerUrl() {
1893 try {
1894 return mService.getCaptivePortalServerUrl();
1895 } catch (RemoteException e) {
1896 throw e.rethrowFromSystemServer();
1897 }
1898 }
1899
1900 /**
1901 * Tells the underlying networking system that the caller wants to
1902 * begin using the named feature. The interpretation of {@code feature}
1903 * is completely up to each networking implementation.
1904 *
1905 * <p>This method requires the caller to hold either the
1906 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1907 * or the ability to modify system settings as determined by
1908 * {@link android.provider.Settings.System#canWrite}.</p>
1909 *
1910 * @param networkType specifies which network the request pertains to
1911 * @param feature the name of the feature to be used
1912 * @return an integer value representing the outcome of the request.
1913 * The interpretation of this value is specific to each networking
1914 * implementation+feature combination, except that the value {@code -1}
1915 * always indicates failure.
1916 *
1917 * @deprecated Deprecated in favor of the cleaner
1918 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1919 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1920 * throw {@code UnsupportedOperationException} if called.
1921 * @removed
1922 */
1923 @Deprecated
1924 public int startUsingNetworkFeature(int networkType, String feature) {
1925 checkLegacyRoutingApiAccess();
1926 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1927 if (netCap == null) {
1928 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1929 feature);
1930 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1931 }
1932
1933 NetworkRequest request = null;
1934 synchronized (sLegacyRequests) {
1935 LegacyRequest l = sLegacyRequests.get(netCap);
1936 if (l != null) {
1937 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1938 renewRequestLocked(l);
1939 if (l.currentNetwork != null) {
1940 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1941 } else {
1942 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1943 }
1944 }
1945
1946 request = requestNetworkForFeatureLocked(netCap);
1947 }
1948 if (request != null) {
1949 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1950 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1951 } else {
1952 Log.d(TAG, " request Failed");
1953 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1954 }
1955 }
1956
1957 /**
1958 * Tells the underlying networking system that the caller is finished
1959 * using the named feature. The interpretation of {@code feature}
1960 * is completely up to each networking implementation.
1961 *
1962 * <p>This method requires the caller to hold either the
1963 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1964 * or the ability to modify system settings as determined by
1965 * {@link android.provider.Settings.System#canWrite}.</p>
1966 *
1967 * @param networkType specifies which network the request pertains to
1968 * @param feature the name of the feature that is no longer needed
1969 * @return an integer value representing the outcome of the request.
1970 * The interpretation of this value is specific to each networking
1971 * implementation+feature combination, except that the value {@code -1}
1972 * always indicates failure.
1973 *
1974 * @deprecated Deprecated in favor of the cleaner
1975 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1976 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1977 * throw {@code UnsupportedOperationException} if called.
1978 * @removed
1979 */
1980 @Deprecated
1981 public int stopUsingNetworkFeature(int networkType, String feature) {
1982 checkLegacyRoutingApiAccess();
1983 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1984 if (netCap == null) {
1985 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1986 feature);
1987 return -1;
1988 }
1989
1990 if (removeRequestForFeature(netCap)) {
1991 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1992 }
1993 return 1;
1994 }
1995
1996 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1997 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1998 if (networkType == TYPE_MOBILE) {
1999 switch (feature) {
2000 case "enableCBS":
2001 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
2002 case "enableDUN":
2003 case "enableDUNAlways":
2004 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
2005 case "enableFOTA":
2006 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
2007 case "enableHIPRI":
2008 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
2009 case "enableIMS":
2010 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
2011 case "enableMMS":
2012 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
2013 case "enableSUPL":
2014 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
2015 default:
2016 return null;
2017 }
2018 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
2019 return networkCapabilitiesForType(TYPE_WIFI_P2P);
2020 }
2021 return null;
2022 }
2023
2024 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
2025 if (netCap == null) return TYPE_NONE;
2026 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
2027 return TYPE_MOBILE_CBS;
2028 }
2029 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2030 return TYPE_MOBILE_IMS;
2031 }
2032 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
2033 return TYPE_MOBILE_FOTA;
2034 }
2035 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
2036 return TYPE_MOBILE_DUN;
2037 }
2038 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
2039 return TYPE_MOBILE_SUPL;
2040 }
2041 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2042 return TYPE_MOBILE_MMS;
2043 }
2044 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
2045 return TYPE_MOBILE_HIPRI;
2046 }
2047 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
2048 return TYPE_WIFI_P2P;
2049 }
2050 return TYPE_NONE;
2051 }
2052
2053 private static class LegacyRequest {
2054 NetworkCapabilities networkCapabilities;
2055 NetworkRequest networkRequest;
2056 int expireSequenceNumber;
2057 Network currentNetwork;
2058 int delay = -1;
2059
2060 private void clearDnsBinding() {
2061 if (currentNetwork != null) {
2062 currentNetwork = null;
2063 setProcessDefaultNetworkForHostResolution(null);
2064 }
2065 }
2066
2067 NetworkCallback networkCallback = new NetworkCallback() {
2068 @Override
2069 public void onAvailable(Network network) {
2070 currentNetwork = network;
2071 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
2072 setProcessDefaultNetworkForHostResolution(network);
2073 }
2074 @Override
2075 public void onLost(Network network) {
2076 if (network.equals(currentNetwork)) clearDnsBinding();
2077 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2078 }
2079 };
2080 }
2081
2082 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2083 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2084 new HashMap<>();
2085
2086 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2087 synchronized (sLegacyRequests) {
2088 LegacyRequest l = sLegacyRequests.get(netCap);
2089 if (l != null) return l.networkRequest;
2090 }
2091 return null;
2092 }
2093
2094 private void renewRequestLocked(LegacyRequest l) {
2095 l.expireSequenceNumber++;
2096 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2097 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2098 }
2099
2100 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2101 int ourSeqNum = -1;
2102 synchronized (sLegacyRequests) {
2103 LegacyRequest l = sLegacyRequests.get(netCap);
2104 if (l == null) return;
2105 ourSeqNum = l.expireSequenceNumber;
2106 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2107 }
2108 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2109 }
2110
2111 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2112 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2113 int delay = -1;
2114 int type = legacyTypeForNetworkCapabilities(netCap);
2115 try {
2116 delay = mService.getRestoreDefaultNetworkDelay(type);
2117 } catch (RemoteException e) {
2118 throw e.rethrowFromSystemServer();
2119 }
2120 LegacyRequest l = new LegacyRequest();
2121 l.networkCapabilities = netCap;
2122 l.delay = delay;
2123 l.expireSequenceNumber = 0;
2124 l.networkRequest = sendRequestForNetwork(
2125 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2126 if (l.networkRequest == null) return null;
2127 sLegacyRequests.put(netCap, l);
2128 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2129 return l.networkRequest;
2130 }
2131
2132 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2133 if (delay >= 0) {
2134 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2135 CallbackHandler handler = getDefaultHandler();
2136 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2137 handler.sendMessageDelayed(msg, delay);
2138 }
2139 }
2140
2141 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2142 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2143 final LegacyRequest l;
2144 synchronized (sLegacyRequests) {
2145 l = sLegacyRequests.remove(netCap);
2146 }
2147 if (l == null) return false;
2148 unregisterNetworkCallback(l.networkCallback);
2149 l.clearDnsBinding();
2150 return true;
2151 }
2152
2153 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2154 static {
2155 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2156 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2157 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2158 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2159 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2160 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2161 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2162 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2163 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2164 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2165 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2166 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2167 }
2168
2169 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2170 static {
2171 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2172 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2173 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2174 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2175 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2176 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2177 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2178 }
2179
2180 /**
2181 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2182 * instance suitable for registering a request or callback. Throws an
2183 * IllegalArgumentException if no mapping from the legacy type to
2184 * NetworkCapabilities is known.
2185 *
2186 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2187 * to find the network instead.
2188 * @hide
2189 */
2190 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2191 final NetworkCapabilities nc = new NetworkCapabilities();
2192
2193 // Map from type to transports.
2194 final int NOT_FOUND = -1;
2195 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002196 if (transport == NOT_FOUND) {
2197 throw new IllegalArgumentException("unknown legacy type: " + type);
2198 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002199 nc.addTransportType(transport);
2200
2201 // Map from type to capabilities.
2202 nc.addCapability(sLegacyTypeToCapability.get(
2203 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2204 nc.maybeMarkCapabilitiesRestricted();
2205 return nc;
2206 }
2207
2208 /** @hide */
2209 public static class PacketKeepaliveCallback {
2210 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2211 public PacketKeepaliveCallback() {
2212 }
2213 /** The requested keepalive was successfully started. */
2214 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2215 public void onStarted() {}
2216 /** The keepalive was successfully stopped. */
2217 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2218 public void onStopped() {}
2219 /** An error occurred. */
2220 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2221 public void onError(int error) {}
2222 }
2223
2224 /**
2225 * Allows applications to request that the system periodically send specific packets on their
2226 * behalf, using hardware offload to save battery power.
2227 *
2228 * To request that the system send keepalives, call one of the methods that return a
2229 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2230 * passing in a non-null callback. If the callback is successfully started, the callback's
2231 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2232 * specifying one of the {@code ERROR_*} constants in this class.
2233 *
2234 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2235 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2236 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2237 *
2238 * @deprecated Use {@link SocketKeepalive} instead.
2239 *
2240 * @hide
2241 */
2242 public class PacketKeepalive {
2243
2244 private static final String TAG = "PacketKeepalive";
2245
2246 /** @hide */
2247 public static final int SUCCESS = 0;
2248
2249 /** @hide */
2250 public static final int NO_KEEPALIVE = -1;
2251
2252 /** @hide */
2253 public static final int BINDER_DIED = -10;
2254
2255 /** The specified {@code Network} is not connected. */
2256 public static final int ERROR_INVALID_NETWORK = -20;
2257 /** The specified IP addresses are invalid. For example, the specified source IP address is
2258 * not configured on the specified {@code Network}. */
2259 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2260 /** The requested port is invalid. */
2261 public static final int ERROR_INVALID_PORT = -22;
2262 /** The packet length is invalid (e.g., too long). */
2263 public static final int ERROR_INVALID_LENGTH = -23;
2264 /** The packet transmission interval is invalid (e.g., too short). */
2265 public static final int ERROR_INVALID_INTERVAL = -24;
2266
2267 /** The hardware does not support this request. */
2268 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2269 /** The hardware returned an error. */
2270 public static final int ERROR_HARDWARE_ERROR = -31;
2271
2272 /** The NAT-T destination port for IPsec */
2273 public static final int NATT_PORT = 4500;
2274
2275 /** The minimum interval in seconds between keepalive packet transmissions */
2276 public static final int MIN_INTERVAL = 10;
2277
2278 private final Network mNetwork;
2279 private final ISocketKeepaliveCallback mCallback;
2280 private final ExecutorService mExecutor;
2281
2282 private volatile Integer mSlot;
2283
2284 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2285 public void stop() {
2286 try {
2287 mExecutor.execute(() -> {
2288 try {
2289 if (mSlot != null) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09002290 // TODO : this is incorrect, because in the presence of auto on/off
2291 // keepalive the slot associated with this keepalive can have
2292 // changed. Also, this actually causes another problem where some other
2293 // app might stop your keepalive if it just knows the network and
2294 // the slot and goes through the trouble of grabbing the aidl object.
2295 // This code should use the callback to identify what keepalive to
2296 // stop instead.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002297 mService.stopKeepalive(mNetwork, mSlot);
2298 }
2299 } catch (RemoteException e) {
2300 Log.e(TAG, "Error stopping packet keepalive: ", e);
2301 throw e.rethrowFromSystemServer();
2302 }
2303 });
2304 } catch (RejectedExecutionException e) {
2305 // The internal executor has already stopped due to previous event.
2306 }
2307 }
2308
2309 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002310 Objects.requireNonNull(network, "network cannot be null");
2311 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002312 mNetwork = network;
2313 mExecutor = Executors.newSingleThreadExecutor();
2314 mCallback = new ISocketKeepaliveCallback.Stub() {
2315 @Override
2316 public void onStarted(int slot) {
2317 final long token = Binder.clearCallingIdentity();
2318 try {
2319 mExecutor.execute(() -> {
2320 mSlot = slot;
2321 callback.onStarted();
2322 });
2323 } finally {
2324 Binder.restoreCallingIdentity(token);
2325 }
2326 }
2327
2328 @Override
2329 public void onStopped() {
2330 final long token = Binder.clearCallingIdentity();
2331 try {
2332 mExecutor.execute(() -> {
2333 mSlot = null;
2334 callback.onStopped();
2335 });
2336 } finally {
2337 Binder.restoreCallingIdentity(token);
2338 }
2339 mExecutor.shutdown();
2340 }
2341
2342 @Override
2343 public void onError(int error) {
2344 final long token = Binder.clearCallingIdentity();
2345 try {
2346 mExecutor.execute(() -> {
2347 mSlot = null;
2348 callback.onError(error);
2349 });
2350 } finally {
2351 Binder.restoreCallingIdentity(token);
2352 }
2353 mExecutor.shutdown();
2354 }
2355
2356 @Override
2357 public void onDataReceived() {
2358 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2359 // this callback when data is received.
2360 }
2361 };
2362 }
2363 }
2364
2365 /**
2366 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2367 *
2368 * @deprecated Use {@link #createSocketKeepalive} instead.
2369 *
2370 * @hide
2371 */
2372 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2373 public PacketKeepalive startNattKeepalive(
2374 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2375 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2376 final PacketKeepalive k = new PacketKeepalive(network, callback);
2377 try {
2378 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2379 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2380 } catch (RemoteException e) {
2381 Log.e(TAG, "Error starting packet keepalive: ", e);
2382 throw e.rethrowFromSystemServer();
2383 }
2384 return k;
2385 }
2386
2387 // Construct an invalid fd.
2388 private ParcelFileDescriptor createInvalidFd() {
2389 final int invalidFd = -1;
2390 return ParcelFileDescriptor.adoptFd(invalidFd);
2391 }
2392
2393 /**
2394 * Request that keepalives be started on a IPsec NAT-T socket.
2395 *
2396 * @param network The {@link Network} the socket is on.
2397 * @param socket The socket that needs to be kept alive.
2398 * @param source The source address of the {@link UdpEncapsulationSocket}.
2399 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2400 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2401 * must run callback sequentially, otherwise the order of callbacks cannot be
2402 * guaranteed.
2403 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2404 * changes. Must be extended by applications that use this API.
2405 *
2406 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2407 * given socket.
2408 **/
2409 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2410 @NonNull UdpEncapsulationSocket socket,
2411 @NonNull InetAddress source,
2412 @NonNull InetAddress destination,
2413 @NonNull @CallbackExecutor Executor executor,
2414 @NonNull Callback callback) {
2415 ParcelFileDescriptor dup;
2416 try {
2417 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2418 // which cannot be obtained by the app process.
2419 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2420 } catch (IOException ignored) {
2421 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2422 // ERROR_INVALID_SOCKET.
2423 dup = createInvalidFd();
2424 }
2425 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2426 destination, executor, callback);
2427 }
2428
2429 /**
2430 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2431 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2432 *
2433 * @param network The {@link Network} the socket is on.
2434 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2435 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2436 * from that port.
2437 * @param source The source address of the {@link UdpEncapsulationSocket}.
2438 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2439 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2440 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2441 * must run callback sequentially, otherwise the order of callbacks cannot be
2442 * guaranteed.
2443 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2444 * changes. Must be extended by applications that use this API.
2445 *
2446 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2447 * given socket.
2448 * @hide
2449 */
2450 @SystemApi
2451 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2452 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2453 @NonNull ParcelFileDescriptor pfd,
2454 @NonNull InetAddress source,
2455 @NonNull InetAddress destination,
2456 @NonNull @CallbackExecutor Executor executor,
2457 @NonNull Callback callback) {
2458 ParcelFileDescriptor dup;
2459 try {
2460 // TODO: Consider remove unnecessary dup.
2461 dup = pfd.dup();
2462 } catch (IOException ignored) {
2463 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2464 // ERROR_INVALID_SOCKET.
2465 dup = createInvalidFd();
2466 }
2467 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002468 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002469 }
2470
2471 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002472 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002473 *
2474 * @param network The {@link Network} the socket is on.
2475 * @param socket The socket that needs to be kept alive.
2476 * @param executor The executor on which callback will be invoked. This implementation assumes
2477 * the provided {@link Executor} runs the callbacks in sequence with no
2478 * concurrency. Failing this, no guarantee of correctness can be made. It is
2479 * the responsibility of the caller to ensure the executor provides this
2480 * guarantee. A simple way of creating such an executor is with the standard
2481 * tool {@code Executors.newSingleThreadExecutor}.
2482 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2483 * changes. Must be extended by applications that use this API.
2484 *
2485 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2486 * given socket.
2487 * @hide
2488 */
2489 @SystemApi
2490 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2491 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2492 @NonNull Socket socket,
2493 @NonNull Executor executor,
2494 @NonNull Callback callback) {
2495 ParcelFileDescriptor dup;
2496 try {
2497 dup = ParcelFileDescriptor.fromSocket(socket);
2498 } catch (UncheckedIOException ignored) {
2499 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2500 // ERROR_INVALID_SOCKET.
2501 dup = createInvalidFd();
2502 }
2503 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2504 }
2505
2506 /**
2507 * Ensure that a network route exists to deliver traffic to the specified
2508 * host via the specified network interface. An attempt to add a route that
2509 * already exists is ignored, but treated as successful.
2510 *
2511 * <p>This method requires the caller to hold either the
2512 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2513 * or the ability to modify system settings as determined by
2514 * {@link android.provider.Settings.System#canWrite}.</p>
2515 *
2516 * @param networkType the type of the network over which traffic to the specified
2517 * host is to be routed
2518 * @param hostAddress the IP address of the host to which the route is desired
2519 * @return {@code true} on success, {@code false} on failure
2520 *
2521 * @deprecated Deprecated in favor of the
2522 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2523 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2524 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2525 * throw {@code UnsupportedOperationException} if called.
2526 * @removed
2527 */
2528 @Deprecated
2529 public boolean requestRouteToHost(int networkType, int hostAddress) {
2530 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2531 }
2532
2533 /**
2534 * Ensure that a network route exists to deliver traffic to the specified
2535 * host via the specified network interface. An attempt to add a route that
2536 * already exists is ignored, but treated as successful.
2537 *
2538 * <p>This method requires the caller to hold either the
2539 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2540 * or the ability to modify system settings as determined by
2541 * {@link android.provider.Settings.System#canWrite}.</p>
2542 *
2543 * @param networkType the type of the network over which traffic to the specified
2544 * host is to be routed
2545 * @param hostAddress the IP address of the host to which the route is desired
2546 * @return {@code true} on success, {@code false} on failure
2547 * @hide
2548 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2549 * {@link #bindProcessToNetwork} API.
2550 */
2551 @Deprecated
2552 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002553 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002554 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2555 checkLegacyRoutingApiAccess();
2556 try {
2557 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2558 mContext.getOpPackageName(), getAttributionTag());
2559 } catch (RemoteException e) {
2560 throw e.rethrowFromSystemServer();
2561 }
2562 }
2563
2564 /**
2565 * @return the context's attribution tag
2566 */
2567 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2568 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002569 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002570 }
2571
2572 /**
2573 * Returns the value of the setting for background data usage. If false,
2574 * applications should not use the network if the application is not in the
2575 * foreground. Developers should respect this setting, and check the value
2576 * of this before performing any background data operations.
2577 * <p>
2578 * All applications that have background services that use the network
2579 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2580 * <p>
2581 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2582 * background data depends on several combined factors, and this method will
2583 * always return {@code true}. Instead, when background data is unavailable,
2584 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2585 *
2586 * @return Whether background data usage is allowed.
2587 */
2588 @Deprecated
2589 public boolean getBackgroundDataSetting() {
2590 // assume that background data is allowed; final authority is
2591 // NetworkInfo which may be blocked.
2592 return true;
2593 }
2594
2595 /**
2596 * Sets the value of the setting for background data usage.
2597 *
2598 * @param allowBackgroundData Whether an application should use data while
2599 * it is in the background.
2600 *
2601 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2602 * @see #getBackgroundDataSetting()
2603 * @hide
2604 */
2605 @Deprecated
2606 @UnsupportedAppUsage
2607 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2608 // ignored
2609 }
2610
2611 /**
2612 * @hide
2613 * @deprecated Talk to TelephonyManager directly
2614 */
2615 @Deprecated
2616 @UnsupportedAppUsage
2617 public boolean getMobileDataEnabled() {
2618 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2619 if (tm != null) {
2620 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2621 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2622 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2623 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2624 + " retVal=" + retVal);
2625 return retVal;
2626 }
2627 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2628 return false;
2629 }
2630
2631 /**
2632 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2633 * to find out when the system default network has gone in to a high power state.
2634 */
2635 public interface OnNetworkActiveListener {
2636 /**
2637 * Called on the main thread of the process to report that the current data network
2638 * has become active, and it is now a good time to perform any pending network
2639 * operations. Note that this listener only tells you when the network becomes
2640 * active; if at any other time you want to know whether it is active (and thus okay
2641 * to initiate network traffic), you can retrieve its instantaneous state with
2642 * {@link ConnectivityManager#isDefaultNetworkActive}.
2643 */
2644 void onNetworkActive();
2645 }
2646
Chiachang Wang2de41682021-09-23 10:46:03 +08002647 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002648 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2649 mNetworkActivityListeners = new ArrayMap<>();
2650
2651 /**
2652 * Start listening to reports when the system's default data network is active, meaning it is
2653 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2654 * to determine the current state of the system's default network after registering the
2655 * listener.
2656 * <p>
2657 * If the process default network has been set with
2658 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2659 * reflect the process's default, but the system default.
2660 *
2661 * @param l The listener to be told when the network is active.
2662 */
2663 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002664 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002665 @Override
2666 public void onNetworkActive() throws RemoteException {
2667 l.onNetworkActive();
2668 }
2669 };
2670
Chiachang Wang2de41682021-09-23 10:46:03 +08002671 synchronized (mNetworkActivityListeners) {
2672 try {
2673 mService.registerNetworkActivityListener(rl);
2674 mNetworkActivityListeners.put(l, rl);
2675 } catch (RemoteException e) {
2676 throw e.rethrowFromSystemServer();
2677 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002678 }
2679 }
2680
2681 /**
2682 * Remove network active listener previously registered with
2683 * {@link #addDefaultNetworkActiveListener}.
2684 *
2685 * @param l Previously registered listener.
2686 */
2687 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002688 synchronized (mNetworkActivityListeners) {
2689 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2690 if (rl == null) {
2691 throw new IllegalArgumentException("Listener was not registered.");
2692 }
2693 try {
2694 mService.unregisterNetworkActivityListener(rl);
2695 mNetworkActivityListeners.remove(l);
2696 } catch (RemoteException e) {
2697 throw e.rethrowFromSystemServer();
2698 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002699 }
2700 }
2701
2702 /**
2703 * Return whether the data network is currently active. An active network means that
2704 * it is currently in a high power state for performing data transmission. On some
2705 * types of networks, it may be expensive to move and stay in such a state, so it is
2706 * more power efficient to batch network traffic together when the radio is already in
2707 * this state. This method tells you whether right now is currently a good time to
2708 * initiate network traffic, as the network is already active.
2709 */
2710 public boolean isDefaultNetworkActive() {
2711 try {
lucaslin709eb842021-01-21 02:04:15 +08002712 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002713 } catch (RemoteException e) {
2714 throw e.rethrowFromSystemServer();
2715 }
2716 }
2717
2718 /**
2719 * {@hide}
2720 */
2721 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002722 this(context, service, true /* newStatic */);
2723 }
2724
2725 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002726 mContext = Objects.requireNonNull(context, "missing context");
2727 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002728 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2729 // different ConnectivityManager, but that's still OK considering its usage.
2730 if (sInstance == null && newStatic) {
2731 final Context appContext = mContext.getApplicationContext();
2732 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2733 // If the application context is null, we're either in the system process or
2734 // it's the application context very early in app initialization. In both these
2735 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2736 // service. http://b/27532714 .
2737 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2738 false /* newStatic */);
2739 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002740 }
2741
2742 /** {@hide} */
2743 @UnsupportedAppUsage
2744 public static ConnectivityManager from(Context context) {
2745 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2746 }
2747
2748 /** @hide */
2749 public NetworkRequest getDefaultRequest() {
2750 try {
2751 // This is not racy as the default request is final in ConnectivityService.
2752 return mService.getDefaultRequest();
2753 } catch (RemoteException e) {
2754 throw e.rethrowFromSystemServer();
2755 }
2756 }
2757
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002758 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002759 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002760 * happened.
2761 *
2762 * @return {@code true} iff the package is allowed to write settings.
2763 */
2764 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2765 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2766 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2767 boolean throwException) {
2768 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002769 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002770 }
2771
2772 /**
2773 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2774 * situations where a Context pointer is unavailable.
2775 * @hide
2776 */
2777 @Deprecated
2778 static ConnectivityManager getInstanceOrNull() {
2779 return sInstance;
2780 }
2781
2782 /**
2783 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2784 * situations where a Context pointer is unavailable.
2785 * @hide
2786 */
2787 @Deprecated
2788 @UnsupportedAppUsage
2789 private static ConnectivityManager getInstance() {
2790 if (getInstanceOrNull() == null) {
2791 throw new IllegalStateException("No ConnectivityManager yet constructed");
2792 }
2793 return getInstanceOrNull();
2794 }
2795
2796 /**
2797 * Get the set of tetherable, available interfaces. This list is limited by
2798 * device configuration and current interface existence.
2799 *
2800 * @return an array of 0 or more Strings of tetherable interface names.
2801 *
2802 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2803 * {@hide}
2804 */
2805 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2806 @UnsupportedAppUsage
2807 @Deprecated
2808 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002809 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002810 }
2811
2812 /**
2813 * Get the set of tethered interfaces.
2814 *
2815 * @return an array of 0 or more String of currently tethered interface names.
2816 *
2817 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2818 * {@hide}
2819 */
2820 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2821 @UnsupportedAppUsage
2822 @Deprecated
2823 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002824 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002825 }
2826
2827 /**
2828 * Get the set of interface names which attempted to tether but
2829 * failed. Re-attempting to tether may cause them to reset to the Tethered
2830 * state. Alternatively, causing the interface to be destroyed and recreated
2831 * may cause them to reset to the available state.
2832 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2833 * information on the cause of the errors.
2834 *
2835 * @return an array of 0 or more String indicating the interface names
2836 * which failed to tether.
2837 *
2838 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2839 * {@hide}
2840 */
2841 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2842 @UnsupportedAppUsage
2843 @Deprecated
2844 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002845 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002846 }
2847
2848 /**
2849 * Get the set of tethered dhcp ranges.
2850 *
2851 * @deprecated This method is not supported.
2852 * TODO: remove this function when all of clients are removed.
2853 * {@hide}
2854 */
2855 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2856 @Deprecated
2857 public String[] getTetheredDhcpRanges() {
2858 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2859 }
2860
2861 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002862 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002863 * on the interface, forward and NAT IP packets and forward DNS requests
2864 * to the best active upstream network interface. Note that if no upstream
2865 * IP network interface is available, dhcp will still run and traffic will be
2866 * allowed between the tethered devices and this device, though upstream net
2867 * access will of course fail until an upstream network interface becomes
2868 * active.
2869 *
2870 * <p>This method requires the caller to hold either the
2871 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2872 * or the ability to modify system settings as determined by
2873 * {@link android.provider.Settings.System#canWrite}.</p>
2874 *
2875 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2876 * and WifiStateMachine which need direct access. All other clients should use
2877 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2878 * logic.</p>
2879 *
2880 * @param iface the interface name to tether.
2881 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2882 * @deprecated Use {@link TetheringManager#startTethering} instead
2883 *
2884 * {@hide}
2885 */
2886 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2887 @Deprecated
2888 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002889 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002890 }
2891
2892 /**
2893 * Stop tethering the named interface.
2894 *
2895 * <p>This method requires the caller to hold either the
2896 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2897 * or the ability to modify system settings as determined by
2898 * {@link android.provider.Settings.System#canWrite}.</p>
2899 *
2900 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2901 * and WifiStateMachine which need direct access. All other clients should use
2902 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2903 * logic.</p>
2904 *
2905 * @param iface the interface name to untether.
2906 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2907 *
2908 * {@hide}
2909 */
2910 @UnsupportedAppUsage
2911 @Deprecated
2912 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002913 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002914 }
2915
2916 /**
2917 * Check if the device allows for tethering. It may be disabled via
2918 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2919 * due to device configuration.
2920 *
2921 * <p>If this app does not have permission to use this API, it will always
2922 * return false rather than throw an exception.</p>
2923 *
2924 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2925 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2926 *
2927 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2928 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2929 *
2930 * @return a boolean - {@code true} indicating Tethering is supported.
2931 *
2932 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2933 * {@hide}
2934 */
2935 @SystemApi
2936 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2937 android.Manifest.permission.WRITE_SETTINGS})
2938 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002939 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002940 }
2941
2942 /**
2943 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2944 *
2945 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2946 * @hide
2947 */
2948 @SystemApi
2949 @Deprecated
2950 public static abstract class OnStartTetheringCallback {
2951 /**
2952 * Called when tethering has been successfully started.
2953 */
2954 public void onTetheringStarted() {}
2955
2956 /**
2957 * Called when starting tethering failed.
2958 */
2959 public void onTetheringFailed() {}
2960 }
2961
2962 /**
2963 * Convenient overload for
2964 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2965 * handler to run on the current thread's {@link Looper}.
2966 *
2967 * @deprecated Use {@link TetheringManager#startTethering} instead.
2968 * @hide
2969 */
2970 @SystemApi
2971 @Deprecated
2972 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2973 public void startTethering(int type, boolean showProvisioningUi,
2974 final OnStartTetheringCallback callback) {
2975 startTethering(type, showProvisioningUi, callback, null);
2976 }
2977
2978 /**
2979 * Runs tether provisioning for the given type if needed and then starts tethering if
2980 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2981 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2982 * schedules tether provisioning re-checks if appropriate.
2983 *
2984 * @param type The type of tethering to start. Must be one of
2985 * {@link ConnectivityManager.TETHERING_WIFI},
2986 * {@link ConnectivityManager.TETHERING_USB}, or
2987 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2988 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2989 * is one. This should be true the first time this function is called and also any time
2990 * the user can see this UI. It gives users information from their carrier about the
2991 * check failing and how they can sign up for tethering if possible.
2992 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2993 * of the result of trying to tether.
2994 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2995 *
2996 * @deprecated Use {@link TetheringManager#startTethering} instead.
2997 * @hide
2998 */
2999 @SystemApi
3000 @Deprecated
3001 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3002 public void startTethering(int type, boolean showProvisioningUi,
3003 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003004 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003005
3006 final Executor executor = new Executor() {
3007 @Override
3008 public void execute(Runnable command) {
3009 if (handler == null) {
3010 command.run();
3011 } else {
3012 handler.post(command);
3013 }
3014 }
3015 };
3016
3017 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
3018 @Override
3019 public void onTetheringStarted() {
3020 callback.onTetheringStarted();
3021 }
3022
3023 @Override
3024 public void onTetheringFailed(final int error) {
3025 callback.onTetheringFailed();
3026 }
3027 };
3028
3029 final TetheringRequest request = new TetheringRequest.Builder(type)
3030 .setShouldShowEntitlementUi(showProvisioningUi).build();
3031
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003032 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003033 }
3034
3035 /**
3036 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
3037 * applicable.
3038 *
3039 * @param type The type of tethering to stop. Must be one of
3040 * {@link ConnectivityManager.TETHERING_WIFI},
3041 * {@link ConnectivityManager.TETHERING_USB}, or
3042 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3043 *
3044 * @deprecated Use {@link TetheringManager#stopTethering} instead.
3045 * @hide
3046 */
3047 @SystemApi
3048 @Deprecated
3049 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3050 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003051 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003052 }
3053
3054 /**
3055 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
3056 * upstream status.
3057 *
3058 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
3059 * @hide
3060 */
3061 @SystemApi
3062 @Deprecated
3063 public abstract static class OnTetheringEventCallback {
3064
3065 /**
3066 * Called when tethering upstream changed. This can be called multiple times and can be
3067 * called any time.
3068 *
3069 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
3070 * have any upstream.
3071 */
3072 public void onUpstreamChanged(@Nullable Network network) {}
3073 }
3074
3075 @GuardedBy("mTetheringEventCallbacks")
3076 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
3077 mTetheringEventCallbacks = new ArrayMap<>();
3078
3079 /**
3080 * Start listening to tethering change events. Any new added callback will receive the last
3081 * tethering status right away. If callback is registered when tethering has no upstream or
3082 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3083 * with a null argument. The same callback object cannot be registered twice.
3084 *
3085 * @param executor the executor on which callback will be invoked.
3086 * @param callback the callback to be called when tethering has change events.
3087 *
3088 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3089 * @hide
3090 */
3091 @SystemApi
3092 @Deprecated
3093 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3094 public void registerTetheringEventCallback(
3095 @NonNull @CallbackExecutor Executor executor,
3096 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003097 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003098
3099 final TetheringEventCallback tetherCallback =
3100 new TetheringEventCallback() {
3101 @Override
3102 public void onUpstreamChanged(@Nullable Network network) {
3103 callback.onUpstreamChanged(network);
3104 }
3105 };
3106
3107 synchronized (mTetheringEventCallbacks) {
3108 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003109 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003110 }
3111 }
3112
3113 /**
3114 * Remove tethering event callback previously registered with
3115 * {@link #registerTetheringEventCallback}.
3116 *
3117 * @param callback previously registered callback.
3118 *
3119 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3120 * @hide
3121 */
3122 @SystemApi
3123 @Deprecated
3124 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3125 public void unregisterTetheringEventCallback(
3126 @NonNull final OnTetheringEventCallback callback) {
3127 Objects.requireNonNull(callback, "The callback must be non-null");
3128 synchronized (mTetheringEventCallbacks) {
3129 final TetheringEventCallback tetherCallback =
3130 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003131 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003132 }
3133 }
3134
3135
3136 /**
3137 * Get the list of regular expressions that define any tetherable
3138 * USB network interfaces. If USB tethering is not supported by the
3139 * device, this list should be empty.
3140 *
3141 * @return an array of 0 or more regular expression Strings defining
3142 * what interfaces are considered tetherable usb interfaces.
3143 *
3144 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3145 * {@hide}
3146 */
3147 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3148 @UnsupportedAppUsage
3149 @Deprecated
3150 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003151 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003152 }
3153
3154 /**
3155 * Get the list of regular expressions that define any tetherable
3156 * Wifi network interfaces. If Wifi tethering is not supported by the
3157 * device, this list should be empty.
3158 *
3159 * @return an array of 0 or more regular expression Strings defining
3160 * what interfaces are considered tetherable wifi interfaces.
3161 *
3162 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3163 * {@hide}
3164 */
3165 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3166 @UnsupportedAppUsage
3167 @Deprecated
3168 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003169 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003170 }
3171
3172 /**
3173 * Get the list of regular expressions that define any tetherable
3174 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3175 * device, this list should be empty.
3176 *
3177 * @return an array of 0 or more regular expression Strings defining
3178 * what interfaces are considered tetherable bluetooth interfaces.
3179 *
3180 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3181 *TetheringManager.TetheringInterfaceRegexps)} instead.
3182 * {@hide}
3183 */
3184 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3185 @UnsupportedAppUsage
3186 @Deprecated
3187 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003188 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003189 }
3190
3191 /**
3192 * Attempt to both alter the mode of USB and Tethering of USB. A
3193 * utility method to deal with some of the complexity of USB - will
3194 * attempt to switch to Rndis and subsequently tether the resulting
3195 * interface on {@code true} or turn off tethering and switch off
3196 * Rndis on {@code false}.
3197 *
3198 * <p>This method requires the caller to hold either the
3199 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3200 * or the ability to modify system settings as determined by
3201 * {@link android.provider.Settings.System#canWrite}.</p>
3202 *
3203 * @param enable a boolean - {@code true} to enable tethering
3204 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3205 * @deprecated Use {@link TetheringManager#startTethering} instead
3206 *
3207 * {@hide}
3208 */
3209 @UnsupportedAppUsage
3210 @Deprecated
3211 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003212 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003213 }
3214
3215 /**
3216 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3217 * {@hide}
3218 */
3219 @SystemApi
3220 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003221 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003222 /**
3223 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3224 * {@hide}
3225 */
3226 @Deprecated
3227 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3228 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3229 /**
3230 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3231 * {@hide}
3232 */
3233 @Deprecated
3234 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3235 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3236 /**
3237 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3238 * {@hide}
3239 */
3240 @Deprecated
3241 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3242 /**
3243 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3244 * {@hide}
3245 */
3246 @Deprecated
3247 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3248 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3249 /**
3250 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3251 * {@hide}
3252 */
3253 @Deprecated
3254 public static final int TETHER_ERROR_MASTER_ERROR =
3255 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3256 /**
3257 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3258 * {@hide}
3259 */
3260 @Deprecated
3261 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3262 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3263 /**
3264 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3265 * {@hide}
3266 */
3267 @Deprecated
3268 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3269 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3270 /**
3271 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3272 * {@hide}
3273 */
3274 @Deprecated
3275 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3276 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3277 /**
3278 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3279 * {@hide}
3280 */
3281 @Deprecated
3282 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3283 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3284 /**
3285 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3286 * {@hide}
3287 */
3288 @Deprecated
3289 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3290 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3291 /**
3292 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3293 * {@hide}
3294 */
3295 @SystemApi
3296 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003297 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003298 /**
3299 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3300 * {@hide}
3301 */
3302 @Deprecated
3303 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3304 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3305 /**
3306 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3307 * {@hide}
3308 */
3309 @SystemApi
3310 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003311 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003312
3313 /**
3314 * Get a more detailed error code after a Tethering or Untethering
3315 * request asynchronously failed.
3316 *
3317 * @param iface The name of the interface of interest
3318 * @return error The error code of the last error tethering or untethering the named
3319 * interface
3320 *
3321 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3322 * {@hide}
3323 */
3324 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3325 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3326 @Deprecated
3327 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003328 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003329 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3330 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3331 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3332 // instead.
3333 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3334 }
3335 return error;
3336 }
3337
3338 /** @hide */
3339 @Retention(RetentionPolicy.SOURCE)
3340 @IntDef(value = {
3341 TETHER_ERROR_NO_ERROR,
3342 TETHER_ERROR_PROVISION_FAILED,
3343 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3344 })
3345 public @interface EntitlementResultCode {
3346 }
3347
3348 /**
3349 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3350 * entitlement succeeded.
3351 *
3352 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3353 * @hide
3354 */
3355 @SystemApi
3356 @Deprecated
3357 public interface OnTetheringEntitlementResultListener {
3358 /**
3359 * Called to notify entitlement result.
3360 *
3361 * @param resultCode an int value of entitlement result. It may be one of
3362 * {@link #TETHER_ERROR_NO_ERROR},
3363 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3364 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3365 */
3366 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3367 }
3368
3369 /**
3370 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003371 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3372 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003373 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003374 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003375 * any reason will update the cached value.
3376 *
3377 * @param type the downstream type of tethering. Must be one of
3378 * {@link #TETHERING_WIFI},
3379 * {@link #TETHERING_USB}, or
3380 * {@link #TETHERING_BLUETOOTH}.
3381 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3382 * @param executor the executor on which callback will be invoked.
3383 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3384 * notify the caller of the result of entitlement check. The listener may be called zero
3385 * or one time.
3386 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3387 * {@hide}
3388 */
3389 @SystemApi
3390 @Deprecated
3391 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3392 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3393 @NonNull @CallbackExecutor Executor executor,
3394 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003395 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003396 ResultReceiver wrappedListener = new ResultReceiver(null) {
3397 @Override
3398 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003399 final long token = Binder.clearCallingIdentity();
3400 try {
3401 executor.execute(() -> {
3402 listener.onTetheringEntitlementResult(resultCode);
3403 });
3404 } finally {
3405 Binder.restoreCallingIdentity(token);
3406 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003407 }
3408 };
3409
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003410 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003411 showEntitlementUi);
3412 }
3413
3414 /**
3415 * Report network connectivity status. This is currently used only
3416 * to alter status bar UI.
3417 * <p>This method requires the caller to hold the permission
3418 * {@link android.Manifest.permission#STATUS_BAR}.
3419 *
3420 * @param networkType The type of network you want to report on
3421 * @param percentage The quality of the connection 0 is bad, 100 is good
3422 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3423 * {@hide}
3424 */
3425 public void reportInetCondition(int networkType, int percentage) {
3426 printStackTrace();
3427 try {
3428 mService.reportInetCondition(networkType, percentage);
3429 } catch (RemoteException e) {
3430 throw e.rethrowFromSystemServer();
3431 }
3432 }
3433
3434 /**
3435 * Report a problem network to the framework. This provides a hint to the system
3436 * that there might be connectivity problems on this network and may cause
3437 * the framework to re-evaluate network connectivity and/or switch to another
3438 * network.
3439 *
3440 * @param network The {@link Network} the application was attempting to use
3441 * or {@code null} to indicate the current default network.
3442 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3443 * working and non-working connectivity.
3444 */
3445 @Deprecated
3446 public void reportBadNetwork(@Nullable Network network) {
3447 printStackTrace();
3448 try {
3449 // One of these will be ignored because it matches system's current state.
3450 // The other will trigger the necessary reevaluation.
3451 mService.reportNetworkConnectivity(network, true);
3452 mService.reportNetworkConnectivity(network, false);
3453 } catch (RemoteException e) {
3454 throw e.rethrowFromSystemServer();
3455 }
3456 }
3457
3458 /**
3459 * Report to the framework whether a network has working connectivity.
3460 * This provides a hint to the system that a particular network is providing
3461 * working connectivity or not. In response the framework may re-evaluate
3462 * the network's connectivity and might take further action thereafter.
3463 *
3464 * @param network The {@link Network} the application was attempting to use
3465 * or {@code null} to indicate the current default network.
3466 * @param hasConnectivity {@code true} if the application was able to successfully access the
3467 * Internet using {@code network} or {@code false} if not.
3468 */
3469 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3470 printStackTrace();
3471 try {
3472 mService.reportNetworkConnectivity(network, hasConnectivity);
3473 } catch (RemoteException e) {
3474 throw e.rethrowFromSystemServer();
3475 }
3476 }
3477
3478 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003479 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003480 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003481 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3482 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3483 * accessing any network, regardless of what the settings for that network are.
3484 *
3485 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3486 * proxy is likely to break networking on multiple networks. This method is only meant
3487 * for device policy clients looking to do general internal filtering or similar use cases.
3488 *
chiachangwang9473c592022-07-15 02:25:52 +00003489 * @see #getGlobalProxy
3490 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003491 *
3492 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3493 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003494 * @hide
3495 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003496 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003497 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003498 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003499 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003500 try {
3501 mService.setGlobalProxy(p);
3502 } catch (RemoteException e) {
3503 throw e.rethrowFromSystemServer();
3504 }
3505 }
3506
3507 /**
3508 * Retrieve any network-independent global HTTP proxy.
3509 *
3510 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3511 * if no global HTTP proxy is set.
3512 * @hide
3513 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003514 @SystemApi(client = MODULE_LIBRARIES)
3515 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003516 public ProxyInfo getGlobalProxy() {
3517 try {
3518 return mService.getGlobalProxy();
3519 } catch (RemoteException e) {
3520 throw e.rethrowFromSystemServer();
3521 }
3522 }
3523
3524 /**
3525 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3526 * network-specific HTTP proxy. If {@code network} is null, the
3527 * network-specific proxy returned is the proxy of the default active
3528 * network.
3529 *
3530 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3531 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3532 * or when {@code network} is {@code null},
3533 * the {@code ProxyInfo} for the default active network. Returns
3534 * {@code null} when no proxy applies or the caller doesn't have
3535 * permission to use {@code network}.
3536 * @hide
3537 */
3538 public ProxyInfo getProxyForNetwork(Network network) {
3539 try {
3540 return mService.getProxyForNetwork(network);
3541 } catch (RemoteException e) {
3542 throw e.rethrowFromSystemServer();
3543 }
3544 }
3545
3546 /**
3547 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3548 * otherwise if this process is bound to a {@link Network} using
3549 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3550 * the default network's proxy is returned.
3551 *
3552 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3553 * HTTP proxy is active.
3554 */
3555 @Nullable
3556 public ProxyInfo getDefaultProxy() {
3557 return getProxyForNetwork(getBoundNetworkForProcess());
3558 }
3559
3560 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003561 * Returns whether the hardware supports the given network type.
3562 *
3563 * This doesn't indicate there is coverage or such a network is available, just whether the
3564 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3565 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003566 *
3567 * @param networkType The network type we'd like to check
3568 * @return {@code true} if supported, else {@code false}
3569 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3570 * @hide
3571 */
3572 @Deprecated
3573 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3574 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3575 public boolean isNetworkSupported(int networkType) {
3576 try {
3577 return mService.isNetworkSupported(networkType);
3578 } catch (RemoteException e) {
3579 throw e.rethrowFromSystemServer();
3580 }
3581 }
3582
3583 /**
3584 * Returns if the currently active data network is metered. A network is
3585 * classified as metered when the user is sensitive to heavy data usage on
3586 * that connection due to monetary costs, data limitations or
3587 * battery/performance issues. You should check this before doing large
3588 * data transfers, and warn the user or delay the operation until another
3589 * network is available.
3590 *
3591 * @return {@code true} if large transfers should be avoided, otherwise
3592 * {@code false}.
3593 */
3594 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3595 public boolean isActiveNetworkMetered() {
3596 try {
3597 return mService.isActiveNetworkMetered();
3598 } catch (RemoteException e) {
3599 throw e.rethrowFromSystemServer();
3600 }
3601 }
3602
3603 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003604 * Set sign in error notification to visible or invisible
3605 *
3606 * @hide
3607 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3608 */
3609 @Deprecated
3610 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3611 String action) {
3612 try {
3613 mService.setProvisioningNotificationVisible(visible, networkType, action);
3614 } catch (RemoteException e) {
3615 throw e.rethrowFromSystemServer();
3616 }
3617 }
3618
3619 /**
3620 * Set the value for enabling/disabling airplane mode
3621 *
3622 * @param enable whether to enable airplane mode or not
3623 *
3624 * @hide
3625 */
3626 @RequiresPermission(anyOf = {
3627 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3628 android.Manifest.permission.NETWORK_SETTINGS,
3629 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3630 android.Manifest.permission.NETWORK_STACK})
3631 @SystemApi
3632 public void setAirplaneMode(boolean enable) {
3633 try {
3634 mService.setAirplaneMode(enable);
3635 } catch (RemoteException e) {
3636 throw e.rethrowFromSystemServer();
3637 }
3638 }
3639
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003640 /**
3641 * Registers the specified {@link NetworkProvider}.
3642 * Each listener must only be registered once. The listener can be unregistered with
3643 * {@link #unregisterNetworkProvider}.
3644 *
3645 * @param provider the provider to register
3646 * @return the ID of the provider. This ID must be used by the provider when registering
3647 * {@link android.net.NetworkAgent}s.
3648 * @hide
3649 */
3650 @SystemApi
3651 @RequiresPermission(anyOf = {
3652 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3653 android.Manifest.permission.NETWORK_FACTORY})
3654 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3655 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3656 throw new IllegalStateException("NetworkProviders can only be registered once");
3657 }
3658
3659 try {
3660 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3661 provider.getName());
3662 provider.setProviderId(providerId);
3663 } catch (RemoteException e) {
3664 throw e.rethrowFromSystemServer();
3665 }
3666 return provider.getProviderId();
3667 }
3668
3669 /**
3670 * Unregisters the specified NetworkProvider.
3671 *
3672 * @param provider the provider to unregister
3673 * @hide
3674 */
3675 @SystemApi
3676 @RequiresPermission(anyOf = {
3677 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3678 android.Manifest.permission.NETWORK_FACTORY})
3679 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3680 try {
3681 mService.unregisterNetworkProvider(provider.getMessenger());
3682 } catch (RemoteException e) {
3683 throw e.rethrowFromSystemServer();
3684 }
3685 provider.setProviderId(NetworkProvider.ID_NONE);
3686 }
3687
Chalard Jeand1b498b2021-01-05 08:40:09 +09003688 /**
3689 * Register or update a network offer with ConnectivityService.
3690 *
3691 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003692 * them to networking requests made by apps or the system. A callback identifies an offer
3693 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3694 * score and the capabilities of the network it might be able to bring up ; these act as
3695 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003696 * provider.
3697 *
3698 * The provider is under no obligation to be able to bring up the network it offers at any
3699 * given time. Instead, this mechanism is meant to limit requests received by providers
3700 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3701 * the quality of the network satisfying a given request to their own offer.
3702 *
3703 * An offer can be updated by calling this again with the same callback object. This is
3704 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3705 * provider with the changes caused by the changes in the offer.
3706 *
3707 * @param provider The provider making this offer.
3708 * @param score The prospective score of the network.
3709 * @param caps The prospective capabilities of the network.
3710 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003711 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003712 */
3713 @RequiresPermission(anyOf = {
3714 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3715 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003716 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003717 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3718 @NonNull final INetworkOfferCallback callback) {
3719 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003720 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003721 Objects.requireNonNull(score, "null score"),
3722 Objects.requireNonNull(caps, "null caps"),
3723 Objects.requireNonNull(callback, "null callback"));
3724 } catch (RemoteException e) {
3725 throw e.rethrowFromSystemServer();
3726 }
3727 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003728
Chalard Jeand1b498b2021-01-05 08:40:09 +09003729 /**
3730 * Withdraw a network offer made with {@link #offerNetwork}.
3731 *
3732 * @param callback The callback passed at registration time. This must be the same object
3733 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003734 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003735 */
3736 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3737 try {
3738 mService.unofferNetwork(Objects.requireNonNull(callback));
3739 } catch (RemoteException e) {
3740 throw e.rethrowFromSystemServer();
3741 }
3742 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003743 /** @hide exposed via the NetworkProvider class. */
3744 @RequiresPermission(anyOf = {
3745 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3746 android.Manifest.permission.NETWORK_FACTORY})
3747 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3748 try {
3749 mService.declareNetworkRequestUnfulfillable(request);
3750 } catch (RemoteException e) {
3751 throw e.rethrowFromSystemServer();
3752 }
3753 }
3754
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003755 /**
3756 * @hide
3757 * Register a NetworkAgent with ConnectivityService.
3758 * @return Network corresponding to NetworkAgent.
3759 */
3760 @RequiresPermission(anyOf = {
3761 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3762 android.Manifest.permission.NETWORK_FACTORY})
3763 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003764 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3765 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003766 try {
3767 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3768 } catch (RemoteException e) {
3769 throw e.rethrowFromSystemServer();
3770 }
3771 }
3772
3773 /**
3774 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3775 * changes. Should be extended by applications wanting notifications.
3776 *
3777 * A {@code NetworkCallback} is registered by calling
3778 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3779 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3780 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3781 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3782 * A {@code NetworkCallback} should be registered at most once at any time.
3783 * A {@code NetworkCallback} that has been unregistered can be registered again.
3784 */
3785 public static class NetworkCallback {
3786 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003787 * No flags associated with this callback.
3788 * @hide
3789 */
3790 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003791
Roshan Piuse08bc182020-12-22 15:10:42 -08003792 /**
lucaslinc582d502022-01-27 09:07:00 +08003793 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3794 *
3795 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3796 * Prior to Android 12, this information is always returned to apps holding the appropriate
3797 * permission, possibly noting that the app has used location.
3798 * <p>In Android 12 and above, by default the sent objects do not contain any location
3799 * information, even if the app holds the necessary permissions, and the system does not
3800 * take note of location usage by the app. Apps can request that location information is
3801 * included, in which case the system will check location permission and the location
3802 * toggle state, and take note of location usage by the app if any such information is
3803 * returned.
3804 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003805 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3806 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3807 * <p>
3808 * These include:
3809 * <li> Some transport info instances (retrieved via
3810 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3811 * contain location sensitive information.
3812 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003813 * sensitive for wifi suggestor apps (i.e using
3814 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003815 * </p>
3816 * <p>
3817 * Note:
3818 * <li> Retrieving this location sensitive information (subject to app's location
3819 * permissions) will be noted by system. </li>
3820 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003821 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003822 */
Roshan Pius189d0092021-03-11 21:16:44 -08003823 // Note: Some existing fields which are location sensitive may still be included without
3824 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003825 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3826
3827 /** @hide */
3828 @Retention(RetentionPolicy.SOURCE)
3829 @IntDef(flag = true, prefix = "FLAG_", value = {
3830 FLAG_NONE,
3831 FLAG_INCLUDE_LOCATION_INFO
3832 })
3833 public @interface Flag { }
3834
3835 /**
3836 * All the valid flags for error checking.
3837 */
3838 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3839
3840 public NetworkCallback() {
3841 this(FLAG_NONE);
3842 }
3843
3844 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003845 if ((flags & VALID_FLAGS) != flags) {
3846 throw new IllegalArgumentException("Invalid flags");
3847 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003848 mFlags = flags;
3849 }
3850
3851 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003852 * Called when the framework connects to a new network to evaluate whether it satisfies this
3853 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3854 * callback. There is no guarantee that this new network will satisfy any requests, or that
3855 * the network will stay connected for longer than the time necessary to evaluate it.
3856 * <p>
3857 * Most applications <b>should not</b> act on this callback, and should instead use
3858 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3859 * the framework in properly evaluating the network &mdash; for example, an application that
3860 * can automatically log in to a captive portal without user intervention.
3861 *
3862 * @param network The {@link Network} of the network that is being evaluated.
3863 *
3864 * @hide
3865 */
3866 public void onPreCheck(@NonNull Network network) {}
3867
3868 /**
3869 * Called when the framework connects and has declared a new network ready for use.
3870 * This callback may be called more than once if the {@link Network} that is
3871 * satisfying the request changes.
3872 *
3873 * @param network The {@link Network} of the satisfying network.
3874 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3875 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3876 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3877 * @hide
3878 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003879 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003880 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003881 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003882 // Internally only this method is called when a new network is available, and
3883 // it calls the callback in the same way and order that older versions used
3884 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003885 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3886 onBlockedStatusChanged(network, blocked);
3887 }
3888
3889 /**
3890 * Legacy variant of onAvailable that takes a boolean blocked reason.
3891 *
3892 * This method has never been public API, but it's not final, so there may be apps that
3893 * implemented it and rely on it being called. Do our best not to break them.
3894 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3895 * this method is called. There does not seem to be a way to avoid this.
3896 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3897 *
3898 * @hide
3899 */
3900 public void onAvailable(@NonNull Network network,
3901 @NonNull NetworkCapabilities networkCapabilities,
3902 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003903 onAvailable(network);
3904 if (!networkCapabilities.hasCapability(
3905 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3906 onNetworkSuspended(network);
3907 }
3908 onCapabilitiesChanged(network, networkCapabilities);
3909 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003910 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003911 }
3912
3913 /**
3914 * Called when the framework connects and has declared a new network ready for use.
3915 *
3916 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3917 * be available at the same time, and onAvailable will be called for each of these as they
3918 * appear.
3919 *
3920 * <p>For callbacks registered with {@link #requestNetwork} and
3921 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3922 * is the new best network for this request and is now tracked by this callback ; this
3923 * callback will no longer receive method calls about other networks that may have been
3924 * passed to this method previously. The previously-best network may have disconnected, or
3925 * it may still be around and the newly-best network may simply be better.
3926 *
3927 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3928 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3929 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3930 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3931 *
3932 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3933 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3934 * this callback as this is prone to race conditions (there is no guarantee the objects
3935 * returned by these methods will be current). Instead, wait for a call to
3936 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3937 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3938 * to be well-ordered with respect to other callbacks.
3939 *
3940 * @param network The {@link Network} of the satisfying network.
3941 */
3942 public void onAvailable(@NonNull Network network) {}
3943
3944 /**
3945 * Called when the network is about to be lost, typically because there are no outstanding
3946 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3947 * with the new replacement network for graceful handover. This method is not guaranteed
3948 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3949 * network is suddenly disconnected.
3950 *
3951 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3952 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3953 * this callback as this is prone to race conditions ; calling these methods while in a
3954 * callback may return an outdated or even a null object.
3955 *
3956 * @param network The {@link Network} that is about to be lost.
3957 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3958 * connected for graceful handover; note that the network may still
3959 * suffer a hard loss at any time.
3960 */
3961 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3962
3963 /**
3964 * Called when a network disconnects or otherwise no longer satisfies this request or
3965 * callback.
3966 *
3967 * <p>If the callback was registered with requestNetwork() or
3968 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3969 * returned by onAvailable() when that network is lost and no other network satisfies
3970 * the criteria of the request.
3971 *
3972 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3973 * each network which no longer satisfies the criteria of the callback.
3974 *
3975 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3976 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3977 * this callback as this is prone to race conditions ; calling these methods while in a
3978 * callback may return an outdated or even a null object.
3979 *
3980 * @param network The {@link Network} lost.
3981 */
3982 public void onLost(@NonNull Network network) {}
3983
3984 /**
3985 * Called if no network is found within the timeout time specified in
3986 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3987 * requested network request cannot be fulfilled (whether or not a timeout was
3988 * specified). When this callback is invoked the associated
3989 * {@link NetworkRequest} will have already been removed and released, as if
3990 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3991 */
3992 public void onUnavailable() {}
3993
3994 /**
3995 * Called when the network corresponding to this request changes capabilities but still
3996 * satisfies the requested criteria.
3997 *
3998 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3999 * to be called immediately after {@link #onAvailable}.
4000 *
4001 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
4002 * ConnectivityManager methods in this callback as this is prone to race conditions :
4003 * calling these methods while in a callback may return an outdated or even a null object.
4004 *
4005 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08004006 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004007 * network.
4008 */
4009 public void onCapabilitiesChanged(@NonNull Network network,
4010 @NonNull NetworkCapabilities networkCapabilities) {}
4011
4012 /**
4013 * Called when the network corresponding to this request changes {@link LinkProperties}.
4014 *
4015 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4016 * to be called immediately after {@link #onAvailable}.
4017 *
4018 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
4019 * ConnectivityManager methods in this callback as this is prone to race conditions :
4020 * calling these methods while in a callback may return an outdated or even a null object.
4021 *
4022 * @param network The {@link Network} whose link properties have changed.
4023 * @param linkProperties The new {@link LinkProperties} for this network.
4024 */
4025 public void onLinkPropertiesChanged(@NonNull Network network,
4026 @NonNull LinkProperties linkProperties) {}
4027
4028 /**
4029 * Called when the network the framework connected to for this request suspends data
4030 * transmission temporarily.
4031 *
4032 * <p>This generally means that while the TCP connections are still live temporarily
4033 * network data fails to transfer. To give a specific example, this is used on cellular
4034 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4035 * means read operations on sockets on this network will block once the buffers are
4036 * drained, and write operations will block once the buffers are full.
4037 *
4038 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4039 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4040 * this callback as this is prone to race conditions (there is no guarantee the objects
4041 * returned by these methods will be current).
4042 *
4043 * @hide
4044 */
4045 public void onNetworkSuspended(@NonNull Network network) {}
4046
4047 /**
4048 * Called when the network the framework connected to for this request
4049 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4050 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4051
4052 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4053 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4054 * this callback as this is prone to race conditions : calling these methods while in a
4055 * callback may return an outdated or even a null object.
4056 *
4057 * @hide
4058 */
4059 public void onNetworkResumed(@NonNull Network network) {}
4060
4061 /**
4062 * Called when access to the specified network is blocked or unblocked.
4063 *
4064 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4065 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4066 * this callback as this is prone to race conditions : calling these methods while in a
4067 * callback may return an outdated or even a null object.
4068 *
4069 * @param network The {@link Network} whose blocked status has changed.
4070 * @param blocked The blocked status of this {@link Network}.
4071 */
4072 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4073
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004074 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004075 * Called when access to the specified network is blocked or unblocked, or the reason for
4076 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004077 *
4078 * If a NetworkCallback object implements this method,
4079 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4080 *
4081 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4082 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4083 * this callback as this is prone to race conditions : calling these methods while in a
4084 * callback may return an outdated or even a null object.
4085 *
4086 * @param network The {@link Network} whose blocked status has changed.
4087 * @param blocked The blocked status of this {@link Network}.
4088 * @hide
4089 */
4090 @SystemApi(client = MODULE_LIBRARIES)
4091 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4092 onBlockedStatusChanged(network, blocked != 0);
4093 }
4094
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004095 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004096 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004097 }
4098
4099 /**
4100 * Constant error codes used by ConnectivityService to communicate about failures and errors
4101 * across a Binder boundary.
4102 * @hide
4103 */
4104 public interface Errors {
4105 int TOO_MANY_REQUESTS = 1;
4106 }
4107
4108 /** @hide */
4109 public static class TooManyRequestsException extends RuntimeException {}
4110
4111 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4112 switch (e.errorCode) {
4113 case Errors.TOO_MANY_REQUESTS:
4114 return new TooManyRequestsException();
4115 default:
4116 Log.w(TAG, "Unknown service error code " + e.errorCode);
4117 return new RuntimeException(e);
4118 }
4119 }
4120
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004121 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004122 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004123 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004124 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004125 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004126 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004127 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004128 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004129 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004130 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004131 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004132 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004133 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004134 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004135 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004136 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004137 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004138 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004139 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004140 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004141 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004142 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004143
4144 /** @hide */
4145 public static String getCallbackName(int whichCallback) {
4146 switch (whichCallback) {
4147 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4148 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4149 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4150 case CALLBACK_LOST: return "CALLBACK_LOST";
4151 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4152 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4153 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4154 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4155 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4156 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4157 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4158 default:
4159 return Integer.toString(whichCallback);
4160 }
4161 }
4162
zhujiatai79b0de92022-09-22 15:44:02 +08004163 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004164 private static final String TAG = "ConnectivityManager.CallbackHandler";
4165 private static final boolean DBG = false;
4166
4167 CallbackHandler(Looper looper) {
4168 super(looper);
4169 }
4170
4171 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004172 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004173 }
4174
4175 @Override
4176 public void handleMessage(Message message) {
4177 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004178 // the sInstance can't be null because to send this message a ConnectivityManager
4179 // instance must have been created prior to creating the thread on which this
4180 // Handler is running.
4181 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004182 return;
4183 }
4184
4185 final NetworkRequest request = getObject(message, NetworkRequest.class);
4186 final Network network = getObject(message, Network.class);
4187 final NetworkCallback callback;
4188 synchronized (sCallbacks) {
4189 callback = sCallbacks.get(request);
4190 if (callback == null) {
4191 Log.w(TAG,
4192 "callback not found for " + getCallbackName(message.what) + " message");
4193 return;
4194 }
4195 if (message.what == CALLBACK_UNAVAIL) {
4196 sCallbacks.remove(request);
4197 callback.networkRequest = ALREADY_UNREGISTERED;
4198 }
4199 }
4200 if (DBG) {
4201 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4202 }
4203
4204 switch (message.what) {
4205 case CALLBACK_PRECHECK: {
4206 callback.onPreCheck(network);
4207 break;
4208 }
4209 case CALLBACK_AVAILABLE: {
4210 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4211 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004212 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004213 break;
4214 }
4215 case CALLBACK_LOSING: {
4216 callback.onLosing(network, message.arg1);
4217 break;
4218 }
4219 case CALLBACK_LOST: {
4220 callback.onLost(network);
4221 break;
4222 }
4223 case CALLBACK_UNAVAIL: {
4224 callback.onUnavailable();
4225 break;
4226 }
4227 case CALLBACK_CAP_CHANGED: {
4228 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4229 callback.onCapabilitiesChanged(network, cap);
4230 break;
4231 }
4232 case CALLBACK_IP_CHANGED: {
4233 LinkProperties lp = getObject(message, LinkProperties.class);
4234 callback.onLinkPropertiesChanged(network, lp);
4235 break;
4236 }
4237 case CALLBACK_SUSPENDED: {
4238 callback.onNetworkSuspended(network);
4239 break;
4240 }
4241 case CALLBACK_RESUMED: {
4242 callback.onNetworkResumed(network);
4243 break;
4244 }
4245 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004246 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004247 }
4248 }
4249 }
4250
4251 private <T> T getObject(Message msg, Class<T> c) {
4252 return (T) msg.getData().getParcelable(c.getSimpleName());
4253 }
4254 }
4255
4256 private CallbackHandler getDefaultHandler() {
4257 synchronized (sCallbacks) {
4258 if (sCallbackHandler == null) {
4259 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4260 }
4261 return sCallbackHandler;
4262 }
4263 }
4264
4265 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4266 private static CallbackHandler sCallbackHandler;
4267
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004268 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4269 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4270 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004271 printStackTrace();
4272 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004273 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4274 throw new IllegalArgumentException("null NetworkCapabilities");
4275 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004276 final NetworkRequest request;
4277 final String callingPackageName = mContext.getOpPackageName();
4278 try {
4279 synchronized(sCallbacks) {
4280 if (callback.networkRequest != null
4281 && callback.networkRequest != ALREADY_UNREGISTERED) {
4282 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4283 // and requests (http://b/20701525).
4284 Log.e(TAG, "NetworkCallback was already registered");
4285 }
4286 Messenger messenger = new Messenger(handler);
4287 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004288 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004289 if (reqType == LISTEN) {
4290 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004291 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004292 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004293 } else {
4294 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004295 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4296 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004297 }
4298 if (request != null) {
4299 sCallbacks.put(request, callback);
4300 }
4301 callback.networkRequest = request;
4302 }
4303 } catch (RemoteException e) {
4304 throw e.rethrowFromSystemServer();
4305 } catch (ServiceSpecificException e) {
4306 throw convertServiceException(e);
4307 }
4308 return request;
4309 }
4310
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004311 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4312 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4313 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4314 legacyType, handler);
4315 }
4316
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004317 /**
4318 * Helper function to request a network with a particular legacy type.
4319 *
4320 * This API is only for use in internal system code that requests networks with legacy type and
4321 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4322 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4323 *
4324 * @param request {@link NetworkRequest} describing this request.
4325 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4326 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4327 * be a positive value (i.e. >0).
4328 * @param legacyType to specify the network type(#TYPE_*).
4329 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4330 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4331 * the callback must not be shared - it uniquely specifies this request.
4332 *
4333 * @hide
4334 */
4335 @SystemApi
4336 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4337 public void requestNetwork(@NonNull NetworkRequest request,
4338 int timeoutMs, int legacyType, @NonNull Handler handler,
4339 @NonNull NetworkCallback networkCallback) {
4340 if (legacyType == TYPE_NONE) {
4341 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4342 }
4343 CallbackHandler cbHandler = new CallbackHandler(handler);
4344 NetworkCapabilities nc = request.networkCapabilities;
4345 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4346 }
4347
4348 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004349 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004350 *
4351 * <p>This method will attempt to find the best network that matches the passed
4352 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4353 * criteria. The platform will evaluate which network is the best at its own discretion.
4354 * Throughput, latency, cost per byte, policy, user preference and other considerations
4355 * may be factored in the decision of what is considered the best network.
4356 *
4357 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4358 * matching this request, while always attempting to match the request to a better network if
4359 * possible. If a better match is found, the platform will switch this request to the now-best
4360 * network and inform the app of the newly best network by invoking
4361 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4362 * will not try to maintain any other network than the best one currently matching the request:
4363 * a network not matching any network request may be disconnected at any time.
4364 *
4365 * <p>For example, an application could use this method to obtain a connected cellular network
4366 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4367 * radio to consume additional power. Or, an application could inform the system that it wants
4368 * a network supporting sending MMSes and have the system let it know about the currently best
4369 * MMS-supporting network through the provided {@link NetworkCallback}.
4370 *
4371 * <p>The status of the request can be followed by listening to the various callbacks described
4372 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4373 * used to direct traffic to the network (although accessing some networks may be subject to
4374 * holding specific permissions). Callers will learn about the specific characteristics of the
4375 * network through
4376 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4377 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4378 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4379 * matching the request at any given time; therefore when a better network matching the request
4380 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4381 * with the new network after which no further updates are given about the previously-best
4382 * network, unless it becomes the best again at some later time. All callbacks are invoked
4383 * in order on the same thread, which by default is a thread created by the framework running
4384 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004385 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004386 * callbacks are invoked.
4387 *
4388 * <p>This{@link NetworkRequest} will live until released via
4389 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4390 * which point the system may let go of the network at any time.
4391 *
4392 * <p>A version of this method which takes a timeout is
4393 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4394 * wait for a limited amount of time for the network to become unavailable.
4395 *
4396 * <p>It is presently unsupported to request a network with mutable
4397 * {@link NetworkCapabilities} such as
4398 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4399 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4400 * as these {@code NetworkCapabilities} represent states that a particular
4401 * network may never attain, and whether a network will attain these states
4402 * is unknown prior to bringing up the network so the framework does not
4403 * know how to go about satisfying a request with these capabilities.
4404 *
4405 * <p>This method requires the caller to hold either the
4406 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4407 * or the ability to modify system settings as determined by
4408 * {@link android.provider.Settings.System#canWrite}.</p>
4409 *
4410 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4411 * number of outstanding requests to 100 per app (identified by their UID), shared with
4412 * all variants of this method, of {@link #registerNetworkCallback} as well as
4413 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4414 * Requesting a network with this method will count toward this limit. If this limit is
4415 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4416 * make sure to unregister the callbacks with
4417 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4418 *
4419 * @param request {@link NetworkRequest} describing this request.
4420 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4421 * the callback must not be shared - it uniquely specifies this request.
4422 * The callback is invoked on the default internal Handler.
4423 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4424 * @throws SecurityException if missing the appropriate permissions.
4425 * @throws RuntimeException if the app already has too many callbacks registered.
4426 */
4427 public void requestNetwork(@NonNull NetworkRequest request,
4428 @NonNull NetworkCallback networkCallback) {
4429 requestNetwork(request, networkCallback, getDefaultHandler());
4430 }
4431
4432 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004433 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004434 *
4435 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4436 * but runs all the callbacks on the passed Handler.
4437 *
4438 * <p>This method has the same permission requirements as
4439 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4440 * and throws the same exceptions in the same conditions.
4441 *
4442 * @param request {@link NetworkRequest} describing this request.
4443 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4444 * the callback must not be shared - it uniquely specifies this request.
4445 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4446 */
4447 public void requestNetwork(@NonNull NetworkRequest request,
4448 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4449 CallbackHandler cbHandler = new CallbackHandler(handler);
4450 NetworkCapabilities nc = request.networkCapabilities;
4451 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4452 }
4453
4454 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004455 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004456 * by a timeout.
4457 *
4458 * This function behaves identically to the non-timed-out version
4459 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4460 * is not found within the given time (in milliseconds) the
4461 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4462 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4463 * not have to be released if timed-out (it is automatically released). Unregistering a
4464 * request that timed out is not an error.
4465 *
4466 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4467 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4468 * for that purpose. Calling this method will attempt to bring up the requested network.
4469 *
4470 * <p>This method has the same permission requirements as
4471 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4472 * and throws the same exceptions in the same conditions.
4473 *
4474 * @param request {@link NetworkRequest} describing this request.
4475 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4476 * the callback must not be shared - it uniquely specifies this request.
4477 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4478 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4479 * be a positive value (i.e. >0).
4480 */
4481 public void requestNetwork(@NonNull NetworkRequest request,
4482 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4483 checkTimeout(timeoutMs);
4484 NetworkCapabilities nc = request.networkCapabilities;
4485 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4486 getDefaultHandler());
4487 }
4488
4489 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004490 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004491 * by a timeout.
4492 *
4493 * This method behaves identically to
4494 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4495 * on the passed Handler.
4496 *
4497 * <p>This method has the same permission requirements as
4498 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4499 * and throws the same exceptions in the same conditions.
4500 *
4501 * @param request {@link NetworkRequest} describing this request.
4502 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4503 * the callback must not be shared - it uniquely specifies this request.
4504 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4505 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4506 * before {@link NetworkCallback#onUnavailable} is called.
4507 */
4508 public void requestNetwork(@NonNull NetworkRequest request,
4509 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4510 checkTimeout(timeoutMs);
4511 CallbackHandler cbHandler = new CallbackHandler(handler);
4512 NetworkCapabilities nc = request.networkCapabilities;
4513 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4514 }
4515
4516 /**
4517 * The lookup key for a {@link Network} object included with the intent after
4518 * successfully finding a network for the applications request. Retrieve it with
4519 * {@link android.content.Intent#getParcelableExtra(String)}.
4520 * <p>
4521 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4522 * then you must get a ConnectivityManager instance before doing so.
4523 */
4524 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4525
4526 /**
4527 * The lookup key for a {@link NetworkRequest} object included with the intent after
4528 * successfully finding a network for the applications request. Retrieve it with
4529 * {@link android.content.Intent#getParcelableExtra(String)}.
4530 */
4531 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4532
4533
4534 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004535 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004536 *
4537 * This function behaves identically to the version that takes a NetworkCallback, but instead
4538 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4539 * the request may outlive the calling application and get called back when a suitable
4540 * network is found.
4541 * <p>
4542 * The operation is an Intent broadcast that goes to a broadcast receiver that
4543 * you registered with {@link Context#registerReceiver} or through the
4544 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4545 * <p>
4546 * The operation Intent is delivered with two extras, a {@link Network} typed
4547 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4548 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4549 * the original requests parameters. It is important to create a new,
4550 * {@link NetworkCallback} based request before completing the processing of the
4551 * Intent to reserve the network or it will be released shortly after the Intent
4552 * is processed.
4553 * <p>
4554 * If there is already a request for this Intent registered (with the equality of
4555 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4556 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4557 * <p>
4558 * The request may be released normally by calling
4559 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4560 * <p>It is presently unsupported to request a network with either
4561 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4562 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4563 * as these {@code NetworkCapabilities} represent states that a particular
4564 * network may never attain, and whether a network will attain these states
4565 * is unknown prior to bringing up the network so the framework does not
4566 * know how to go about satisfying a request with these capabilities.
4567 *
4568 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4569 * number of outstanding requests to 100 per app (identified by their UID), shared with
4570 * all variants of this method, of {@link #registerNetworkCallback} as well as
4571 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4572 * Requesting a network with this method will count toward this limit. If this limit is
4573 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4574 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4575 * or {@link #releaseNetworkRequest(PendingIntent)}.
4576 *
4577 * <p>This method requires the caller to hold either the
4578 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4579 * or the ability to modify system settings as determined by
4580 * {@link android.provider.Settings.System#canWrite}.</p>
4581 *
4582 * @param request {@link NetworkRequest} describing this request.
4583 * @param operation Action to perform when the network is available (corresponds
4584 * to the {@link NetworkCallback#onAvailable} call. Typically
4585 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4586 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4587 * @throws SecurityException if missing the appropriate permissions.
4588 * @throws RuntimeException if the app already has too many callbacks registered.
4589 */
4590 public void requestNetwork(@NonNull NetworkRequest request,
4591 @NonNull PendingIntent operation) {
4592 printStackTrace();
4593 checkPendingIntentNotNull(operation);
4594 try {
4595 mService.pendingRequestForNetwork(
4596 request.networkCapabilities, operation, mContext.getOpPackageName(),
4597 getAttributionTag());
4598 } catch (RemoteException e) {
4599 throw e.rethrowFromSystemServer();
4600 } catch (ServiceSpecificException e) {
4601 throw convertServiceException(e);
4602 }
4603 }
4604
4605 /**
4606 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4607 * <p>
4608 * This method has the same behavior as
4609 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4610 * releasing network resources and disconnecting.
4611 *
4612 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4613 * PendingIntent passed to
4614 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4615 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4616 */
4617 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4618 printStackTrace();
4619 checkPendingIntentNotNull(operation);
4620 try {
4621 mService.releasePendingNetworkRequest(operation);
4622 } catch (RemoteException e) {
4623 throw e.rethrowFromSystemServer();
4624 }
4625 }
4626
4627 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004628 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004629 }
4630
4631 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004632 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004633 }
4634
4635 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004636 if (timeoutMs <= 0) {
4637 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4638 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004639 }
4640
4641 /**
4642 * Registers to receive notifications about all networks which satisfy the given
4643 * {@link NetworkRequest}. The callbacks will continue to be called until
4644 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4645 * called.
4646 *
4647 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4648 * number of outstanding requests to 100 per app (identified by their UID), shared with
4649 * all variants of this method, of {@link #requestNetwork} as well as
4650 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4651 * Requesting a network with this method will count toward this limit. If this limit is
4652 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4653 * make sure to unregister the callbacks with
4654 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4655 *
4656 * @param request {@link NetworkRequest} describing this request.
4657 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4658 * networks change state.
4659 * The callback is invoked on the default internal Handler.
4660 * @throws RuntimeException if the app already has too many callbacks registered.
4661 */
4662 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4663 public void registerNetworkCallback(@NonNull NetworkRequest request,
4664 @NonNull NetworkCallback networkCallback) {
4665 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4666 }
4667
4668 /**
4669 * Registers to receive notifications about all networks which satisfy the given
4670 * {@link NetworkRequest}. The callbacks will continue to be called until
4671 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4672 * called.
4673 *
4674 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4675 * number of outstanding requests to 100 per app (identified by their UID), shared with
4676 * all variants of this method, of {@link #requestNetwork} as well as
4677 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4678 * Requesting a network with this method will count toward this limit. If this limit is
4679 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4680 * make sure to unregister the callbacks with
4681 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4682 *
4683 *
4684 * @param request {@link NetworkRequest} describing this request.
4685 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4686 * networks change state.
4687 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4688 * @throws RuntimeException if the app already has too many callbacks registered.
4689 */
4690 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4691 public void registerNetworkCallback(@NonNull NetworkRequest request,
4692 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4693 CallbackHandler cbHandler = new CallbackHandler(handler);
4694 NetworkCapabilities nc = request.networkCapabilities;
4695 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4696 }
4697
4698 /**
4699 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4700 * {@link NetworkRequest}.
4701 *
4702 * This function behaves identically to the version that takes a NetworkCallback, but instead
4703 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4704 * the request may outlive the calling application and get called back when a suitable
4705 * network is found.
4706 * <p>
4707 * The operation is an Intent broadcast that goes to a broadcast receiver that
4708 * you registered with {@link Context#registerReceiver} or through the
4709 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4710 * <p>
4711 * The operation Intent is delivered with two extras, a {@link Network} typed
4712 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4713 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4714 * the original requests parameters.
4715 * <p>
4716 * If there is already a request for this Intent registered (with the equality of
4717 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4718 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4719 * <p>
4720 * The request may be released normally by calling
4721 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4722 *
4723 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4724 * number of outstanding requests to 100 per app (identified by their UID), shared with
4725 * all variants of this method, of {@link #requestNetwork} as well as
4726 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4727 * Requesting a network with this method will count toward this limit. If this limit is
4728 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4729 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4730 * or {@link #releaseNetworkRequest(PendingIntent)}.
4731 *
4732 * @param request {@link NetworkRequest} describing this request.
4733 * @param operation Action to perform when the network is available (corresponds
4734 * to the {@link NetworkCallback#onAvailable} call. Typically
4735 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4736 * @throws RuntimeException if the app already has too many callbacks registered.
4737 */
4738 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4739 public void registerNetworkCallback(@NonNull NetworkRequest request,
4740 @NonNull PendingIntent operation) {
4741 printStackTrace();
4742 checkPendingIntentNotNull(operation);
4743 try {
4744 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004745 request.networkCapabilities, operation, mContext.getOpPackageName(),
4746 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004747 } catch (RemoteException e) {
4748 throw e.rethrowFromSystemServer();
4749 } catch (ServiceSpecificException e) {
4750 throw convertServiceException(e);
4751 }
4752 }
4753
4754 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004755 * Registers to receive notifications about changes in the application's default network. This
4756 * may be a physical network or a virtual network, such as a VPN that applies to the
4757 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004758 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4759 *
4760 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4761 * number of outstanding requests to 100 per app (identified by their UID), shared with
4762 * all variants of this method, of {@link #requestNetwork} as well as
4763 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4764 * Requesting a network with this method will count toward this limit. If this limit is
4765 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4766 * make sure to unregister the callbacks with
4767 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4768 *
4769 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004770 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004771 * The callback is invoked on the default internal Handler.
4772 * @throws RuntimeException if the app already has too many callbacks registered.
4773 */
4774 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4775 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4776 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4777 }
4778
4779 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004780 * Registers to receive notifications about changes in the application's default network. This
4781 * may be a physical network or a virtual network, such as a VPN that applies to the
4782 * application. The callbacks will continue to be called until either the application exits or
4783 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4784 *
4785 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4786 * number of outstanding requests to 100 per app (identified by their UID), shared with
4787 * all variants of this method, of {@link #requestNetwork} as well as
4788 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4789 * Requesting a network with this method will count toward this limit. If this limit is
4790 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4791 * make sure to unregister the callbacks with
4792 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4793 *
4794 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4795 * application's default network changes.
4796 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4797 * @throws RuntimeException if the app already has too many callbacks registered.
4798 */
4799 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4800 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4801 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004802 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004803 }
4804
4805 /**
4806 * Registers to receive notifications about changes in the default network for the specified
4807 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4808 * UID. The callbacks will continue to be called until either the application exits or
4809 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4810 *
4811 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4812 * number of outstanding requests to 100 per app (identified by their UID), shared with
4813 * all variants of this method, of {@link #requestNetwork} as well as
4814 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4815 * Requesting a network with this method will count toward this limit. If this limit is
4816 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4817 * make sure to unregister the callbacks with
4818 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4819 *
4820 * @param uid the UID for which to track default network changes.
4821 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4822 * UID's default network changes.
4823 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4824 * @throws RuntimeException if the app already has too many callbacks registered.
4825 * @hide
4826 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004827 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004828 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4829 @RequiresPermission(anyOf = {
4830 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4831 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004832 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004833 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004834 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004835 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004836 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4837 }
4838
4839 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004840 * Registers to receive notifications about changes in the system default network. The callbacks
4841 * will continue to be called until either the application exits or
4842 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4843 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004844 * This method should not be used to determine networking state seen by applications, because in
4845 * many cases, most or even all application traffic may not use the default network directly,
4846 * and traffic from different applications may go on different networks by default. As an
4847 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4848 * and not onto the system default network. Applications or system components desiring to do
4849 * determine network state as seen by applications should use other methods such as
4850 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4851 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004852 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4853 * number of outstanding requests to 100 per app (identified by their UID), shared with
4854 * all variants of this method, of {@link #requestNetwork} as well as
4855 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4856 * Requesting a network with this method will count toward this limit. If this limit is
4857 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4858 * make sure to unregister the callbacks with
4859 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4860 *
4861 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4862 * system default network changes.
4863 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4864 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004865 *
4866 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004867 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004868 @SystemApi(client = MODULE_LIBRARIES)
4869 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4870 @RequiresPermission(anyOf = {
4871 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004872 android.Manifest.permission.NETWORK_SETTINGS,
4873 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004874 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004875 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004876 CallbackHandler cbHandler = new CallbackHandler(handler);
4877 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004878 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004879 }
4880
4881 /**
junyulaibd123062021-03-15 11:48:48 +08004882 * Registers to receive notifications about the best matching network which satisfy the given
4883 * {@link NetworkRequest}. The callbacks will continue to be called until
4884 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4885 * called.
4886 *
4887 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4888 * number of outstanding requests to 100 per app (identified by their UID), shared with
4889 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4890 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4891 * Requesting a network with this method will count toward this limit. If this limit is
4892 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4893 * make sure to unregister the callbacks with
4894 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4895 *
4896 *
4897 * @param request {@link NetworkRequest} describing this request.
4898 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4899 * networks change state.
4900 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4901 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004902 */
junyulai5a5c99b2021-03-05 15:51:17 +08004903 @SuppressLint("ExecutorRegistration")
4904 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4905 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4906 final NetworkCapabilities nc = request.networkCapabilities;
4907 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004908 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004909 }
4910
4911 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004912 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4913 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4914 * network connection for updated bandwidth information. The caller will be notified via
4915 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4916 * method assumes that the caller has previously called
4917 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4918 * changes.
4919 *
4920 * @param network {@link Network} specifying which network you're interested.
4921 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4922 */
4923 public boolean requestBandwidthUpdate(@NonNull Network network) {
4924 try {
4925 return mService.requestBandwidthUpdate(network);
4926 } catch (RemoteException e) {
4927 throw e.rethrowFromSystemServer();
4928 }
4929 }
4930
4931 /**
4932 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4933 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4934 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09004935 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
4936 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004937 *
4938 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4939 * triggering it as soon as this call returns.
4940 *
4941 * @param networkCallback The {@link NetworkCallback} used when making the request.
4942 */
4943 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4944 printStackTrace();
4945 checkCallbackNotNull(networkCallback);
4946 final List<NetworkRequest> reqs = new ArrayList<>();
4947 // Find all requests associated to this callback and stop callback triggers immediately.
4948 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4949 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004950 if (networkCallback.networkRequest == null) {
4951 throw new IllegalArgumentException("NetworkCallback was not registered");
4952 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004953 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4954 Log.d(TAG, "NetworkCallback was already unregistered");
4955 return;
4956 }
4957 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4958 if (e.getValue() == networkCallback) {
4959 reqs.add(e.getKey());
4960 }
4961 }
4962 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4963 for (NetworkRequest r : reqs) {
4964 try {
4965 mService.releaseNetworkRequest(r);
4966 } catch (RemoteException e) {
4967 throw e.rethrowFromSystemServer();
4968 }
4969 // Only remove mapping if rpc was successful.
4970 sCallbacks.remove(r);
4971 }
4972 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4973 }
4974 }
4975
4976 /**
4977 * Unregisters a callback previously registered via
4978 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4979 *
4980 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4981 * PendingIntent passed to
4982 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4983 * Cannot be null.
4984 */
4985 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4986 releaseNetworkRequest(operation);
4987 }
4988
4989 /**
4990 * Informs the system whether it should switch to {@code network} regardless of whether it is
4991 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4992 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4993 * the system default network regardless of any other network that's currently connected. If
4994 * {@code always} is true, then the choice is remembered, so that the next time the user
4995 * connects to this network, the system will switch to it.
4996 *
4997 * @param network The network to accept.
4998 * @param accept Whether to accept the network even if unvalidated.
4999 * @param always Whether to remember this choice in the future.
5000 *
5001 * @hide
5002 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005003 @SystemApi(client = MODULE_LIBRARIES)
5004 @RequiresPermission(anyOf = {
5005 android.Manifest.permission.NETWORK_SETTINGS,
5006 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5007 android.Manifest.permission.NETWORK_STACK,
5008 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5009 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005010 try {
5011 mService.setAcceptUnvalidated(network, accept, always);
5012 } catch (RemoteException e) {
5013 throw e.rethrowFromSystemServer();
5014 }
5015 }
5016
5017 /**
5018 * Informs the system whether it should consider the network as validated even if it only has
5019 * partial connectivity. If {@code accept} is true, then the network will be considered as
5020 * validated even if connectivity is only partial. If {@code always} is true, then the choice
5021 * is remembered, so that the next time the user connects to this network, the system will
5022 * switch to it.
5023 *
5024 * @param network The network to accept.
5025 * @param accept Whether to consider the network as validated even if it has partial
5026 * connectivity.
5027 * @param always Whether to remember this choice in the future.
5028 *
5029 * @hide
5030 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005031 @SystemApi(client = MODULE_LIBRARIES)
5032 @RequiresPermission(anyOf = {
5033 android.Manifest.permission.NETWORK_SETTINGS,
5034 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5035 android.Manifest.permission.NETWORK_STACK,
5036 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5037 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5038 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005039 try {
5040 mService.setAcceptPartialConnectivity(network, accept, always);
5041 } catch (RemoteException e) {
5042 throw e.rethrowFromSystemServer();
5043 }
5044 }
5045
5046 /**
5047 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5048 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5049 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5050 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5051 *
5052 * @param network The network to accept.
5053 *
5054 * @hide
5055 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005056 @SystemApi(client = MODULE_LIBRARIES)
5057 @RequiresPermission(anyOf = {
5058 android.Manifest.permission.NETWORK_SETTINGS,
5059 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5060 android.Manifest.permission.NETWORK_STACK,
5061 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5062 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005063 try {
5064 mService.setAvoidUnvalidated(network);
5065 } catch (RemoteException e) {
5066 throw e.rethrowFromSystemServer();
5067 }
5068 }
5069
5070 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005071 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005072 *
5073 * @param timeMs The expired current time. The value should be set within a limited time from
5074 * now.
5075 *
5076 * @hide
5077 */
5078 public void setTestAllowBadWifiUntil(long timeMs) {
5079 try {
5080 mService.setTestAllowBadWifiUntil(timeMs);
5081 } catch (RemoteException e) {
5082 throw e.rethrowFromSystemServer();
5083 }
5084 }
5085
5086 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005087 * Requests that the system open the captive portal app on the specified network.
5088 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005089 * <p>This is to be used on networks where a captive portal was detected, as per
5090 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5091 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005092 * @param network The network to log into.
5093 *
5094 * @hide
5095 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005096 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5097 @RequiresPermission(anyOf = {
5098 android.Manifest.permission.NETWORK_SETTINGS,
5099 android.Manifest.permission.NETWORK_STACK,
5100 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5101 })
5102 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005103 try {
5104 mService.startCaptivePortalApp(network);
5105 } catch (RemoteException e) {
5106 throw e.rethrowFromSystemServer();
5107 }
5108 }
5109
5110 /**
5111 * Requests that the system open the captive portal app with the specified extras.
5112 *
5113 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5114 * corresponding permission.
5115 * @param network Network on which the captive portal was detected.
5116 * @param appExtras Extras to include in the app start intent.
5117 * @hide
5118 */
5119 @SystemApi
5120 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5121 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5122 try {
5123 mService.startCaptivePortalAppInternal(network, appExtras);
5124 } catch (RemoteException e) {
5125 throw e.rethrowFromSystemServer();
5126 }
5127 }
5128
5129 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005130 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005131 * @hide
5132 */
5133 @SystemApi
5134 @RequiresPermission(anyOf = {
5135 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5136 android.Manifest.permission.NETWORK_STACK})
5137 public boolean shouldAvoidBadWifi() {
5138 try {
5139 return mService.shouldAvoidBadWifi();
5140 } catch (RemoteException e) {
5141 throw e.rethrowFromSystemServer();
5142 }
5143 }
5144
5145 /**
5146 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5147 * time-sensitive user-facing operations when the system default network is temporarily
5148 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5149 * this method), and the operation should be infrequent to ensure that data usage is limited.
5150 *
5151 * An example of such an operation might be a time-sensitive foreground activity, such as a
5152 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5153 */
5154 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5155
5156 /**
5157 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5158 * a backup channel for traffic that is primarily going over another network.
5159 *
5160 * An example might be maintaining backup connections to peers or servers for the purpose of
5161 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5162 * on backup paths should be negligible compared to the traffic on the main path.
5163 */
5164 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5165
5166 /**
5167 * It is acceptable to use metered data to improve network latency and performance.
5168 */
5169 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5170
5171 /**
5172 * Return value to use for unmetered networks. On such networks we currently set all the flags
5173 * to true.
5174 * @hide
5175 */
5176 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5177 MULTIPATH_PREFERENCE_HANDOVER |
5178 MULTIPATH_PREFERENCE_RELIABILITY |
5179 MULTIPATH_PREFERENCE_PERFORMANCE;
5180
Aaron Huangcff22942021-05-27 16:31:26 +08005181 /** @hide */
5182 @Retention(RetentionPolicy.SOURCE)
5183 @IntDef(flag = true, value = {
5184 MULTIPATH_PREFERENCE_HANDOVER,
5185 MULTIPATH_PREFERENCE_RELIABILITY,
5186 MULTIPATH_PREFERENCE_PERFORMANCE,
5187 })
5188 public @interface MultipathPreference {
5189 }
5190
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005191 /**
5192 * Provides a hint to the calling application on whether it is desirable to use the
5193 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5194 * for multipath data transfer on this network when it is not the system default network.
5195 * Applications desiring to use multipath network protocols should call this method before
5196 * each such operation.
5197 *
5198 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005199 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005200 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005201 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005202 */
5203 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5204 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5205 try {
5206 return mService.getMultipathPreference(network);
5207 } catch (RemoteException e) {
5208 throw e.rethrowFromSystemServer();
5209 }
5210 }
5211
5212 /**
5213 * Resets all connectivity manager settings back to factory defaults.
5214 * @hide
5215 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005216 @SystemApi(client = MODULE_LIBRARIES)
5217 @RequiresPermission(anyOf = {
5218 android.Manifest.permission.NETWORK_SETTINGS,
5219 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005220 public void factoryReset() {
5221 try {
5222 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005223 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005224 } catch (RemoteException e) {
5225 throw e.rethrowFromSystemServer();
5226 }
5227 }
5228
5229 /**
5230 * Binds the current process to {@code network}. All Sockets created in the future
5231 * (and not explicitly bound via a bound SocketFactory from
5232 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5233 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5234 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5235 * work and all host name resolutions will fail. This is by design so an application doesn't
5236 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5237 * To clear binding pass {@code null} for {@code network}. Using individually bound
5238 * Sockets created by Network.getSocketFactory().createSocket() and
5239 * performing network-specific host name resolutions via
5240 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5241 * {@code bindProcessToNetwork}.
5242 *
5243 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5244 * the current binding.
5245 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5246 */
5247 public boolean bindProcessToNetwork(@Nullable Network network) {
5248 // Forcing callers to call through non-static function ensures ConnectivityManager
5249 // instantiated.
5250 return setProcessDefaultNetwork(network);
5251 }
5252
5253 /**
5254 * Binds the current process to {@code network}. All Sockets created in the future
5255 * (and not explicitly bound via a bound SocketFactory from
5256 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5257 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5258 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5259 * work and all host name resolutions will fail. This is by design so an application doesn't
5260 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5261 * To clear binding pass {@code null} for {@code network}. Using individually bound
5262 * Sockets created by Network.getSocketFactory().createSocket() and
5263 * performing network-specific host name resolutions via
5264 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5265 * {@code setProcessDefaultNetwork}.
5266 *
5267 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5268 * the current binding.
5269 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5270 * @deprecated This function can throw {@link IllegalStateException}. Use
5271 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5272 * is a direct replacement.
5273 */
5274 @Deprecated
5275 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5276 int netId = (network == null) ? NETID_UNSET : network.netId;
5277 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5278
5279 if (netId != NETID_UNSET) {
5280 netId = network.getNetIdForResolv();
5281 }
5282
5283 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5284 return false;
5285 }
5286
5287 if (!isSameNetId) {
5288 // Set HTTP proxy system properties to match network.
5289 // TODO: Deprecate this static method and replace it with a non-static version.
5290 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005291 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005292 } catch (SecurityException e) {
5293 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5294 Log.e(TAG, "Can't set proxy properties", e);
5295 }
5296 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005297 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005298 // Must flush socket pool as idle sockets will be bound to previous network and may
5299 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005300 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005301 }
5302
5303 return true;
5304 }
5305
5306 /**
5307 * Returns the {@link Network} currently bound to this process via
5308 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5309 *
5310 * @return {@code Network} to which this process is bound, or {@code null}.
5311 */
5312 @Nullable
5313 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005314 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005315 // instantiated.
5316 return getProcessDefaultNetwork();
5317 }
5318
5319 /**
5320 * Returns the {@link Network} currently bound to this process via
5321 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5322 *
5323 * @return {@code Network} to which this process is bound, or {@code null}.
5324 * @deprecated Using this function can lead to other functions throwing
5325 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5326 * {@code getBoundNetworkForProcess} is a direct replacement.
5327 */
5328 @Deprecated
5329 @Nullable
5330 public static Network getProcessDefaultNetwork() {
5331 int netId = NetworkUtils.getBoundNetworkForProcess();
5332 if (netId == NETID_UNSET) return null;
5333 return new Network(netId);
5334 }
5335
5336 private void unsupportedStartingFrom(int version) {
5337 if (Process.myUid() == Process.SYSTEM_UID) {
5338 // The getApplicationInfo() call we make below is not supported in system context. Let
5339 // the call through here, and rely on the fact that ConnectivityService will refuse to
5340 // allow the system to use these APIs anyway.
5341 return;
5342 }
5343
5344 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5345 throw new UnsupportedOperationException(
5346 "This method is not supported in target SDK version " + version + " and above");
5347 }
5348 }
5349
5350 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5351 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5352 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5353 // remove these exemptions. Note that this check is not secure, and apps can still access these
5354 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5355 // so is unsupported and may break in the future. http://b/22728205
5356 private void checkLegacyRoutingApiAccess() {
5357 unsupportedStartingFrom(VERSION_CODES.M);
5358 }
5359
5360 /**
5361 * Binds host resolutions performed by this process to {@code network}.
5362 * {@link #bindProcessToNetwork} takes precedence over this setting.
5363 *
5364 * @param network The {@link Network} to bind host resolutions from the current process to, or
5365 * {@code null} to clear the current binding.
5366 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5367 * @hide
5368 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5369 */
5370 @Deprecated
5371 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5372 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5373 return NetworkUtils.bindProcessToNetworkForHostResolution(
5374 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5375 }
5376
5377 /**
5378 * Device is not restricting metered network activity while application is running on
5379 * background.
5380 */
5381 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5382
5383 /**
5384 * Device is restricting metered network activity while application is running on background,
5385 * but application is allowed to bypass it.
5386 * <p>
5387 * In this state, application should take action to mitigate metered network access.
5388 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5389 */
5390 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5391
5392 /**
5393 * Device is restricting metered network activity while application is running on background.
5394 * <p>
5395 * In this state, application should not try to use the network while running on background,
5396 * because it would be denied.
5397 */
5398 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5399
5400 /**
5401 * A change in the background metered network activity restriction has occurred.
5402 * <p>
5403 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5404 * applies to them.
5405 * <p>
5406 * This is only sent to registered receivers, not manifest receivers.
5407 */
5408 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5409 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5410 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5411
Aaron Huangcff22942021-05-27 16:31:26 +08005412 /** @hide */
5413 @Retention(RetentionPolicy.SOURCE)
5414 @IntDef(flag = false, value = {
5415 RESTRICT_BACKGROUND_STATUS_DISABLED,
5416 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5417 RESTRICT_BACKGROUND_STATUS_ENABLED,
5418 })
5419 public @interface RestrictBackgroundStatus {
5420 }
5421
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005422 /**
5423 * Determines if the calling application is subject to metered network restrictions while
5424 * running on background.
5425 *
5426 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5427 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5428 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5429 */
5430 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5431 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005432 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005433 } catch (RemoteException e) {
5434 throw e.rethrowFromSystemServer();
5435 }
5436 }
5437
5438 /**
5439 * The network watchlist is a list of domains and IP addresses that are associated with
5440 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5441 * currently used by the system for validation purposes.
5442 *
5443 * @return Hash of network watchlist config file. Null if config does not exist.
5444 */
5445 @Nullable
5446 public byte[] getNetworkWatchlistConfigHash() {
5447 try {
5448 return mService.getNetworkWatchlistConfigHash();
5449 } catch (RemoteException e) {
5450 Log.e(TAG, "Unable to get watchlist config hash");
5451 throw e.rethrowFromSystemServer();
5452 }
5453 }
5454
5455 /**
5456 * Returns the {@code uid} of the owner of a network connection.
5457 *
5458 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5459 * IPPROTO_UDP} currently supported.
5460 * @param local The local {@link InetSocketAddress} of a connection.
5461 * @param remote The remote {@link InetSocketAddress} of a connection.
5462 * @return {@code uid} if the connection is found and the app has permission to observe it
5463 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5464 * android.os.Process#INVALID_UID} if the connection is not found.
5465 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5466 * user.
5467 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5468 */
5469 public int getConnectionOwnerUid(
5470 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5471 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5472 try {
5473 return mService.getConnectionOwnerUid(connectionInfo);
5474 } catch (RemoteException e) {
5475 throw e.rethrowFromSystemServer();
5476 }
5477 }
5478
5479 private void printStackTrace() {
5480 if (DEBUG) {
5481 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5482 final StringBuffer sb = new StringBuffer();
5483 for (int i = 3; i < callStack.length; i++) {
5484 final String stackTrace = callStack[i].toString();
5485 if (stackTrace == null || stackTrace.contains("android.os")) {
5486 break;
5487 }
5488 sb.append(" [").append(stackTrace).append("]");
5489 }
5490 Log.d(TAG, "StackLog:" + sb.toString());
5491 }
5492 }
5493
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005494 /** @hide */
5495 public TestNetworkManager startOrGetTestNetworkManager() {
5496 final IBinder tnBinder;
5497 try {
5498 tnBinder = mService.startOrGetTestNetworkService();
5499 } catch (RemoteException e) {
5500 throw e.rethrowFromSystemServer();
5501 }
5502
5503 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5504 }
5505
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005506 /** @hide */
5507 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5508 return new ConnectivityDiagnosticsManager(mContext, mService);
5509 }
5510
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005511 /**
5512 * Simulates a Data Stall for the specified Network.
5513 *
5514 * <p>This method should only be used for tests.
5515 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005516 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5517 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005518 *
5519 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005520 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5521 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5522 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005523 * @param network The Network for which a Data Stall is being simluated.
5524 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5525 * @throws SecurityException if the caller is not the owner of the given network.
5526 * @hide
5527 */
5528 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5529 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5530 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005531 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005532 @NonNull Network network, @NonNull PersistableBundle extras) {
5533 try {
5534 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5535 } catch (RemoteException e) {
5536 e.rethrowFromSystemServer();
5537 }
5538 }
5539
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005540 @NonNull
5541 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5542
5543 /**
5544 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5545 * receive available QoS events related to the {@link Network} and local ip + port
5546 * specified within socketInfo.
5547 * <p/>
5548 * The same {@link QosCallback} must be unregistered before being registered a second time,
5549 * otherwise {@link QosCallbackRegistrationException} is thrown.
5550 * <p/>
5551 * This API does not, in itself, require any permission if called with a network that is not
5552 * restricted. However, the underlying implementation currently only supports the IMS network,
5553 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5554 * useful, because they'd never be called back on networks that they would have access to.
5555 *
5556 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5557 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5558 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5559 * @throws RuntimeException if the app already has too many callbacks registered.
5560 *
5561 * Exceptions after the time of registration is passed through
5562 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5563 *
5564 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005565 * @param executor The executor on which the callback will be invoked. The provided
5566 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005567 * callbacks cannot be guaranteed.onQosCallbackRegistered
5568 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005569 *
5570 * @hide
5571 */
5572 @SystemApi
5573 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005574 @CallbackExecutor @NonNull final Executor executor,
5575 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005576 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005577 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005578 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005579
5580 try {
5581 synchronized (mQosCallbackConnections) {
5582 if (getQosCallbackConnection(callback) == null) {
5583 final QosCallbackConnection connection =
5584 new QosCallbackConnection(this, callback, executor);
5585 mQosCallbackConnections.add(connection);
5586 mService.registerQosSocketCallback(socketInfo, connection);
5587 } else {
5588 Log.e(TAG, "registerQosCallback: Callback already registered");
5589 throw new QosCallbackRegistrationException();
5590 }
5591 }
5592 } catch (final RemoteException e) {
5593 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5594
5595 // The same unregister method method is called for consistency even though nothing
5596 // will be sent to the ConnectivityService since the callback was never successfully
5597 // registered.
5598 unregisterQosCallback(callback);
5599 e.rethrowFromSystemServer();
5600 } catch (final ServiceSpecificException e) {
5601 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5602 unregisterQosCallback(callback);
5603 throw convertServiceException(e);
5604 }
5605 }
5606
5607 /**
5608 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5609 * events once unregistered and can be registered a second time.
5610 * <p/>
5611 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5612 *
5613 * @param callback the callback being unregistered
5614 *
5615 * @hide
5616 */
5617 @SystemApi
5618 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5619 Objects.requireNonNull(callback, "The callback must be non-null");
5620 try {
5621 synchronized (mQosCallbackConnections) {
5622 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5623 if (connection != null) {
5624 connection.stopReceivingMessages();
5625 mService.unregisterQosCallback(connection);
5626 mQosCallbackConnections.remove(connection);
5627 } else {
5628 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5629 }
5630 }
5631 } catch (final RemoteException e) {
5632 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5633 e.rethrowFromSystemServer();
5634 }
5635 }
5636
5637 /**
5638 * Gets the connection related to the callback.
5639 *
5640 * @param callback the callback to look up
5641 * @return the related connection
5642 */
5643 @Nullable
5644 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5645 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5646 // Checking by reference here is intentional
5647 if (connection.getCallback() == callback) {
5648 return connection;
5649 }
5650 }
5651 return null;
5652 }
5653
5654 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005655 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005656 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5657 * be used to request that the system provide a network without causing the network to be
5658 * in the foreground.
5659 *
5660 * <p>This method will attempt to find the best network that matches the passed
5661 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5662 * criteria. The platform will evaluate which network is the best at its own discretion.
5663 * Throughput, latency, cost per byte, policy, user preference and other considerations
5664 * may be factored in the decision of what is considered the best network.
5665 *
5666 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5667 * matching this request, while always attempting to match the request to a better network if
5668 * possible. If a better match is found, the platform will switch this request to the now-best
5669 * network and inform the app of the newly best network by invoking
5670 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5671 * will not try to maintain any other network than the best one currently matching the request:
5672 * a network not matching any network request may be disconnected at any time.
5673 *
5674 * <p>For example, an application could use this method to obtain a connected cellular network
5675 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5676 * radio to consume additional power. Or, an application could inform the system that it wants
5677 * a network supporting sending MMSes and have the system let it know about the currently best
5678 * MMS-supporting network through the provided {@link NetworkCallback}.
5679 *
5680 * <p>The status of the request can be followed by listening to the various callbacks described
5681 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5682 * used to direct traffic to the network (although accessing some networks may be subject to
5683 * holding specific permissions). Callers will learn about the specific characteristics of the
5684 * network through
5685 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5686 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5687 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5688 * matching the request at any given time; therefore when a better network matching the request
5689 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5690 * with the new network after which no further updates are given about the previously-best
5691 * network, unless it becomes the best again at some later time. All callbacks are invoked
5692 * in order on the same thread, which by default is a thread created by the framework running
5693 * in the app.
5694 *
5695 * <p>This{@link NetworkRequest} will live until released via
5696 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5697 * which point the system may let go of the network at any time.
5698 *
5699 * <p>It is presently unsupported to request a network with mutable
5700 * {@link NetworkCapabilities} such as
5701 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5702 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5703 * as these {@code NetworkCapabilities} represent states that a particular
5704 * network may never attain, and whether a network will attain these states
5705 * is unknown prior to bringing up the network so the framework does not
5706 * know how to go about satisfying a request with these capabilities.
5707 *
5708 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5709 * number of outstanding requests to 100 per app (identified by their UID), shared with
5710 * all variants of this method, of {@link #registerNetworkCallback} as well as
5711 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5712 * Requesting a network with this method will count toward this limit. If this limit is
5713 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5714 * make sure to unregister the callbacks with
5715 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5716 *
5717 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005718 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5719 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005720 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5721 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005722 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5723 * @throws SecurityException if missing the appropriate permissions.
5724 * @throws RuntimeException if the app already has too many callbacks registered.
5725 *
5726 * @hide
5727 */
5728 @SystemApi(client = MODULE_LIBRARIES)
5729 @SuppressLint("ExecutorRegistration")
5730 @RequiresPermission(anyOf = {
5731 android.Manifest.permission.NETWORK_SETTINGS,
5732 android.Manifest.permission.NETWORK_STACK,
5733 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5734 })
5735 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005736 @NonNull NetworkCallback networkCallback,
5737 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005738 final NetworkCapabilities nc = request.networkCapabilities;
5739 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005740 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005741 }
James Mattis12aeab82021-01-10 14:24:24 -08005742
5743 /**
James Mattis12aeab82021-01-10 14:24:24 -08005744 * Used by automotive devices to set the network preferences used to direct traffic at an
5745 * application level as per the given OemNetworkPreferences. An example use-case would be an
5746 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5747 * vehicle via a particular network.
5748 *
5749 * Calling this will overwrite the existing preference.
5750 *
5751 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5752 * @param executor the executor on which listener will be invoked.
5753 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5754 * communicate completion of setOemNetworkPreference(). This will only be
5755 * called once upon successful completion of setOemNetworkPreference().
5756 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5757 * @throws SecurityException if missing the appropriate permissions.
5758 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005759 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005760 */
James Mattis6e2d7022021-01-26 16:23:52 -08005761 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005762 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005763 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005764 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005765 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005766 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5767 if (null != listener) {
5768 Objects.requireNonNull(executor, "Executor must be non-null");
5769 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005770 final IOnCompleteListener listenerInternal = listener == null ? null :
5771 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005772 @Override
5773 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005774 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005775 }
5776 };
5777
5778 try {
5779 mService.setOemNetworkPreference(preference, listenerInternal);
5780 } catch (RemoteException e) {
5781 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5782 throw e.rethrowFromSystemServer();
5783 }
5784 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005785
Chalard Jeanad565e22021-02-25 17:23:40 +09005786 /**
5787 * Request that a user profile is put by default on a network matching a given preference.
5788 *
5789 * See the documentation for the individual preferences for a description of the supported
5790 * behaviors.
5791 *
5792 * @param profile the profile concerned.
5793 * @param preference the preference for this profile.
5794 * @param executor an executor to execute the listener on. Optional if listener is null.
5795 * @param listener an optional listener to listen for completion of the operation.
5796 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5797 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005798 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5799 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005800 * @hide
5801 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005802 // This function is for establishing per-profile default networking and can only be called by
5803 // the device policy manager, running as the system server. It would make no sense to call it
5804 // on a context for a user because it does not establish a setting on behalf of a user, rather
5805 // it establishes a setting for a user on behalf of the DPM.
5806 @SuppressLint({"UserHandle"})
5807 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005808 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005809 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005810 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005811 @ProfileNetworkPreferencePolicy final int preference,
5812 @Nullable @CallbackExecutor final Executor executor,
5813 @Nullable final Runnable listener) {
5814
5815 ProfileNetworkPreference.Builder preferenceBuilder =
5816 new ProfileNetworkPreference.Builder();
5817 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005818 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5819 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5820 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005821 setProfileNetworkPreferences(profile,
5822 List.of(preferenceBuilder.build()), executor, listener);
5823 }
5824
5825 /**
5826 * Set a list of default network selection policies for a user profile.
5827 *
5828 * Calling this API with a user handle defines the entire policy for that user handle.
5829 * It will overwrite any setting previously set for the same user profile,
5830 * and not affect previously set settings for other handles.
5831 *
5832 * Call this API with an empty list to remove settings for this user profile.
5833 *
5834 * See {@link ProfileNetworkPreference} for more details on each preference
5835 * parameter.
5836 *
5837 * @param profile the user profile for which the preference is being set.
5838 * @param profileNetworkPreferences the list of profile network preferences for the
5839 * provided profile.
5840 * @param executor an executor to execute the listener on. Optional if listener is null.
5841 * @param listener an optional listener to listen for completion of the operation.
5842 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5843 * @throws SecurityException if missing the appropriate permissions.
5844 * @hide
5845 */
5846 @SystemApi(client = MODULE_LIBRARIES)
5847 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5848 public void setProfileNetworkPreferences(
5849 @NonNull final UserHandle profile,
5850 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005851 @Nullable @CallbackExecutor final Executor executor,
5852 @Nullable final Runnable listener) {
5853 if (null != listener) {
5854 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5855 }
5856 final IOnCompleteListener proxy;
5857 if (null == listener) {
5858 proxy = null;
5859 } else {
5860 proxy = new IOnCompleteListener.Stub() {
5861 @Override
5862 public void onComplete() {
5863 executor.execute(listener::run);
5864 }
5865 };
5866 }
5867 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005868 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005869 } catch (RemoteException e) {
5870 throw e.rethrowFromSystemServer();
5871 }
5872 }
5873
lucaslin5cdbcfb2021-03-12 00:46:33 +08005874 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005875 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005876 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005877 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005878
5879 /**
5880 * Get the network ID range reserved for IPSec tunnel interfaces.
5881 *
5882 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5883 * @hide
5884 */
5885 @SystemApi(client = MODULE_LIBRARIES)
5886 @NonNull
5887 public static Range<Integer> getIpSecNetIdRange() {
5888 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5889 }
markchien738ad912021-12-09 18:15:45 +08005890
5891 /**
markchiene46042b2022-03-02 18:07:35 +08005892 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5893 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005894 *
5895 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005896 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005897 * @hide
5898 */
5899 @SystemApi(client = MODULE_LIBRARIES)
5900 @RequiresPermission(anyOf = {
5901 android.Manifest.permission.NETWORK_SETTINGS,
5902 android.Manifest.permission.NETWORK_STACK,
5903 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5904 })
markchiene46042b2022-03-02 18:07:35 +08005905 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005906 try {
markchiene46042b2022-03-02 18:07:35 +08005907 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08005908 } catch (RemoteException e) {
5909 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005910 }
5911 }
5912
5913 /**
markchiene46042b2022-03-02 18:07:35 +08005914 * Removes the specified UID from the list of UIDs that are allowed to use background data on
5915 * metered networks when background data is restricted. The deny list takes precedence over
5916 * the allow list.
5917 *
5918 * @param uid uid of target app
5919 * @throws IllegalStateException if updating allow list failed.
5920 * @hide
5921 */
5922 @SystemApi(client = MODULE_LIBRARIES)
5923 @RequiresPermission(anyOf = {
5924 android.Manifest.permission.NETWORK_SETTINGS,
5925 android.Manifest.permission.NETWORK_STACK,
5926 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5927 })
5928 public void removeUidFromMeteredNetworkAllowList(final int uid) {
5929 try {
5930 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
5931 } catch (RemoteException e) {
5932 throw e.rethrowFromSystemServer();
5933 }
5934 }
5935
5936 /**
5937 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
5938 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08005939 *
5940 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005941 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08005942 * @hide
5943 */
5944 @SystemApi(client = MODULE_LIBRARIES)
5945 @RequiresPermission(anyOf = {
5946 android.Manifest.permission.NETWORK_SETTINGS,
5947 android.Manifest.permission.NETWORK_STACK,
5948 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5949 })
markchiene46042b2022-03-02 18:07:35 +08005950 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005951 try {
markchiene46042b2022-03-02 18:07:35 +08005952 mService.updateMeteredNetworkDenyList(uid, true /* add */);
5953 } catch (RemoteException e) {
5954 throw e.rethrowFromSystemServer();
5955 }
5956 }
5957
5958 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005959 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08005960 * networks if background data is not restricted. The deny list takes precedence over the
5961 * allow list.
5962 *
5963 * @param uid uid of target app
5964 * @throws IllegalStateException if updating deny list failed.
5965 * @hide
5966 */
5967 @SystemApi(client = MODULE_LIBRARIES)
5968 @RequiresPermission(anyOf = {
5969 android.Manifest.permission.NETWORK_SETTINGS,
5970 android.Manifest.permission.NETWORK_STACK,
5971 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5972 })
5973 public void removeUidFromMeteredNetworkDenyList(final int uid) {
5974 try {
5975 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08005976 } catch (RemoteException e) {
5977 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08005978 }
5979 }
5980
5981 /**
5982 * Sets a firewall rule for the specified UID on the specified chain.
5983 *
5984 * @param chain target chain.
5985 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08005986 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08005987 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08005988 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08005989 * @hide
5990 */
5991 @SystemApi(client = MODULE_LIBRARIES)
5992 @RequiresPermission(anyOf = {
5993 android.Manifest.permission.NETWORK_SETTINGS,
5994 android.Manifest.permission.NETWORK_STACK,
5995 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5996 })
markchien3c04e662022-03-22 16:29:56 +08005997 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
5998 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08005999 try {
markchien3c04e662022-03-22 16:29:56 +08006000 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08006001 } catch (RemoteException e) {
6002 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006003 }
6004 }
markchien98a6f952022-01-13 23:43:53 +08006005
6006 /**
6007 * Enables or disables the specified firewall chain.
6008 *
6009 * @param chain target chain.
6010 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00006011 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08006012 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08006013 * @hide
6014 */
6015 @SystemApi(client = MODULE_LIBRARIES)
6016 @RequiresPermission(anyOf = {
6017 android.Manifest.permission.NETWORK_SETTINGS,
6018 android.Manifest.permission.NETWORK_STACK,
6019 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6020 })
6021 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
6022 try {
6023 mService.setFirewallChainEnabled(chain, enable);
6024 } catch (RemoteException e) {
6025 throw e.rethrowFromSystemServer();
6026 }
6027 }
markchien00a0bed2022-01-13 23:46:13 +08006028
6029 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00006030 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006031 *
6032 * @param chain target chain.
6033 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6034 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006035 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6036 * cause of the failure.
6037 * @hide
6038 */
6039 @RequiresPermission(anyOf = {
6040 android.Manifest.permission.NETWORK_SETTINGS,
6041 android.Manifest.permission.NETWORK_STACK,
6042 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6043 })
6044 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6045 try {
6046 return mService.getFirewallChainEnabled(chain);
6047 } catch (RemoteException e) {
6048 throw e.rethrowFromSystemServer();
6049 }
6050 }
6051
6052 /**
markchien00a0bed2022-01-13 23:46:13 +08006053 * Replaces the contents of the specified UID-based firewall chain.
6054 *
6055 * @param chain target chain to replace.
6056 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006057 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006058 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6059 * @hide
6060 */
6061 @SystemApi(client = MODULE_LIBRARIES)
6062 @RequiresPermission(anyOf = {
6063 android.Manifest.permission.NETWORK_SETTINGS,
6064 android.Manifest.permission.NETWORK_STACK,
6065 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6066 })
6067 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6068 Objects.requireNonNull(uids);
6069 try {
6070 mService.replaceFirewallChain(chain, uids);
6071 } catch (RemoteException e) {
6072 throw e.rethrowFromSystemServer();
6073 }
6074 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006075
6076 /** @hide */
6077 public IBinder getCompanionDeviceManagerProxyService() {
6078 try {
6079 return mService.getCompanionDeviceManagerProxyService();
6080 } catch (RemoteException e) {
6081 throw e.rethrowFromSystemServer();
6082 }
6083 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006084}