blob: 1b4b42fbe36d8e60c232a7571e1e4c80f4dba3bd [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 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001235 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001236 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001237 * Specify that the traffic for this user should by follow the default rules.
1238 * @hide
1239 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001240 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001241 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1242
1243 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001244 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001245 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001246 * Specify that the traffic for this user should by default go on a network with
1247 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1248 * if no such network is available.
1249 * @hide
1250 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001251 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001252 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1253
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001254 /**
1255 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001256 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001257 * Specify that the traffic for this user should by default go on a network with
1258 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
1259 * should not go on the system default network
1260 * @hide
1261 */
1262 @SystemApi(client = MODULE_LIBRARIES)
1263 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1264
Chalard Jeanad565e22021-02-25 17:23:40 +09001265 /** @hide */
1266 @Retention(RetentionPolicy.SOURCE)
1267 @IntDef(value = {
1268 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001269 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1270 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001271 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001272 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001273 }
1274
1275 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001276 * Specifies the preferred network type. When the device has more
1277 * than one type available the preferred network type will be used.
1278 *
1279 * @param preference the network type to prefer over all others. It is
1280 * unspecified what happens to the old preferred network in the
1281 * overall ordering.
1282 * @deprecated Functionality has been removed as it no longer makes sense,
1283 * with many more than two networks - we'd need an array to express
1284 * preference. Instead we use dynamic network properties of
1285 * the networks to describe their precedence.
1286 */
1287 @Deprecated
1288 public void setNetworkPreference(int preference) {
1289 }
1290
1291 /**
1292 * Retrieves the current preferred network type.
1293 *
1294 * @return an integer representing the preferred network type
1295 *
1296 * @deprecated Functionality has been removed as it no longer makes sense,
1297 * with many more than two networks - we'd need an array to express
1298 * preference. Instead we use dynamic network properties of
1299 * the networks to describe their precedence.
1300 */
1301 @Deprecated
1302 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1303 public int getNetworkPreference() {
1304 return TYPE_NONE;
1305 }
1306
1307 /**
1308 * Returns details about the currently active default data network. When
1309 * connected, this network is the default route for outgoing connections.
1310 * You should always check {@link NetworkInfo#isConnected()} before initiating
1311 * network traffic. This may return {@code null} when there is no default
1312 * network.
1313 * Note that if the default network is a VPN, this method will return the
1314 * NetworkInfo for one of its underlying networks instead, or null if the
1315 * VPN agent did not specify any. Apps interested in learning about VPNs
1316 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1317 *
1318 * @return a {@link NetworkInfo} object for the current default network
1319 * or {@code null} if no default network is currently active
1320 * @deprecated See {@link NetworkInfo}.
1321 */
1322 @Deprecated
1323 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1324 @Nullable
1325 public NetworkInfo getActiveNetworkInfo() {
1326 try {
1327 return mService.getActiveNetworkInfo();
1328 } catch (RemoteException e) {
1329 throw e.rethrowFromSystemServer();
1330 }
1331 }
1332
1333 /**
1334 * Returns a {@link Network} object corresponding to the currently active
1335 * default data network. In the event that the current active default data
1336 * network disconnects, the returned {@code Network} object will no longer
1337 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001338 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001339 *
1340 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001341 * {@code null} if no default network is currently active or if
1342 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001343 */
1344 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1345 @Nullable
1346 public Network getActiveNetwork() {
1347 try {
1348 return mService.getActiveNetwork();
1349 } catch (RemoteException e) {
1350 throw e.rethrowFromSystemServer();
1351 }
1352 }
1353
1354 /**
1355 * Returns a {@link Network} object corresponding to the currently active
1356 * default data network for a specific UID. In the event that the default data
1357 * network disconnects, the returned {@code Network} object will no longer
1358 * be usable. This will return {@code null} when there is no default
1359 * network for the UID.
1360 *
1361 * @return a {@link Network} object for the current default network for the
1362 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001363 *
1364 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001365 */
1366 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1367 @Nullable
1368 public Network getActiveNetworkForUid(int uid) {
1369 return getActiveNetworkForUid(uid, false);
1370 }
1371
1372 /** {@hide} */
1373 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1374 try {
1375 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1376 } catch (RemoteException e) {
1377 throw e.rethrowFromSystemServer();
1378 }
1379 }
1380
1381 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001382 * Adds or removes a requirement for given UID ranges to use the VPN.
1383 *
1384 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1385 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1386 * otherwise have permission to bypass the VPN (e.g., because they have the
1387 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1388 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1389 * set to {@code false}, a previously-added restriction is removed.
1390 * <p>
1391 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1392 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1393 * remove a previously-added range, the exact range must be removed as is.
1394 * <p>
1395 * The changes are applied asynchronously and may not have been applied by the time the method
1396 * returns. Apps will be notified about any changes that apply to them via
1397 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1398 * effect.
1399 * <p>
1400 * This method should be called only by the VPN code.
1401 *
1402 * @param ranges the UID ranges to restrict
1403 * @param requireVpn whether the specified UID ranges must use a VPN
1404 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001405 * @hide
1406 */
1407 @RequiresPermission(anyOf = {
1408 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001409 android.Manifest.permission.NETWORK_STACK,
1410 android.Manifest.permission.NETWORK_SETTINGS})
1411 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001412 public void setRequireVpnForUids(boolean requireVpn,
1413 @NonNull Collection<Range<Integer>> ranges) {
1414 Objects.requireNonNull(ranges);
1415 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1416 // This method is not necessarily expected to be used outside the system server, so
1417 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1418 // stack process, or by tests.
1419 UidRange[] rangesArray = new UidRange[ranges.size()];
1420 int index = 0;
1421 for (Range<Integer> range : ranges) {
1422 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1423 }
1424 try {
1425 mService.setRequireVpnForUids(requireVpn, rangesArray);
1426 } catch (RemoteException e) {
1427 throw e.rethrowFromSystemServer();
1428 }
1429 }
1430
1431 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001432 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1433 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1434 * but is still supported for backwards compatibility.
1435 * <p>
1436 * This type of VPN is assumed always to use the system default network, and must always declare
1437 * exactly one underlying network, which is the network that was the default when the VPN
1438 * connected.
1439 * <p>
1440 * Calling this method with {@code true} enables legacy behaviour, specifically:
1441 * <ul>
1442 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1443 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1444 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1445 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1446 * underlying the VPN.</li>
1447 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1448 * similarly replaced by the VPN network state.</li>
1449 * <li>Information on current network interfaces passed to NetworkStatsService will not
1450 * include any VPN interfaces.</li>
1451 * </ul>
1452 *
1453 * @param enabled whether legacy lockdown VPN is enabled or disabled
1454 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001455 * @hide
1456 */
1457 @RequiresPermission(anyOf = {
1458 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001459 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001460 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001461 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001462 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1463 try {
1464 mService.setLegacyLockdownVpnEnabled(enabled);
1465 } catch (RemoteException e) {
1466 throw e.rethrowFromSystemServer();
1467 }
1468 }
1469
1470 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001471 * Returns details about the currently active default data network for a given uid.
1472 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001473 *
1474 * @return a {@link NetworkInfo} object for the current default network
1475 * for the given uid or {@code null} if no default network is
1476 * available for the specified uid.
1477 *
1478 * {@hide}
1479 */
1480 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1481 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1482 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1483 return getActiveNetworkInfoForUid(uid, false);
1484 }
1485
1486 /** {@hide} */
1487 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1488 try {
1489 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1490 } catch (RemoteException e) {
1491 throw e.rethrowFromSystemServer();
1492 }
1493 }
1494
1495 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001496 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001497 *
1498 * @param networkType integer specifying which networkType in
1499 * which you're interested.
1500 * @return a {@link NetworkInfo} object for the requested
1501 * network type or {@code null} if the type is not
1502 * supported by the device. If {@code networkType} is
1503 * TYPE_VPN and a VPN is active for the calling app,
1504 * then this method will try to return one of the
1505 * underlying networks for the VPN or null if the
1506 * VPN agent didn't specify any.
1507 *
1508 * @deprecated This method does not support multiple connected networks
1509 * of the same type. Use {@link #getAllNetworks} and
1510 * {@link #getNetworkInfo(android.net.Network)} instead.
1511 */
1512 @Deprecated
1513 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1514 @Nullable
1515 public NetworkInfo getNetworkInfo(int networkType) {
1516 try {
1517 return mService.getNetworkInfo(networkType);
1518 } catch (RemoteException e) {
1519 throw e.rethrowFromSystemServer();
1520 }
1521 }
1522
1523 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001524 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001525 *
1526 * @param network {@link Network} specifying which network
1527 * in which you're interested.
1528 * @return a {@link NetworkInfo} object for the requested
1529 * network or {@code null} if the {@code Network}
1530 * is not valid.
1531 * @deprecated See {@link NetworkInfo}.
1532 */
1533 @Deprecated
1534 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1535 @Nullable
1536 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1537 return getNetworkInfoForUid(network, Process.myUid(), false);
1538 }
1539
1540 /** {@hide} */
1541 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1542 try {
1543 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1544 } catch (RemoteException e) {
1545 throw e.rethrowFromSystemServer();
1546 }
1547 }
1548
1549 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001550 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001551 *
1552 * @return an array of {@link NetworkInfo} objects. Check each
1553 * {@link NetworkInfo#getType} for which type each applies.
1554 *
1555 * @deprecated This method does not support multiple connected networks
1556 * of the same type. Use {@link #getAllNetworks} and
1557 * {@link #getNetworkInfo(android.net.Network)} instead.
1558 */
1559 @Deprecated
1560 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1561 @NonNull
1562 public NetworkInfo[] getAllNetworkInfo() {
1563 try {
1564 return mService.getAllNetworkInfo();
1565 } catch (RemoteException e) {
1566 throw e.rethrowFromSystemServer();
1567 }
1568 }
1569
1570 /**
junyulaib1211372021-03-03 12:09:05 +08001571 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1572 * connected.
1573 * @hide
1574 */
1575 @SystemApi(client = MODULE_LIBRARIES)
1576 @RequiresPermission(anyOf = {
1577 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1578 android.Manifest.permission.NETWORK_STACK,
1579 android.Manifest.permission.NETWORK_SETTINGS})
1580 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001581 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001582 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001583 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001584 } catch (RemoteException e) {
1585 throw e.rethrowFromSystemServer();
1586 }
1587 }
1588
1589 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001590 * Returns the {@link Network} object currently serving a given type, or
1591 * null if the given type is not connected.
1592 *
1593 * @hide
1594 * @deprecated This method does not support multiple connected networks
1595 * of the same type. Use {@link #getAllNetworks} and
1596 * {@link #getNetworkInfo(android.net.Network)} instead.
1597 */
1598 @Deprecated
1599 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1600 @UnsupportedAppUsage
1601 public Network getNetworkForType(int networkType) {
1602 try {
1603 return mService.getNetworkForType(networkType);
1604 } catch (RemoteException e) {
1605 throw e.rethrowFromSystemServer();
1606 }
1607 }
1608
1609 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001610 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001611 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001612 * @deprecated This method does not provide any notification of network state changes, forcing
1613 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1614 * Apps should use methods such as
1615 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1616 * Apps that desire to obtain information about networks that do not apply to them
1617 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1618 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001619 * @return an array of {@link Network} objects.
1620 */
1621 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1622 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001623 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001624 public Network[] getAllNetworks() {
1625 try {
1626 return mService.getAllNetworks();
1627 } catch (RemoteException e) {
1628 throw e.rethrowFromSystemServer();
1629 }
1630 }
1631
1632 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001633 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001634 * the Networks that applications run by the given user will use by default.
1635 * @hide
1636 */
1637 @UnsupportedAppUsage
1638 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1639 try {
1640 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001641 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001642 } catch (RemoteException e) {
1643 throw e.rethrowFromSystemServer();
1644 }
1645 }
1646
1647 /**
1648 * Returns the IP information for the current default network.
1649 *
1650 * @return a {@link LinkProperties} object describing the IP info
1651 * for the current default network, or {@code null} if there
1652 * is no current default network.
1653 *
1654 * {@hide}
1655 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1656 * value of {@link #getActiveNetwork()} instead. In particular,
1657 * this method will return non-null LinkProperties even if the
1658 * app is blocked by policy from using this network.
1659 */
1660 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1661 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1662 public LinkProperties getActiveLinkProperties() {
1663 try {
1664 return mService.getActiveLinkProperties();
1665 } catch (RemoteException e) {
1666 throw e.rethrowFromSystemServer();
1667 }
1668 }
1669
1670 /**
1671 * Returns the IP information for a given network type.
1672 *
1673 * @param networkType the network type of interest.
1674 * @return a {@link LinkProperties} object describing the IP info
1675 * for the given networkType, or {@code null} if there is
1676 * no current default network.
1677 *
1678 * {@hide}
1679 * @deprecated This method does not support multiple connected networks
1680 * of the same type. Use {@link #getAllNetworks},
1681 * {@link #getNetworkInfo(android.net.Network)}, and
1682 * {@link #getLinkProperties(android.net.Network)} instead.
1683 */
1684 @Deprecated
1685 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1686 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1687 public LinkProperties getLinkProperties(int networkType) {
1688 try {
1689 return mService.getLinkPropertiesForType(networkType);
1690 } catch (RemoteException e) {
1691 throw e.rethrowFromSystemServer();
1692 }
1693 }
1694
1695 /**
1696 * Get the {@link LinkProperties} for the given {@link Network}. This
1697 * will return {@code null} if the network is unknown.
1698 *
1699 * @param network The {@link Network} object identifying the network in question.
1700 * @return The {@link LinkProperties} for the network, or {@code null}.
1701 */
1702 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1703 @Nullable
1704 public LinkProperties getLinkProperties(@Nullable Network network) {
1705 try {
1706 return mService.getLinkProperties(network);
1707 } catch (RemoteException e) {
1708 throw e.rethrowFromSystemServer();
1709 }
1710 }
1711
1712 /**
lucaslinc582d502022-01-27 09:07:00 +08001713 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001714 *
lucaslinc582d502022-01-27 09:07:00 +08001715 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1716 * given package, considering its permissions.
1717 *
1718 * @param lp A {@link LinkProperties} which will be redacted.
1719 * @param uid The target uid.
1720 * @param packageName The name of the package, for appops logging.
1721 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1722 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1723 * @hide
1724 */
1725 @RequiresPermission(anyOf = {
1726 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1727 android.Manifest.permission.NETWORK_STACK,
1728 android.Manifest.permission.NETWORK_SETTINGS})
1729 @SystemApi(client = MODULE_LIBRARIES)
1730 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001731 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001732 @NonNull String packageName) {
1733 try {
lucaslind2b06132022-03-02 10:56:57 +08001734 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001735 lp, uid, packageName, getAttributionTag());
1736 } catch (RemoteException e) {
1737 throw e.rethrowFromSystemServer();
1738 }
1739 }
1740
1741 /**
1742 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1743 *
1744 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1745 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1746 * sensitive information. To retrieve this location sensitive information (subject to
1747 * the caller's location permissions), use a {@link NetworkCallback} with the
1748 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1749 *
1750 * This method returns {@code null} if the network is unknown or if the |network| argument
1751 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001752 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001753 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001754 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001755 */
1756 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1757 @Nullable
1758 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1759 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001760 return mService.getNetworkCapabilities(
1761 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001762 } catch (RemoteException e) {
1763 throw e.rethrowFromSystemServer();
1764 }
1765 }
1766
1767 /**
lucaslinc582d502022-01-27 09:07:00 +08001768 * Redact {@link NetworkCapabilities} for a given package.
1769 *
1770 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001771 * to the given package, considering its permissions. If the passed capabilities contain
1772 * location-sensitive information, they will be redacted to the correct degree for the location
1773 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1774 * that level of location. If the UID holds no location permission, the returned object will
1775 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001776 *
1777 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1778 * @param uid The target uid.
1779 * @param packageName The name of the package, for appops logging.
1780 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1781 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1782 * @hide
1783 */
1784 @RequiresPermission(anyOf = {
1785 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1786 android.Manifest.permission.NETWORK_STACK,
1787 android.Manifest.permission.NETWORK_SETTINGS})
1788 @SystemApi(client = MODULE_LIBRARIES)
1789 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001790 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001791 @NonNull NetworkCapabilities nc,
1792 int uid, @NonNull String packageName) {
1793 try {
lucaslind2b06132022-03-02 10:56:57 +08001794 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001795 getAttributionTag());
1796 } catch (RemoteException e) {
1797 throw e.rethrowFromSystemServer();
1798 }
1799 }
1800
1801 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001802 * Gets a URL that can be used for resolving whether a captive portal is present.
1803 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1804 * portal is present.
1805 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1806 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1807 *
1808 * The system network validation may be using different strategies to detect captive portals,
1809 * so this method does not necessarily return a URL used by the system. It only returns a URL
1810 * that may be relevant for other components trying to detect captive portals.
1811 *
1812 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001813 * @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 +09001814 * system.
1815 */
1816 @Deprecated
1817 @SystemApi
1818 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1819 public String getCaptivePortalServerUrl() {
1820 try {
1821 return mService.getCaptivePortalServerUrl();
1822 } catch (RemoteException e) {
1823 throw e.rethrowFromSystemServer();
1824 }
1825 }
1826
1827 /**
1828 * Tells the underlying networking system that the caller wants to
1829 * begin using the named feature. The interpretation of {@code feature}
1830 * is completely up to each networking implementation.
1831 *
1832 * <p>This method requires the caller to hold either the
1833 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1834 * or the ability to modify system settings as determined by
1835 * {@link android.provider.Settings.System#canWrite}.</p>
1836 *
1837 * @param networkType specifies which network the request pertains to
1838 * @param feature the name of the feature to be used
1839 * @return an integer value representing the outcome of the request.
1840 * The interpretation of this value is specific to each networking
1841 * implementation+feature combination, except that the value {@code -1}
1842 * always indicates failure.
1843 *
1844 * @deprecated Deprecated in favor of the cleaner
1845 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1846 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1847 * throw {@code UnsupportedOperationException} if called.
1848 * @removed
1849 */
1850 @Deprecated
1851 public int startUsingNetworkFeature(int networkType, String feature) {
1852 checkLegacyRoutingApiAccess();
1853 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1854 if (netCap == null) {
1855 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1856 feature);
1857 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1858 }
1859
1860 NetworkRequest request = null;
1861 synchronized (sLegacyRequests) {
1862 LegacyRequest l = sLegacyRequests.get(netCap);
1863 if (l != null) {
1864 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1865 renewRequestLocked(l);
1866 if (l.currentNetwork != null) {
1867 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1868 } else {
1869 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1870 }
1871 }
1872
1873 request = requestNetworkForFeatureLocked(netCap);
1874 }
1875 if (request != null) {
1876 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1877 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1878 } else {
1879 Log.d(TAG, " request Failed");
1880 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1881 }
1882 }
1883
1884 /**
1885 * Tells the underlying networking system that the caller is finished
1886 * using the named feature. The interpretation of {@code feature}
1887 * is completely up to each networking implementation.
1888 *
1889 * <p>This method requires the caller to hold either the
1890 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1891 * or the ability to modify system settings as determined by
1892 * {@link android.provider.Settings.System#canWrite}.</p>
1893 *
1894 * @param networkType specifies which network the request pertains to
1895 * @param feature the name of the feature that is no longer needed
1896 * @return an integer value representing the outcome of the request.
1897 * The interpretation of this value is specific to each networking
1898 * implementation+feature combination, except that the value {@code -1}
1899 * always indicates failure.
1900 *
1901 * @deprecated Deprecated in favor of the cleaner
1902 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1903 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1904 * throw {@code UnsupportedOperationException} if called.
1905 * @removed
1906 */
1907 @Deprecated
1908 public int stopUsingNetworkFeature(int networkType, String feature) {
1909 checkLegacyRoutingApiAccess();
1910 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1911 if (netCap == null) {
1912 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1913 feature);
1914 return -1;
1915 }
1916
1917 if (removeRequestForFeature(netCap)) {
1918 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1919 }
1920 return 1;
1921 }
1922
1923 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1924 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1925 if (networkType == TYPE_MOBILE) {
1926 switch (feature) {
1927 case "enableCBS":
1928 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1929 case "enableDUN":
1930 case "enableDUNAlways":
1931 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1932 case "enableFOTA":
1933 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1934 case "enableHIPRI":
1935 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1936 case "enableIMS":
1937 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1938 case "enableMMS":
1939 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1940 case "enableSUPL":
1941 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1942 default:
1943 return null;
1944 }
1945 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1946 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1947 }
1948 return null;
1949 }
1950
1951 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1952 if (netCap == null) return TYPE_NONE;
1953 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1954 return TYPE_MOBILE_CBS;
1955 }
1956 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1957 return TYPE_MOBILE_IMS;
1958 }
1959 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1960 return TYPE_MOBILE_FOTA;
1961 }
1962 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1963 return TYPE_MOBILE_DUN;
1964 }
1965 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1966 return TYPE_MOBILE_SUPL;
1967 }
1968 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1969 return TYPE_MOBILE_MMS;
1970 }
1971 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1972 return TYPE_MOBILE_HIPRI;
1973 }
1974 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1975 return TYPE_WIFI_P2P;
1976 }
1977 return TYPE_NONE;
1978 }
1979
1980 private static class LegacyRequest {
1981 NetworkCapabilities networkCapabilities;
1982 NetworkRequest networkRequest;
1983 int expireSequenceNumber;
1984 Network currentNetwork;
1985 int delay = -1;
1986
1987 private void clearDnsBinding() {
1988 if (currentNetwork != null) {
1989 currentNetwork = null;
1990 setProcessDefaultNetworkForHostResolution(null);
1991 }
1992 }
1993
1994 NetworkCallback networkCallback = new NetworkCallback() {
1995 @Override
1996 public void onAvailable(Network network) {
1997 currentNetwork = network;
1998 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1999 setProcessDefaultNetworkForHostResolution(network);
2000 }
2001 @Override
2002 public void onLost(Network network) {
2003 if (network.equals(currentNetwork)) clearDnsBinding();
2004 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2005 }
2006 };
2007 }
2008
2009 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2010 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2011 new HashMap<>();
2012
2013 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2014 synchronized (sLegacyRequests) {
2015 LegacyRequest l = sLegacyRequests.get(netCap);
2016 if (l != null) return l.networkRequest;
2017 }
2018 return null;
2019 }
2020
2021 private void renewRequestLocked(LegacyRequest l) {
2022 l.expireSequenceNumber++;
2023 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2024 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2025 }
2026
2027 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2028 int ourSeqNum = -1;
2029 synchronized (sLegacyRequests) {
2030 LegacyRequest l = sLegacyRequests.get(netCap);
2031 if (l == null) return;
2032 ourSeqNum = l.expireSequenceNumber;
2033 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2034 }
2035 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2036 }
2037
2038 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2039 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2040 int delay = -1;
2041 int type = legacyTypeForNetworkCapabilities(netCap);
2042 try {
2043 delay = mService.getRestoreDefaultNetworkDelay(type);
2044 } catch (RemoteException e) {
2045 throw e.rethrowFromSystemServer();
2046 }
2047 LegacyRequest l = new LegacyRequest();
2048 l.networkCapabilities = netCap;
2049 l.delay = delay;
2050 l.expireSequenceNumber = 0;
2051 l.networkRequest = sendRequestForNetwork(
2052 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2053 if (l.networkRequest == null) return null;
2054 sLegacyRequests.put(netCap, l);
2055 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2056 return l.networkRequest;
2057 }
2058
2059 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2060 if (delay >= 0) {
2061 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2062 CallbackHandler handler = getDefaultHandler();
2063 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2064 handler.sendMessageDelayed(msg, delay);
2065 }
2066 }
2067
2068 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2069 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2070 final LegacyRequest l;
2071 synchronized (sLegacyRequests) {
2072 l = sLegacyRequests.remove(netCap);
2073 }
2074 if (l == null) return false;
2075 unregisterNetworkCallback(l.networkCallback);
2076 l.clearDnsBinding();
2077 return true;
2078 }
2079
2080 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2081 static {
2082 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2083 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2084 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2085 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2086 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2087 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2088 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2089 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2090 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2091 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2092 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2093 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2094 }
2095
2096 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2097 static {
2098 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2099 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2100 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2101 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2102 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2103 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2104 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2105 }
2106
2107 /**
2108 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2109 * instance suitable for registering a request or callback. Throws an
2110 * IllegalArgumentException if no mapping from the legacy type to
2111 * NetworkCapabilities is known.
2112 *
2113 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2114 * to find the network instead.
2115 * @hide
2116 */
2117 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2118 final NetworkCapabilities nc = new NetworkCapabilities();
2119
2120 // Map from type to transports.
2121 final int NOT_FOUND = -1;
2122 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002123 if (transport == NOT_FOUND) {
2124 throw new IllegalArgumentException("unknown legacy type: " + type);
2125 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002126 nc.addTransportType(transport);
2127
2128 // Map from type to capabilities.
2129 nc.addCapability(sLegacyTypeToCapability.get(
2130 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2131 nc.maybeMarkCapabilitiesRestricted();
2132 return nc;
2133 }
2134
2135 /** @hide */
2136 public static class PacketKeepaliveCallback {
2137 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2138 public PacketKeepaliveCallback() {
2139 }
2140 /** The requested keepalive was successfully started. */
2141 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2142 public void onStarted() {}
2143 /** The keepalive was successfully stopped. */
2144 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2145 public void onStopped() {}
2146 /** An error occurred. */
2147 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2148 public void onError(int error) {}
2149 }
2150
2151 /**
2152 * Allows applications to request that the system periodically send specific packets on their
2153 * behalf, using hardware offload to save battery power.
2154 *
2155 * To request that the system send keepalives, call one of the methods that return a
2156 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2157 * passing in a non-null callback. If the callback is successfully started, the callback's
2158 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2159 * specifying one of the {@code ERROR_*} constants in this class.
2160 *
2161 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2162 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2163 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2164 *
2165 * @deprecated Use {@link SocketKeepalive} instead.
2166 *
2167 * @hide
2168 */
2169 public class PacketKeepalive {
2170
2171 private static final String TAG = "PacketKeepalive";
2172
2173 /** @hide */
2174 public static final int SUCCESS = 0;
2175
2176 /** @hide */
2177 public static final int NO_KEEPALIVE = -1;
2178
2179 /** @hide */
2180 public static final int BINDER_DIED = -10;
2181
2182 /** The specified {@code Network} is not connected. */
2183 public static final int ERROR_INVALID_NETWORK = -20;
2184 /** The specified IP addresses are invalid. For example, the specified source IP address is
2185 * not configured on the specified {@code Network}. */
2186 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2187 /** The requested port is invalid. */
2188 public static final int ERROR_INVALID_PORT = -22;
2189 /** The packet length is invalid (e.g., too long). */
2190 public static final int ERROR_INVALID_LENGTH = -23;
2191 /** The packet transmission interval is invalid (e.g., too short). */
2192 public static final int ERROR_INVALID_INTERVAL = -24;
2193
2194 /** The hardware does not support this request. */
2195 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2196 /** The hardware returned an error. */
2197 public static final int ERROR_HARDWARE_ERROR = -31;
2198
2199 /** The NAT-T destination port for IPsec */
2200 public static final int NATT_PORT = 4500;
2201
2202 /** The minimum interval in seconds between keepalive packet transmissions */
2203 public static final int MIN_INTERVAL = 10;
2204
2205 private final Network mNetwork;
2206 private final ISocketKeepaliveCallback mCallback;
2207 private final ExecutorService mExecutor;
2208
2209 private volatile Integer mSlot;
2210
2211 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2212 public void stop() {
2213 try {
2214 mExecutor.execute(() -> {
2215 try {
2216 if (mSlot != null) {
2217 mService.stopKeepalive(mNetwork, mSlot);
2218 }
2219 } catch (RemoteException e) {
2220 Log.e(TAG, "Error stopping packet keepalive: ", e);
2221 throw e.rethrowFromSystemServer();
2222 }
2223 });
2224 } catch (RejectedExecutionException e) {
2225 // The internal executor has already stopped due to previous event.
2226 }
2227 }
2228
2229 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002230 Objects.requireNonNull(network, "network cannot be null");
2231 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002232 mNetwork = network;
2233 mExecutor = Executors.newSingleThreadExecutor();
2234 mCallback = new ISocketKeepaliveCallback.Stub() {
2235 @Override
2236 public void onStarted(int slot) {
2237 final long token = Binder.clearCallingIdentity();
2238 try {
2239 mExecutor.execute(() -> {
2240 mSlot = slot;
2241 callback.onStarted();
2242 });
2243 } finally {
2244 Binder.restoreCallingIdentity(token);
2245 }
2246 }
2247
2248 @Override
2249 public void onStopped() {
2250 final long token = Binder.clearCallingIdentity();
2251 try {
2252 mExecutor.execute(() -> {
2253 mSlot = null;
2254 callback.onStopped();
2255 });
2256 } finally {
2257 Binder.restoreCallingIdentity(token);
2258 }
2259 mExecutor.shutdown();
2260 }
2261
2262 @Override
2263 public void onError(int error) {
2264 final long token = Binder.clearCallingIdentity();
2265 try {
2266 mExecutor.execute(() -> {
2267 mSlot = null;
2268 callback.onError(error);
2269 });
2270 } finally {
2271 Binder.restoreCallingIdentity(token);
2272 }
2273 mExecutor.shutdown();
2274 }
2275
2276 @Override
2277 public void onDataReceived() {
2278 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2279 // this callback when data is received.
2280 }
2281 };
2282 }
2283 }
2284
2285 /**
2286 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2287 *
2288 * @deprecated Use {@link #createSocketKeepalive} instead.
2289 *
2290 * @hide
2291 */
2292 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2293 public PacketKeepalive startNattKeepalive(
2294 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2295 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2296 final PacketKeepalive k = new PacketKeepalive(network, callback);
2297 try {
2298 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2299 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2300 } catch (RemoteException e) {
2301 Log.e(TAG, "Error starting packet keepalive: ", e);
2302 throw e.rethrowFromSystemServer();
2303 }
2304 return k;
2305 }
2306
2307 // Construct an invalid fd.
2308 private ParcelFileDescriptor createInvalidFd() {
2309 final int invalidFd = -1;
2310 return ParcelFileDescriptor.adoptFd(invalidFd);
2311 }
2312
2313 /**
2314 * Request that keepalives be started on a IPsec NAT-T socket.
2315 *
2316 * @param network The {@link Network} the socket is on.
2317 * @param socket The socket that needs to be kept alive.
2318 * @param source The source address of the {@link UdpEncapsulationSocket}.
2319 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2320 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2321 * must run callback sequentially, otherwise the order of callbacks cannot be
2322 * guaranteed.
2323 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2324 * changes. Must be extended by applications that use this API.
2325 *
2326 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2327 * given socket.
2328 **/
2329 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2330 @NonNull UdpEncapsulationSocket socket,
2331 @NonNull InetAddress source,
2332 @NonNull InetAddress destination,
2333 @NonNull @CallbackExecutor Executor executor,
2334 @NonNull Callback callback) {
2335 ParcelFileDescriptor dup;
2336 try {
2337 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2338 // which cannot be obtained by the app process.
2339 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2340 } catch (IOException ignored) {
2341 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2342 // ERROR_INVALID_SOCKET.
2343 dup = createInvalidFd();
2344 }
2345 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2346 destination, executor, callback);
2347 }
2348
2349 /**
2350 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2351 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2352 *
2353 * @param network The {@link Network} the socket is on.
2354 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2355 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2356 * from that port.
2357 * @param source The source address of the {@link UdpEncapsulationSocket}.
2358 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2359 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2360 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2361 * must run callback sequentially, otherwise the order of callbacks cannot be
2362 * guaranteed.
2363 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2364 * changes. Must be extended by applications that use this API.
2365 *
2366 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2367 * given socket.
2368 * @hide
2369 */
2370 @SystemApi
2371 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2372 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2373 @NonNull ParcelFileDescriptor pfd,
2374 @NonNull InetAddress source,
2375 @NonNull InetAddress destination,
2376 @NonNull @CallbackExecutor Executor executor,
2377 @NonNull Callback callback) {
2378 ParcelFileDescriptor dup;
2379 try {
2380 // TODO: Consider remove unnecessary dup.
2381 dup = pfd.dup();
2382 } catch (IOException ignored) {
2383 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2384 // ERROR_INVALID_SOCKET.
2385 dup = createInvalidFd();
2386 }
2387 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002388 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002389 }
2390
2391 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002392 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002393 *
2394 * @param network The {@link Network} the socket is on.
2395 * @param socket The socket that needs to be kept alive.
2396 * @param executor The executor on which callback will be invoked. This implementation assumes
2397 * the provided {@link Executor} runs the callbacks in sequence with no
2398 * concurrency. Failing this, no guarantee of correctness can be made. It is
2399 * the responsibility of the caller to ensure the executor provides this
2400 * guarantee. A simple way of creating such an executor is with the standard
2401 * tool {@code Executors.newSingleThreadExecutor}.
2402 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2403 * changes. Must be extended by applications that use this API.
2404 *
2405 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2406 * given socket.
2407 * @hide
2408 */
2409 @SystemApi
2410 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2411 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2412 @NonNull Socket socket,
2413 @NonNull Executor executor,
2414 @NonNull Callback callback) {
2415 ParcelFileDescriptor dup;
2416 try {
2417 dup = ParcelFileDescriptor.fromSocket(socket);
2418 } catch (UncheckedIOException ignored) {
2419 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2420 // ERROR_INVALID_SOCKET.
2421 dup = createInvalidFd();
2422 }
2423 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2424 }
2425
2426 /**
2427 * Ensure that a network route exists to deliver traffic to the specified
2428 * host via the specified network interface. An attempt to add a route that
2429 * already exists is ignored, but treated as successful.
2430 *
2431 * <p>This method requires the caller to hold either the
2432 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2433 * or the ability to modify system settings as determined by
2434 * {@link android.provider.Settings.System#canWrite}.</p>
2435 *
2436 * @param networkType the type of the network over which traffic to the specified
2437 * host is to be routed
2438 * @param hostAddress the IP address of the host to which the route is desired
2439 * @return {@code true} on success, {@code false} on failure
2440 *
2441 * @deprecated Deprecated in favor of the
2442 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2443 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2444 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2445 * throw {@code UnsupportedOperationException} if called.
2446 * @removed
2447 */
2448 @Deprecated
2449 public boolean requestRouteToHost(int networkType, int hostAddress) {
2450 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2451 }
2452
2453 /**
2454 * Ensure that a network route exists to deliver traffic to the specified
2455 * host via the specified network interface. An attempt to add a route that
2456 * already exists is ignored, but treated as successful.
2457 *
2458 * <p>This method requires the caller to hold either the
2459 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2460 * or the ability to modify system settings as determined by
2461 * {@link android.provider.Settings.System#canWrite}.</p>
2462 *
2463 * @param networkType the type of the network over which traffic to the specified
2464 * host is to be routed
2465 * @param hostAddress the IP address of the host to which the route is desired
2466 * @return {@code true} on success, {@code false} on failure
2467 * @hide
2468 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2469 * {@link #bindProcessToNetwork} API.
2470 */
2471 @Deprecated
2472 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002473 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002474 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2475 checkLegacyRoutingApiAccess();
2476 try {
2477 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2478 mContext.getOpPackageName(), getAttributionTag());
2479 } catch (RemoteException e) {
2480 throw e.rethrowFromSystemServer();
2481 }
2482 }
2483
2484 /**
2485 * @return the context's attribution tag
2486 */
2487 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2488 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002489 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002490 }
2491
2492 /**
2493 * Returns the value of the setting for background data usage. If false,
2494 * applications should not use the network if the application is not in the
2495 * foreground. Developers should respect this setting, and check the value
2496 * of this before performing any background data operations.
2497 * <p>
2498 * All applications that have background services that use the network
2499 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2500 * <p>
2501 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2502 * background data depends on several combined factors, and this method will
2503 * always return {@code true}. Instead, when background data is unavailable,
2504 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2505 *
2506 * @return Whether background data usage is allowed.
2507 */
2508 @Deprecated
2509 public boolean getBackgroundDataSetting() {
2510 // assume that background data is allowed; final authority is
2511 // NetworkInfo which may be blocked.
2512 return true;
2513 }
2514
2515 /**
2516 * Sets the value of the setting for background data usage.
2517 *
2518 * @param allowBackgroundData Whether an application should use data while
2519 * it is in the background.
2520 *
2521 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2522 * @see #getBackgroundDataSetting()
2523 * @hide
2524 */
2525 @Deprecated
2526 @UnsupportedAppUsage
2527 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2528 // ignored
2529 }
2530
2531 /**
2532 * @hide
2533 * @deprecated Talk to TelephonyManager directly
2534 */
2535 @Deprecated
2536 @UnsupportedAppUsage
2537 public boolean getMobileDataEnabled() {
2538 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2539 if (tm != null) {
2540 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2541 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2542 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2543 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2544 + " retVal=" + retVal);
2545 return retVal;
2546 }
2547 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2548 return false;
2549 }
2550
2551 /**
2552 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2553 * to find out when the system default network has gone in to a high power state.
2554 */
2555 public interface OnNetworkActiveListener {
2556 /**
2557 * Called on the main thread of the process to report that the current data network
2558 * has become active, and it is now a good time to perform any pending network
2559 * operations. Note that this listener only tells you when the network becomes
2560 * active; if at any other time you want to know whether it is active (and thus okay
2561 * to initiate network traffic), you can retrieve its instantaneous state with
2562 * {@link ConnectivityManager#isDefaultNetworkActive}.
2563 */
2564 void onNetworkActive();
2565 }
2566
Chiachang Wang2de41682021-09-23 10:46:03 +08002567 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002568 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2569 mNetworkActivityListeners = new ArrayMap<>();
2570
2571 /**
2572 * Start listening to reports when the system's default data network is active, meaning it is
2573 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2574 * to determine the current state of the system's default network after registering the
2575 * listener.
2576 * <p>
2577 * If the process default network has been set with
2578 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2579 * reflect the process's default, but the system default.
2580 *
2581 * @param l The listener to be told when the network is active.
2582 */
2583 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002584 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002585 @Override
2586 public void onNetworkActive() throws RemoteException {
2587 l.onNetworkActive();
2588 }
2589 };
2590
Chiachang Wang2de41682021-09-23 10:46:03 +08002591 synchronized (mNetworkActivityListeners) {
2592 try {
2593 mService.registerNetworkActivityListener(rl);
2594 mNetworkActivityListeners.put(l, rl);
2595 } catch (RemoteException e) {
2596 throw e.rethrowFromSystemServer();
2597 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002598 }
2599 }
2600
2601 /**
2602 * Remove network active listener previously registered with
2603 * {@link #addDefaultNetworkActiveListener}.
2604 *
2605 * @param l Previously registered listener.
2606 */
2607 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002608 synchronized (mNetworkActivityListeners) {
2609 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2610 if (rl == null) {
2611 throw new IllegalArgumentException("Listener was not registered.");
2612 }
2613 try {
2614 mService.unregisterNetworkActivityListener(rl);
2615 mNetworkActivityListeners.remove(l);
2616 } catch (RemoteException e) {
2617 throw e.rethrowFromSystemServer();
2618 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002619 }
2620 }
2621
2622 /**
2623 * Return whether the data network is currently active. An active network means that
2624 * it is currently in a high power state for performing data transmission. On some
2625 * types of networks, it may be expensive to move and stay in such a state, so it is
2626 * more power efficient to batch network traffic together when the radio is already in
2627 * this state. This method tells you whether right now is currently a good time to
2628 * initiate network traffic, as the network is already active.
2629 */
2630 public boolean isDefaultNetworkActive() {
2631 try {
lucaslin709eb842021-01-21 02:04:15 +08002632 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002633 } catch (RemoteException e) {
2634 throw e.rethrowFromSystemServer();
2635 }
2636 }
2637
2638 /**
2639 * {@hide}
2640 */
2641 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002642 this(context, service, true /* newStatic */);
2643 }
2644
2645 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002646 mContext = Objects.requireNonNull(context, "missing context");
2647 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002648 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2649 // different ConnectivityManager, but that's still OK considering its usage.
2650 if (sInstance == null && newStatic) {
2651 final Context appContext = mContext.getApplicationContext();
2652 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2653 // If the application context is null, we're either in the system process or
2654 // it's the application context very early in app initialization. In both these
2655 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2656 // service. http://b/27532714 .
2657 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2658 false /* newStatic */);
2659 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002660 }
2661
2662 /** {@hide} */
2663 @UnsupportedAppUsage
2664 public static ConnectivityManager from(Context context) {
2665 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2666 }
2667
2668 /** @hide */
2669 public NetworkRequest getDefaultRequest() {
2670 try {
2671 // This is not racy as the default request is final in ConnectivityService.
2672 return mService.getDefaultRequest();
2673 } catch (RemoteException e) {
2674 throw e.rethrowFromSystemServer();
2675 }
2676 }
2677
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002678 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002679 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002680 * happened.
2681 *
2682 * @return {@code true} iff the package is allowed to write settings.
2683 */
2684 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2685 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2686 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2687 boolean throwException) {
2688 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002689 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002690 }
2691
2692 /**
2693 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2694 * situations where a Context pointer is unavailable.
2695 * @hide
2696 */
2697 @Deprecated
2698 static ConnectivityManager getInstanceOrNull() {
2699 return sInstance;
2700 }
2701
2702 /**
2703 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2704 * situations where a Context pointer is unavailable.
2705 * @hide
2706 */
2707 @Deprecated
2708 @UnsupportedAppUsage
2709 private static ConnectivityManager getInstance() {
2710 if (getInstanceOrNull() == null) {
2711 throw new IllegalStateException("No ConnectivityManager yet constructed");
2712 }
2713 return getInstanceOrNull();
2714 }
2715
2716 /**
2717 * Get the set of tetherable, available interfaces. This list is limited by
2718 * device configuration and current interface existence.
2719 *
2720 * @return an array of 0 or more Strings of tetherable interface names.
2721 *
2722 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2723 * {@hide}
2724 */
2725 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2726 @UnsupportedAppUsage
2727 @Deprecated
2728 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002729 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002730 }
2731
2732 /**
2733 * Get the set of tethered interfaces.
2734 *
2735 * @return an array of 0 or more String of currently tethered interface names.
2736 *
2737 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2738 * {@hide}
2739 */
2740 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2741 @UnsupportedAppUsage
2742 @Deprecated
2743 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002744 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002745 }
2746
2747 /**
2748 * Get the set of interface names which attempted to tether but
2749 * failed. Re-attempting to tether may cause them to reset to the Tethered
2750 * state. Alternatively, causing the interface to be destroyed and recreated
2751 * may cause them to reset to the available state.
2752 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2753 * information on the cause of the errors.
2754 *
2755 * @return an array of 0 or more String indicating the interface names
2756 * which failed to tether.
2757 *
2758 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2759 * {@hide}
2760 */
2761 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2762 @UnsupportedAppUsage
2763 @Deprecated
2764 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002765 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002766 }
2767
2768 /**
2769 * Get the set of tethered dhcp ranges.
2770 *
2771 * @deprecated This method is not supported.
2772 * TODO: remove this function when all of clients are removed.
2773 * {@hide}
2774 */
2775 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2776 @Deprecated
2777 public String[] getTetheredDhcpRanges() {
2778 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2779 }
2780
2781 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002782 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002783 * on the interface, forward and NAT IP packets and forward DNS requests
2784 * to the best active upstream network interface. Note that if no upstream
2785 * IP network interface is available, dhcp will still run and traffic will be
2786 * allowed between the tethered devices and this device, though upstream net
2787 * access will of course fail until an upstream network interface becomes
2788 * active.
2789 *
2790 * <p>This method requires the caller to hold either the
2791 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2792 * or the ability to modify system settings as determined by
2793 * {@link android.provider.Settings.System#canWrite}.</p>
2794 *
2795 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2796 * and WifiStateMachine which need direct access. All other clients should use
2797 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2798 * logic.</p>
2799 *
2800 * @param iface the interface name to tether.
2801 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2802 * @deprecated Use {@link TetheringManager#startTethering} instead
2803 *
2804 * {@hide}
2805 */
2806 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2807 @Deprecated
2808 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002809 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002810 }
2811
2812 /**
2813 * Stop tethering the named interface.
2814 *
2815 * <p>This method requires the caller to hold either the
2816 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2817 * or the ability to modify system settings as determined by
2818 * {@link android.provider.Settings.System#canWrite}.</p>
2819 *
2820 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2821 * and WifiStateMachine which need direct access. All other clients should use
2822 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2823 * logic.</p>
2824 *
2825 * @param iface the interface name to untether.
2826 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2827 *
2828 * {@hide}
2829 */
2830 @UnsupportedAppUsage
2831 @Deprecated
2832 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002833 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002834 }
2835
2836 /**
2837 * Check if the device allows for tethering. It may be disabled via
2838 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2839 * due to device configuration.
2840 *
2841 * <p>If this app does not have permission to use this API, it will always
2842 * return false rather than throw an exception.</p>
2843 *
2844 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2845 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2846 *
2847 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2848 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2849 *
2850 * @return a boolean - {@code true} indicating Tethering is supported.
2851 *
2852 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2853 * {@hide}
2854 */
2855 @SystemApi
2856 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2857 android.Manifest.permission.WRITE_SETTINGS})
2858 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002859 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002860 }
2861
2862 /**
2863 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2864 *
2865 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2866 * @hide
2867 */
2868 @SystemApi
2869 @Deprecated
2870 public static abstract class OnStartTetheringCallback {
2871 /**
2872 * Called when tethering has been successfully started.
2873 */
2874 public void onTetheringStarted() {}
2875
2876 /**
2877 * Called when starting tethering failed.
2878 */
2879 public void onTetheringFailed() {}
2880 }
2881
2882 /**
2883 * Convenient overload for
2884 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2885 * handler to run on the current thread's {@link Looper}.
2886 *
2887 * @deprecated Use {@link TetheringManager#startTethering} instead.
2888 * @hide
2889 */
2890 @SystemApi
2891 @Deprecated
2892 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2893 public void startTethering(int type, boolean showProvisioningUi,
2894 final OnStartTetheringCallback callback) {
2895 startTethering(type, showProvisioningUi, callback, null);
2896 }
2897
2898 /**
2899 * Runs tether provisioning for the given type if needed and then starts tethering if
2900 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2901 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2902 * schedules tether provisioning re-checks if appropriate.
2903 *
2904 * @param type The type of tethering to start. Must be one of
2905 * {@link ConnectivityManager.TETHERING_WIFI},
2906 * {@link ConnectivityManager.TETHERING_USB}, or
2907 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2908 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2909 * is one. This should be true the first time this function is called and also any time
2910 * the user can see this UI. It gives users information from their carrier about the
2911 * check failing and how they can sign up for tethering if possible.
2912 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2913 * of the result of trying to tether.
2914 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2915 *
2916 * @deprecated Use {@link TetheringManager#startTethering} instead.
2917 * @hide
2918 */
2919 @SystemApi
2920 @Deprecated
2921 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2922 public void startTethering(int type, boolean showProvisioningUi,
2923 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002924 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002925
2926 final Executor executor = new Executor() {
2927 @Override
2928 public void execute(Runnable command) {
2929 if (handler == null) {
2930 command.run();
2931 } else {
2932 handler.post(command);
2933 }
2934 }
2935 };
2936
2937 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2938 @Override
2939 public void onTetheringStarted() {
2940 callback.onTetheringStarted();
2941 }
2942
2943 @Override
2944 public void onTetheringFailed(final int error) {
2945 callback.onTetheringFailed();
2946 }
2947 };
2948
2949 final TetheringRequest request = new TetheringRequest.Builder(type)
2950 .setShouldShowEntitlementUi(showProvisioningUi).build();
2951
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002952 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002953 }
2954
2955 /**
2956 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2957 * applicable.
2958 *
2959 * @param type The type of tethering to stop. Must be one of
2960 * {@link ConnectivityManager.TETHERING_WIFI},
2961 * {@link ConnectivityManager.TETHERING_USB}, or
2962 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2963 *
2964 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2965 * @hide
2966 */
2967 @SystemApi
2968 @Deprecated
2969 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2970 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002971 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002972 }
2973
2974 /**
2975 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2976 * upstream status.
2977 *
2978 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2979 * @hide
2980 */
2981 @SystemApi
2982 @Deprecated
2983 public abstract static class OnTetheringEventCallback {
2984
2985 /**
2986 * Called when tethering upstream changed. This can be called multiple times and can be
2987 * called any time.
2988 *
2989 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2990 * have any upstream.
2991 */
2992 public void onUpstreamChanged(@Nullable Network network) {}
2993 }
2994
2995 @GuardedBy("mTetheringEventCallbacks")
2996 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2997 mTetheringEventCallbacks = new ArrayMap<>();
2998
2999 /**
3000 * Start listening to tethering change events. Any new added callback will receive the last
3001 * tethering status right away. If callback is registered when tethering has no upstream or
3002 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3003 * with a null argument. The same callback object cannot be registered twice.
3004 *
3005 * @param executor the executor on which callback will be invoked.
3006 * @param callback the callback to be called when tethering has change events.
3007 *
3008 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3009 * @hide
3010 */
3011 @SystemApi
3012 @Deprecated
3013 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3014 public void registerTetheringEventCallback(
3015 @NonNull @CallbackExecutor Executor executor,
3016 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003017 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003018
3019 final TetheringEventCallback tetherCallback =
3020 new TetheringEventCallback() {
3021 @Override
3022 public void onUpstreamChanged(@Nullable Network network) {
3023 callback.onUpstreamChanged(network);
3024 }
3025 };
3026
3027 synchronized (mTetheringEventCallbacks) {
3028 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003029 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003030 }
3031 }
3032
3033 /**
3034 * Remove tethering event callback previously registered with
3035 * {@link #registerTetheringEventCallback}.
3036 *
3037 * @param callback previously registered callback.
3038 *
3039 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3040 * @hide
3041 */
3042 @SystemApi
3043 @Deprecated
3044 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3045 public void unregisterTetheringEventCallback(
3046 @NonNull final OnTetheringEventCallback callback) {
3047 Objects.requireNonNull(callback, "The callback must be non-null");
3048 synchronized (mTetheringEventCallbacks) {
3049 final TetheringEventCallback tetherCallback =
3050 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003051 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003052 }
3053 }
3054
3055
3056 /**
3057 * Get the list of regular expressions that define any tetherable
3058 * USB network interfaces. If USB tethering is not supported by the
3059 * device, this list should be empty.
3060 *
3061 * @return an array of 0 or more regular expression Strings defining
3062 * what interfaces are considered tetherable usb interfaces.
3063 *
3064 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3065 * {@hide}
3066 */
3067 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3068 @UnsupportedAppUsage
3069 @Deprecated
3070 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003071 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003072 }
3073
3074 /**
3075 * Get the list of regular expressions that define any tetherable
3076 * Wifi network interfaces. If Wifi tethering is not supported by the
3077 * device, this list should be empty.
3078 *
3079 * @return an array of 0 or more regular expression Strings defining
3080 * what interfaces are considered tetherable wifi interfaces.
3081 *
3082 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3083 * {@hide}
3084 */
3085 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3086 @UnsupportedAppUsage
3087 @Deprecated
3088 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003089 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003090 }
3091
3092 /**
3093 * Get the list of regular expressions that define any tetherable
3094 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3095 * device, this list should be empty.
3096 *
3097 * @return an array of 0 or more regular expression Strings defining
3098 * what interfaces are considered tetherable bluetooth interfaces.
3099 *
3100 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3101 *TetheringManager.TetheringInterfaceRegexps)} instead.
3102 * {@hide}
3103 */
3104 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3105 @UnsupportedAppUsage
3106 @Deprecated
3107 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003108 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003109 }
3110
3111 /**
3112 * Attempt to both alter the mode of USB and Tethering of USB. A
3113 * utility method to deal with some of the complexity of USB - will
3114 * attempt to switch to Rndis and subsequently tether the resulting
3115 * interface on {@code true} or turn off tethering and switch off
3116 * Rndis on {@code false}.
3117 *
3118 * <p>This method requires the caller to hold either the
3119 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3120 * or the ability to modify system settings as determined by
3121 * {@link android.provider.Settings.System#canWrite}.</p>
3122 *
3123 * @param enable a boolean - {@code true} to enable tethering
3124 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3125 * @deprecated Use {@link TetheringManager#startTethering} instead
3126 *
3127 * {@hide}
3128 */
3129 @UnsupportedAppUsage
3130 @Deprecated
3131 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003132 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003133 }
3134
3135 /**
3136 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3137 * {@hide}
3138 */
3139 @SystemApi
3140 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003141 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003142 /**
3143 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3144 * {@hide}
3145 */
3146 @Deprecated
3147 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3148 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3149 /**
3150 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3151 * {@hide}
3152 */
3153 @Deprecated
3154 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3155 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3156 /**
3157 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3158 * {@hide}
3159 */
3160 @Deprecated
3161 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3162 /**
3163 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3164 * {@hide}
3165 */
3166 @Deprecated
3167 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3168 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3169 /**
3170 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3171 * {@hide}
3172 */
3173 @Deprecated
3174 public static final int TETHER_ERROR_MASTER_ERROR =
3175 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3176 /**
3177 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3178 * {@hide}
3179 */
3180 @Deprecated
3181 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3182 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3183 /**
3184 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3185 * {@hide}
3186 */
3187 @Deprecated
3188 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3189 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3190 /**
3191 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3192 * {@hide}
3193 */
3194 @Deprecated
3195 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3196 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3197 /**
3198 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3199 * {@hide}
3200 */
3201 @Deprecated
3202 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3203 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3204 /**
3205 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3206 * {@hide}
3207 */
3208 @Deprecated
3209 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3210 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3211 /**
3212 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3213 * {@hide}
3214 */
3215 @SystemApi
3216 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003217 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003218 /**
3219 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3220 * {@hide}
3221 */
3222 @Deprecated
3223 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3224 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3225 /**
3226 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3227 * {@hide}
3228 */
3229 @SystemApi
3230 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003231 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003232
3233 /**
3234 * Get a more detailed error code after a Tethering or Untethering
3235 * request asynchronously failed.
3236 *
3237 * @param iface The name of the interface of interest
3238 * @return error The error code of the last error tethering or untethering the named
3239 * interface
3240 *
3241 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3242 * {@hide}
3243 */
3244 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3245 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3246 @Deprecated
3247 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003248 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003249 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3250 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3251 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3252 // instead.
3253 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3254 }
3255 return error;
3256 }
3257
3258 /** @hide */
3259 @Retention(RetentionPolicy.SOURCE)
3260 @IntDef(value = {
3261 TETHER_ERROR_NO_ERROR,
3262 TETHER_ERROR_PROVISION_FAILED,
3263 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3264 })
3265 public @interface EntitlementResultCode {
3266 }
3267
3268 /**
3269 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3270 * entitlement succeeded.
3271 *
3272 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3273 * @hide
3274 */
3275 @SystemApi
3276 @Deprecated
3277 public interface OnTetheringEntitlementResultListener {
3278 /**
3279 * Called to notify entitlement result.
3280 *
3281 * @param resultCode an int value of entitlement result. It may be one of
3282 * {@link #TETHER_ERROR_NO_ERROR},
3283 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3284 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3285 */
3286 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3287 }
3288
3289 /**
3290 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003291 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3292 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003293 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003294 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003295 * any reason will update the cached value.
3296 *
3297 * @param type the downstream type of tethering. Must be one of
3298 * {@link #TETHERING_WIFI},
3299 * {@link #TETHERING_USB}, or
3300 * {@link #TETHERING_BLUETOOTH}.
3301 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3302 * @param executor the executor on which callback will be invoked.
3303 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3304 * notify the caller of the result of entitlement check. The listener may be called zero
3305 * or one time.
3306 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3307 * {@hide}
3308 */
3309 @SystemApi
3310 @Deprecated
3311 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3312 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3313 @NonNull @CallbackExecutor Executor executor,
3314 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003315 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003316 ResultReceiver wrappedListener = new ResultReceiver(null) {
3317 @Override
3318 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003319 final long token = Binder.clearCallingIdentity();
3320 try {
3321 executor.execute(() -> {
3322 listener.onTetheringEntitlementResult(resultCode);
3323 });
3324 } finally {
3325 Binder.restoreCallingIdentity(token);
3326 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003327 }
3328 };
3329
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003330 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003331 showEntitlementUi);
3332 }
3333
3334 /**
3335 * Report network connectivity status. This is currently used only
3336 * to alter status bar UI.
3337 * <p>This method requires the caller to hold the permission
3338 * {@link android.Manifest.permission#STATUS_BAR}.
3339 *
3340 * @param networkType The type of network you want to report on
3341 * @param percentage The quality of the connection 0 is bad, 100 is good
3342 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3343 * {@hide}
3344 */
3345 public void reportInetCondition(int networkType, int percentage) {
3346 printStackTrace();
3347 try {
3348 mService.reportInetCondition(networkType, percentage);
3349 } catch (RemoteException e) {
3350 throw e.rethrowFromSystemServer();
3351 }
3352 }
3353
3354 /**
3355 * Report a problem network to the framework. This provides a hint to the system
3356 * that there might be connectivity problems on this network and may cause
3357 * the framework to re-evaluate network connectivity and/or switch to another
3358 * network.
3359 *
3360 * @param network The {@link Network} the application was attempting to use
3361 * or {@code null} to indicate the current default network.
3362 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3363 * working and non-working connectivity.
3364 */
3365 @Deprecated
3366 public void reportBadNetwork(@Nullable Network network) {
3367 printStackTrace();
3368 try {
3369 // One of these will be ignored because it matches system's current state.
3370 // The other will trigger the necessary reevaluation.
3371 mService.reportNetworkConnectivity(network, true);
3372 mService.reportNetworkConnectivity(network, false);
3373 } catch (RemoteException e) {
3374 throw e.rethrowFromSystemServer();
3375 }
3376 }
3377
3378 /**
3379 * Report to the framework whether a network has working connectivity.
3380 * This provides a hint to the system that a particular network is providing
3381 * working connectivity or not. In response the framework may re-evaluate
3382 * the network's connectivity and might take further action thereafter.
3383 *
3384 * @param network The {@link Network} the application was attempting to use
3385 * or {@code null} to indicate the current default network.
3386 * @param hasConnectivity {@code true} if the application was able to successfully access the
3387 * Internet using {@code network} or {@code false} if not.
3388 */
3389 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3390 printStackTrace();
3391 try {
3392 mService.reportNetworkConnectivity(network, hasConnectivity);
3393 } catch (RemoteException e) {
3394 throw e.rethrowFromSystemServer();
3395 }
3396 }
3397
3398 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003399 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003400 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003401 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3402 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3403 * accessing any network, regardless of what the settings for that network are.
3404 *
3405 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3406 * proxy is likely to break networking on multiple networks. This method is only meant
3407 * for device policy clients looking to do general internal filtering or similar use cases.
3408 *
chiachangwang9473c592022-07-15 02:25:52 +00003409 * @see #getGlobalProxy
3410 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003411 *
3412 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3413 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003414 * @hide
3415 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003416 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003417 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003418 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003419 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003420 try {
3421 mService.setGlobalProxy(p);
3422 } catch (RemoteException e) {
3423 throw e.rethrowFromSystemServer();
3424 }
3425 }
3426
3427 /**
3428 * Retrieve any network-independent global HTTP proxy.
3429 *
3430 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3431 * if no global HTTP proxy is set.
3432 * @hide
3433 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003434 @SystemApi(client = MODULE_LIBRARIES)
3435 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003436 public ProxyInfo getGlobalProxy() {
3437 try {
3438 return mService.getGlobalProxy();
3439 } catch (RemoteException e) {
3440 throw e.rethrowFromSystemServer();
3441 }
3442 }
3443
3444 /**
3445 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3446 * network-specific HTTP proxy. If {@code network} is null, the
3447 * network-specific proxy returned is the proxy of the default active
3448 * network.
3449 *
3450 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3451 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3452 * or when {@code network} is {@code null},
3453 * the {@code ProxyInfo} for the default active network. Returns
3454 * {@code null} when no proxy applies or the caller doesn't have
3455 * permission to use {@code network}.
3456 * @hide
3457 */
3458 public ProxyInfo getProxyForNetwork(Network network) {
3459 try {
3460 return mService.getProxyForNetwork(network);
3461 } catch (RemoteException e) {
3462 throw e.rethrowFromSystemServer();
3463 }
3464 }
3465
3466 /**
3467 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3468 * otherwise if this process is bound to a {@link Network} using
3469 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3470 * the default network's proxy is returned.
3471 *
3472 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3473 * HTTP proxy is active.
3474 */
3475 @Nullable
3476 public ProxyInfo getDefaultProxy() {
3477 return getProxyForNetwork(getBoundNetworkForProcess());
3478 }
3479
3480 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003481 * Returns whether the hardware supports the given network type.
3482 *
3483 * This doesn't indicate there is coverage or such a network is available, just whether the
3484 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3485 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003486 *
3487 * @param networkType The network type we'd like to check
3488 * @return {@code true} if supported, else {@code false}
3489 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3490 * @hide
3491 */
3492 @Deprecated
3493 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3494 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3495 public boolean isNetworkSupported(int networkType) {
3496 try {
3497 return mService.isNetworkSupported(networkType);
3498 } catch (RemoteException e) {
3499 throw e.rethrowFromSystemServer();
3500 }
3501 }
3502
3503 /**
3504 * Returns if the currently active data network is metered. A network is
3505 * classified as metered when the user is sensitive to heavy data usage on
3506 * that connection due to monetary costs, data limitations or
3507 * battery/performance issues. You should check this before doing large
3508 * data transfers, and warn the user or delay the operation until another
3509 * network is available.
3510 *
3511 * @return {@code true} if large transfers should be avoided, otherwise
3512 * {@code false}.
3513 */
3514 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3515 public boolean isActiveNetworkMetered() {
3516 try {
3517 return mService.isActiveNetworkMetered();
3518 } catch (RemoteException e) {
3519 throw e.rethrowFromSystemServer();
3520 }
3521 }
3522
3523 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003524 * Set sign in error notification to visible or invisible
3525 *
3526 * @hide
3527 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3528 */
3529 @Deprecated
3530 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3531 String action) {
3532 try {
3533 mService.setProvisioningNotificationVisible(visible, networkType, action);
3534 } catch (RemoteException e) {
3535 throw e.rethrowFromSystemServer();
3536 }
3537 }
3538
3539 /**
3540 * Set the value for enabling/disabling airplane mode
3541 *
3542 * @param enable whether to enable airplane mode or not
3543 *
3544 * @hide
3545 */
3546 @RequiresPermission(anyOf = {
3547 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3548 android.Manifest.permission.NETWORK_SETTINGS,
3549 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3550 android.Manifest.permission.NETWORK_STACK})
3551 @SystemApi
3552 public void setAirplaneMode(boolean enable) {
3553 try {
3554 mService.setAirplaneMode(enable);
3555 } catch (RemoteException e) {
3556 throw e.rethrowFromSystemServer();
3557 }
3558 }
3559
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003560 /**
3561 * Registers the specified {@link NetworkProvider}.
3562 * Each listener must only be registered once. The listener can be unregistered with
3563 * {@link #unregisterNetworkProvider}.
3564 *
3565 * @param provider the provider to register
3566 * @return the ID of the provider. This ID must be used by the provider when registering
3567 * {@link android.net.NetworkAgent}s.
3568 * @hide
3569 */
3570 @SystemApi
3571 @RequiresPermission(anyOf = {
3572 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3573 android.Manifest.permission.NETWORK_FACTORY})
3574 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3575 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3576 throw new IllegalStateException("NetworkProviders can only be registered once");
3577 }
3578
3579 try {
3580 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3581 provider.getName());
3582 provider.setProviderId(providerId);
3583 } catch (RemoteException e) {
3584 throw e.rethrowFromSystemServer();
3585 }
3586 return provider.getProviderId();
3587 }
3588
3589 /**
3590 * Unregisters the specified NetworkProvider.
3591 *
3592 * @param provider the provider to unregister
3593 * @hide
3594 */
3595 @SystemApi
3596 @RequiresPermission(anyOf = {
3597 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3598 android.Manifest.permission.NETWORK_FACTORY})
3599 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3600 try {
3601 mService.unregisterNetworkProvider(provider.getMessenger());
3602 } catch (RemoteException e) {
3603 throw e.rethrowFromSystemServer();
3604 }
3605 provider.setProviderId(NetworkProvider.ID_NONE);
3606 }
3607
Chalard Jeand1b498b2021-01-05 08:40:09 +09003608 /**
3609 * Register or update a network offer with ConnectivityService.
3610 *
3611 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003612 * them to networking requests made by apps or the system. A callback identifies an offer
3613 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3614 * score and the capabilities of the network it might be able to bring up ; these act as
3615 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003616 * provider.
3617 *
3618 * The provider is under no obligation to be able to bring up the network it offers at any
3619 * given time. Instead, this mechanism is meant to limit requests received by providers
3620 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3621 * the quality of the network satisfying a given request to their own offer.
3622 *
3623 * An offer can be updated by calling this again with the same callback object. This is
3624 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3625 * provider with the changes caused by the changes in the offer.
3626 *
3627 * @param provider The provider making this offer.
3628 * @param score The prospective score of the network.
3629 * @param caps The prospective capabilities of the network.
3630 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003631 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003632 */
3633 @RequiresPermission(anyOf = {
3634 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3635 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003636 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003637 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3638 @NonNull final INetworkOfferCallback callback) {
3639 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003640 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003641 Objects.requireNonNull(score, "null score"),
3642 Objects.requireNonNull(caps, "null caps"),
3643 Objects.requireNonNull(callback, "null callback"));
3644 } catch (RemoteException e) {
3645 throw e.rethrowFromSystemServer();
3646 }
3647 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003648
Chalard Jeand1b498b2021-01-05 08:40:09 +09003649 /**
3650 * Withdraw a network offer made with {@link #offerNetwork}.
3651 *
3652 * @param callback The callback passed at registration time. This must be the same object
3653 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003654 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003655 */
3656 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3657 try {
3658 mService.unofferNetwork(Objects.requireNonNull(callback));
3659 } catch (RemoteException e) {
3660 throw e.rethrowFromSystemServer();
3661 }
3662 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003663 /** @hide exposed via the NetworkProvider class. */
3664 @RequiresPermission(anyOf = {
3665 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3666 android.Manifest.permission.NETWORK_FACTORY})
3667 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3668 try {
3669 mService.declareNetworkRequestUnfulfillable(request);
3670 } catch (RemoteException e) {
3671 throw e.rethrowFromSystemServer();
3672 }
3673 }
3674
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003675 /**
3676 * @hide
3677 * Register a NetworkAgent with ConnectivityService.
3678 * @return Network corresponding to NetworkAgent.
3679 */
3680 @RequiresPermission(anyOf = {
3681 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3682 android.Manifest.permission.NETWORK_FACTORY})
3683 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003684 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3685 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003686 try {
3687 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3688 } catch (RemoteException e) {
3689 throw e.rethrowFromSystemServer();
3690 }
3691 }
3692
3693 /**
3694 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3695 * changes. Should be extended by applications wanting notifications.
3696 *
3697 * A {@code NetworkCallback} is registered by calling
3698 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3699 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3700 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3701 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3702 * A {@code NetworkCallback} should be registered at most once at any time.
3703 * A {@code NetworkCallback} that has been unregistered can be registered again.
3704 */
3705 public static class NetworkCallback {
3706 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003707 * No flags associated with this callback.
3708 * @hide
3709 */
3710 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003711
Roshan Piuse08bc182020-12-22 15:10:42 -08003712 /**
lucaslinc582d502022-01-27 09:07:00 +08003713 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3714 *
3715 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3716 * Prior to Android 12, this information is always returned to apps holding the appropriate
3717 * permission, possibly noting that the app has used location.
3718 * <p>In Android 12 and above, by default the sent objects do not contain any location
3719 * information, even if the app holds the necessary permissions, and the system does not
3720 * take note of location usage by the app. Apps can request that location information is
3721 * included, in which case the system will check location permission and the location
3722 * toggle state, and take note of location usage by the app if any such information is
3723 * returned.
3724 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003725 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3726 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3727 * <p>
3728 * These include:
3729 * <li> Some transport info instances (retrieved via
3730 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3731 * contain location sensitive information.
3732 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003733 * sensitive for wifi suggestor apps (i.e using
3734 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003735 * </p>
3736 * <p>
3737 * Note:
3738 * <li> Retrieving this location sensitive information (subject to app's location
3739 * permissions) will be noted by system. </li>
3740 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003741 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003742 */
Roshan Pius189d0092021-03-11 21:16:44 -08003743 // Note: Some existing fields which are location sensitive may still be included without
3744 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003745 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3746
3747 /** @hide */
3748 @Retention(RetentionPolicy.SOURCE)
3749 @IntDef(flag = true, prefix = "FLAG_", value = {
3750 FLAG_NONE,
3751 FLAG_INCLUDE_LOCATION_INFO
3752 })
3753 public @interface Flag { }
3754
3755 /**
3756 * All the valid flags for error checking.
3757 */
3758 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3759
3760 public NetworkCallback() {
3761 this(FLAG_NONE);
3762 }
3763
3764 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003765 if ((flags & VALID_FLAGS) != flags) {
3766 throw new IllegalArgumentException("Invalid flags");
3767 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003768 mFlags = flags;
3769 }
3770
3771 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003772 * Called when the framework connects to a new network to evaluate whether it satisfies this
3773 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3774 * callback. There is no guarantee that this new network will satisfy any requests, or that
3775 * the network will stay connected for longer than the time necessary to evaluate it.
3776 * <p>
3777 * Most applications <b>should not</b> act on this callback, and should instead use
3778 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3779 * the framework in properly evaluating the network &mdash; for example, an application that
3780 * can automatically log in to a captive portal without user intervention.
3781 *
3782 * @param network The {@link Network} of the network that is being evaluated.
3783 *
3784 * @hide
3785 */
3786 public void onPreCheck(@NonNull Network network) {}
3787
3788 /**
3789 * Called when the framework connects and has declared a new network ready for use.
3790 * This callback may be called more than once if the {@link Network} that is
3791 * satisfying the request changes.
3792 *
3793 * @param network The {@link Network} of the satisfying network.
3794 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3795 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3796 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3797 * @hide
3798 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003799 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003800 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003801 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003802 // Internally only this method is called when a new network is available, and
3803 // it calls the callback in the same way and order that older versions used
3804 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003805 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3806 onBlockedStatusChanged(network, blocked);
3807 }
3808
3809 /**
3810 * Legacy variant of onAvailable that takes a boolean blocked reason.
3811 *
3812 * This method has never been public API, but it's not final, so there may be apps that
3813 * implemented it and rely on it being called. Do our best not to break them.
3814 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3815 * this method is called. There does not seem to be a way to avoid this.
3816 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3817 *
3818 * @hide
3819 */
3820 public void onAvailable(@NonNull Network network,
3821 @NonNull NetworkCapabilities networkCapabilities,
3822 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003823 onAvailable(network);
3824 if (!networkCapabilities.hasCapability(
3825 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3826 onNetworkSuspended(network);
3827 }
3828 onCapabilitiesChanged(network, networkCapabilities);
3829 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003830 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003831 }
3832
3833 /**
3834 * Called when the framework connects and has declared a new network ready for use.
3835 *
3836 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3837 * be available at the same time, and onAvailable will be called for each of these as they
3838 * appear.
3839 *
3840 * <p>For callbacks registered with {@link #requestNetwork} and
3841 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3842 * is the new best network for this request and is now tracked by this callback ; this
3843 * callback will no longer receive method calls about other networks that may have been
3844 * passed to this method previously. The previously-best network may have disconnected, or
3845 * it may still be around and the newly-best network may simply be better.
3846 *
3847 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3848 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3849 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3850 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3851 *
3852 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3853 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3854 * this callback as this is prone to race conditions (there is no guarantee the objects
3855 * returned by these methods will be current). Instead, wait for a call to
3856 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3857 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3858 * to be well-ordered with respect to other callbacks.
3859 *
3860 * @param network The {@link Network} of the satisfying network.
3861 */
3862 public void onAvailable(@NonNull Network network) {}
3863
3864 /**
3865 * Called when the network is about to be lost, typically because there are no outstanding
3866 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3867 * with the new replacement network for graceful handover. This method is not guaranteed
3868 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3869 * network is suddenly disconnected.
3870 *
3871 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3872 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3873 * this callback as this is prone to race conditions ; calling these methods while in a
3874 * callback may return an outdated or even a null object.
3875 *
3876 * @param network The {@link Network} that is about to be lost.
3877 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3878 * connected for graceful handover; note that the network may still
3879 * suffer a hard loss at any time.
3880 */
3881 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3882
3883 /**
3884 * Called when a network disconnects or otherwise no longer satisfies this request or
3885 * callback.
3886 *
3887 * <p>If the callback was registered with requestNetwork() or
3888 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3889 * returned by onAvailable() when that network is lost and no other network satisfies
3890 * the criteria of the request.
3891 *
3892 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3893 * each network which no longer satisfies the criteria of the callback.
3894 *
3895 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3896 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3897 * this callback as this is prone to race conditions ; calling these methods while in a
3898 * callback may return an outdated or even a null object.
3899 *
3900 * @param network The {@link Network} lost.
3901 */
3902 public void onLost(@NonNull Network network) {}
3903
3904 /**
3905 * Called if no network is found within the timeout time specified in
3906 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3907 * requested network request cannot be fulfilled (whether or not a timeout was
3908 * specified). When this callback is invoked the associated
3909 * {@link NetworkRequest} will have already been removed and released, as if
3910 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3911 */
3912 public void onUnavailable() {}
3913
3914 /**
3915 * Called when the network corresponding to this request changes capabilities but still
3916 * satisfies the requested criteria.
3917 *
3918 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3919 * to be called immediately after {@link #onAvailable}.
3920 *
3921 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3922 * ConnectivityManager methods in this callback as this is prone to race conditions :
3923 * calling these methods while in a callback may return an outdated or even a null object.
3924 *
3925 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003926 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003927 * network.
3928 */
3929 public void onCapabilitiesChanged(@NonNull Network network,
3930 @NonNull NetworkCapabilities networkCapabilities) {}
3931
3932 /**
3933 * Called when the network corresponding to this request changes {@link LinkProperties}.
3934 *
3935 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3936 * to be called immediately after {@link #onAvailable}.
3937 *
3938 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3939 * ConnectivityManager methods in this callback as this is prone to race conditions :
3940 * calling these methods while in a callback may return an outdated or even a null object.
3941 *
3942 * @param network The {@link Network} whose link properties have changed.
3943 * @param linkProperties The new {@link LinkProperties} for this network.
3944 */
3945 public void onLinkPropertiesChanged(@NonNull Network network,
3946 @NonNull LinkProperties linkProperties) {}
3947
3948 /**
3949 * Called when the network the framework connected to for this request suspends data
3950 * transmission temporarily.
3951 *
3952 * <p>This generally means that while the TCP connections are still live temporarily
3953 * network data fails to transfer. To give a specific example, this is used on cellular
3954 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3955 * means read operations on sockets on this network will block once the buffers are
3956 * drained, and write operations will block once the buffers are full.
3957 *
3958 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3959 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3960 * this callback as this is prone to race conditions (there is no guarantee the objects
3961 * returned by these methods will be current).
3962 *
3963 * @hide
3964 */
3965 public void onNetworkSuspended(@NonNull Network network) {}
3966
3967 /**
3968 * Called when the network the framework connected to for this request
3969 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3970 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3971
3972 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3973 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3974 * this callback as this is prone to race conditions : calling these methods while in a
3975 * callback may return an outdated or even a null object.
3976 *
3977 * @hide
3978 */
3979 public void onNetworkResumed(@NonNull Network network) {}
3980
3981 /**
3982 * Called when access to the specified network is blocked or unblocked.
3983 *
3984 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3985 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3986 * this callback as this is prone to race conditions : calling these methods while in a
3987 * callback may return an outdated or even a null object.
3988 *
3989 * @param network The {@link Network} whose blocked status has changed.
3990 * @param blocked The blocked status of this {@link Network}.
3991 */
3992 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3993
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003994 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09003995 * Called when access to the specified network is blocked or unblocked, or the reason for
3996 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003997 *
3998 * If a NetworkCallback object implements this method,
3999 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4000 *
4001 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4002 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4003 * this callback as this is prone to race conditions : calling these methods while in a
4004 * callback may return an outdated or even a null object.
4005 *
4006 * @param network The {@link Network} whose blocked status has changed.
4007 * @param blocked The blocked status of this {@link Network}.
4008 * @hide
4009 */
4010 @SystemApi(client = MODULE_LIBRARIES)
4011 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4012 onBlockedStatusChanged(network, blocked != 0);
4013 }
4014
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004015 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004016 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004017 }
4018
4019 /**
4020 * Constant error codes used by ConnectivityService to communicate about failures and errors
4021 * across a Binder boundary.
4022 * @hide
4023 */
4024 public interface Errors {
4025 int TOO_MANY_REQUESTS = 1;
4026 }
4027
4028 /** @hide */
4029 public static class TooManyRequestsException extends RuntimeException {}
4030
4031 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4032 switch (e.errorCode) {
4033 case Errors.TOO_MANY_REQUESTS:
4034 return new TooManyRequestsException();
4035 default:
4036 Log.w(TAG, "Unknown service error code " + e.errorCode);
4037 return new RuntimeException(e);
4038 }
4039 }
4040
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004041 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004042 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004043 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004044 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004045 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004046 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004047 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004048 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004049 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004050 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004051 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004052 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004053 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004054 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004055 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004056 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004057 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004058 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004059 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004060 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004061 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004062 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004063
4064 /** @hide */
4065 public static String getCallbackName(int whichCallback) {
4066 switch (whichCallback) {
4067 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4068 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4069 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4070 case CALLBACK_LOST: return "CALLBACK_LOST";
4071 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4072 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4073 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4074 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4075 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4076 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4077 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4078 default:
4079 return Integer.toString(whichCallback);
4080 }
4081 }
4082
zhujiatai79b0de92022-09-22 15:44:02 +08004083 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004084 private static final String TAG = "ConnectivityManager.CallbackHandler";
4085 private static final boolean DBG = false;
4086
4087 CallbackHandler(Looper looper) {
4088 super(looper);
4089 }
4090
4091 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004092 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004093 }
4094
4095 @Override
4096 public void handleMessage(Message message) {
4097 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004098 // the sInstance can't be null because to send this message a ConnectivityManager
4099 // instance must have been created prior to creating the thread on which this
4100 // Handler is running.
4101 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004102 return;
4103 }
4104
4105 final NetworkRequest request = getObject(message, NetworkRequest.class);
4106 final Network network = getObject(message, Network.class);
4107 final NetworkCallback callback;
4108 synchronized (sCallbacks) {
4109 callback = sCallbacks.get(request);
4110 if (callback == null) {
4111 Log.w(TAG,
4112 "callback not found for " + getCallbackName(message.what) + " message");
4113 return;
4114 }
4115 if (message.what == CALLBACK_UNAVAIL) {
4116 sCallbacks.remove(request);
4117 callback.networkRequest = ALREADY_UNREGISTERED;
4118 }
4119 }
4120 if (DBG) {
4121 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4122 }
4123
4124 switch (message.what) {
4125 case CALLBACK_PRECHECK: {
4126 callback.onPreCheck(network);
4127 break;
4128 }
4129 case CALLBACK_AVAILABLE: {
4130 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4131 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004132 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004133 break;
4134 }
4135 case CALLBACK_LOSING: {
4136 callback.onLosing(network, message.arg1);
4137 break;
4138 }
4139 case CALLBACK_LOST: {
4140 callback.onLost(network);
4141 break;
4142 }
4143 case CALLBACK_UNAVAIL: {
4144 callback.onUnavailable();
4145 break;
4146 }
4147 case CALLBACK_CAP_CHANGED: {
4148 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4149 callback.onCapabilitiesChanged(network, cap);
4150 break;
4151 }
4152 case CALLBACK_IP_CHANGED: {
4153 LinkProperties lp = getObject(message, LinkProperties.class);
4154 callback.onLinkPropertiesChanged(network, lp);
4155 break;
4156 }
4157 case CALLBACK_SUSPENDED: {
4158 callback.onNetworkSuspended(network);
4159 break;
4160 }
4161 case CALLBACK_RESUMED: {
4162 callback.onNetworkResumed(network);
4163 break;
4164 }
4165 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004166 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004167 }
4168 }
4169 }
4170
4171 private <T> T getObject(Message msg, Class<T> c) {
4172 return (T) msg.getData().getParcelable(c.getSimpleName());
4173 }
4174 }
4175
4176 private CallbackHandler getDefaultHandler() {
4177 synchronized (sCallbacks) {
4178 if (sCallbackHandler == null) {
4179 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4180 }
4181 return sCallbackHandler;
4182 }
4183 }
4184
4185 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4186 private static CallbackHandler sCallbackHandler;
4187
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004188 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4189 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4190 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004191 printStackTrace();
4192 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004193 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4194 throw new IllegalArgumentException("null NetworkCapabilities");
4195 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004196 final NetworkRequest request;
4197 final String callingPackageName = mContext.getOpPackageName();
4198 try {
4199 synchronized(sCallbacks) {
4200 if (callback.networkRequest != null
4201 && callback.networkRequest != ALREADY_UNREGISTERED) {
4202 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4203 // and requests (http://b/20701525).
4204 Log.e(TAG, "NetworkCallback was already registered");
4205 }
4206 Messenger messenger = new Messenger(handler);
4207 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004208 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004209 if (reqType == LISTEN) {
4210 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004211 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004212 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004213 } else {
4214 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004215 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4216 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004217 }
4218 if (request != null) {
4219 sCallbacks.put(request, callback);
4220 }
4221 callback.networkRequest = request;
4222 }
4223 } catch (RemoteException e) {
4224 throw e.rethrowFromSystemServer();
4225 } catch (ServiceSpecificException e) {
4226 throw convertServiceException(e);
4227 }
4228 return request;
4229 }
4230
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004231 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4232 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4233 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4234 legacyType, handler);
4235 }
4236
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004237 /**
4238 * Helper function to request a network with a particular legacy type.
4239 *
4240 * This API is only for use in internal system code that requests networks with legacy type and
4241 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4242 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4243 *
4244 * @param request {@link NetworkRequest} describing this request.
4245 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4246 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4247 * be a positive value (i.e. >0).
4248 * @param legacyType to specify the network type(#TYPE_*).
4249 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4250 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4251 * the callback must not be shared - it uniquely specifies this request.
4252 *
4253 * @hide
4254 */
4255 @SystemApi
4256 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4257 public void requestNetwork(@NonNull NetworkRequest request,
4258 int timeoutMs, int legacyType, @NonNull Handler handler,
4259 @NonNull NetworkCallback networkCallback) {
4260 if (legacyType == TYPE_NONE) {
4261 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4262 }
4263 CallbackHandler cbHandler = new CallbackHandler(handler);
4264 NetworkCapabilities nc = request.networkCapabilities;
4265 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4266 }
4267
4268 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004269 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004270 *
4271 * <p>This method will attempt to find the best network that matches the passed
4272 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4273 * criteria. The platform will evaluate which network is the best at its own discretion.
4274 * Throughput, latency, cost per byte, policy, user preference and other considerations
4275 * may be factored in the decision of what is considered the best network.
4276 *
4277 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4278 * matching this request, while always attempting to match the request to a better network if
4279 * possible. If a better match is found, the platform will switch this request to the now-best
4280 * network and inform the app of the newly best network by invoking
4281 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4282 * will not try to maintain any other network than the best one currently matching the request:
4283 * a network not matching any network request may be disconnected at any time.
4284 *
4285 * <p>For example, an application could use this method to obtain a connected cellular network
4286 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4287 * radio to consume additional power. Or, an application could inform the system that it wants
4288 * a network supporting sending MMSes and have the system let it know about the currently best
4289 * MMS-supporting network through the provided {@link NetworkCallback}.
4290 *
4291 * <p>The status of the request can be followed by listening to the various callbacks described
4292 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4293 * used to direct traffic to the network (although accessing some networks may be subject to
4294 * holding specific permissions). Callers will learn about the specific characteristics of the
4295 * network through
4296 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4297 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4298 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4299 * matching the request at any given time; therefore when a better network matching the request
4300 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4301 * with the new network after which no further updates are given about the previously-best
4302 * network, unless it becomes the best again at some later time. All callbacks are invoked
4303 * in order on the same thread, which by default is a thread created by the framework running
4304 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004305 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004306 * callbacks are invoked.
4307 *
4308 * <p>This{@link NetworkRequest} will live until released via
4309 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4310 * which point the system may let go of the network at any time.
4311 *
4312 * <p>A version of this method which takes a timeout is
4313 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4314 * wait for a limited amount of time for the network to become unavailable.
4315 *
4316 * <p>It is presently unsupported to request a network with mutable
4317 * {@link NetworkCapabilities} such as
4318 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4319 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4320 * as these {@code NetworkCapabilities} represent states that a particular
4321 * network may never attain, and whether a network will attain these states
4322 * is unknown prior to bringing up the network so the framework does not
4323 * know how to go about satisfying a request with these capabilities.
4324 *
4325 * <p>This method requires the caller to hold either the
4326 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4327 * or the ability to modify system settings as determined by
4328 * {@link android.provider.Settings.System#canWrite}.</p>
4329 *
4330 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4331 * number of outstanding requests to 100 per app (identified by their UID), shared with
4332 * all variants of this method, of {@link #registerNetworkCallback} as well as
4333 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4334 * Requesting a network with this method will count toward this limit. If this limit is
4335 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4336 * make sure to unregister the callbacks with
4337 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4338 *
4339 * @param request {@link NetworkRequest} describing this request.
4340 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4341 * the callback must not be shared - it uniquely specifies this request.
4342 * The callback is invoked on the default internal Handler.
4343 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4344 * @throws SecurityException if missing the appropriate permissions.
4345 * @throws RuntimeException if the app already has too many callbacks registered.
4346 */
4347 public void requestNetwork(@NonNull NetworkRequest request,
4348 @NonNull NetworkCallback networkCallback) {
4349 requestNetwork(request, networkCallback, getDefaultHandler());
4350 }
4351
4352 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004353 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004354 *
4355 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4356 * but runs all the callbacks on the passed Handler.
4357 *
4358 * <p>This method has the same permission requirements as
4359 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4360 * and throws the same exceptions in the same conditions.
4361 *
4362 * @param request {@link NetworkRequest} describing this request.
4363 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4364 * the callback must not be shared - it uniquely specifies this request.
4365 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4366 */
4367 public void requestNetwork(@NonNull NetworkRequest request,
4368 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4369 CallbackHandler cbHandler = new CallbackHandler(handler);
4370 NetworkCapabilities nc = request.networkCapabilities;
4371 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4372 }
4373
4374 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004375 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004376 * by a timeout.
4377 *
4378 * This function behaves identically to the non-timed-out version
4379 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4380 * is not found within the given time (in milliseconds) the
4381 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4382 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4383 * not have to be released if timed-out (it is automatically released). Unregistering a
4384 * request that timed out is not an error.
4385 *
4386 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4387 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4388 * for that purpose. Calling this method will attempt to bring up the requested network.
4389 *
4390 * <p>This method has the same permission requirements as
4391 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4392 * and throws the same exceptions in the same conditions.
4393 *
4394 * @param request {@link NetworkRequest} describing this request.
4395 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4396 * the callback must not be shared - it uniquely specifies this request.
4397 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4398 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4399 * be a positive value (i.e. >0).
4400 */
4401 public void requestNetwork(@NonNull NetworkRequest request,
4402 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4403 checkTimeout(timeoutMs);
4404 NetworkCapabilities nc = request.networkCapabilities;
4405 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4406 getDefaultHandler());
4407 }
4408
4409 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004410 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004411 * by a timeout.
4412 *
4413 * This method behaves identically to
4414 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4415 * on the passed Handler.
4416 *
4417 * <p>This method has the same permission requirements as
4418 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4419 * and throws the same exceptions in the same conditions.
4420 *
4421 * @param request {@link NetworkRequest} describing this request.
4422 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4423 * the callback must not be shared - it uniquely specifies this request.
4424 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4425 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4426 * before {@link NetworkCallback#onUnavailable} is called.
4427 */
4428 public void requestNetwork(@NonNull NetworkRequest request,
4429 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4430 checkTimeout(timeoutMs);
4431 CallbackHandler cbHandler = new CallbackHandler(handler);
4432 NetworkCapabilities nc = request.networkCapabilities;
4433 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4434 }
4435
4436 /**
4437 * The lookup key for a {@link Network} object included with the intent after
4438 * successfully finding a network for the applications request. Retrieve it with
4439 * {@link android.content.Intent#getParcelableExtra(String)}.
4440 * <p>
4441 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4442 * then you must get a ConnectivityManager instance before doing so.
4443 */
4444 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4445
4446 /**
4447 * The lookup key for a {@link NetworkRequest} object included with the intent after
4448 * successfully finding a network for the applications request. Retrieve it with
4449 * {@link android.content.Intent#getParcelableExtra(String)}.
4450 */
4451 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4452
4453
4454 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004455 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004456 *
4457 * This function behaves identically to the version that takes a NetworkCallback, but instead
4458 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4459 * the request may outlive the calling application and get called back when a suitable
4460 * network is found.
4461 * <p>
4462 * The operation is an Intent broadcast that goes to a broadcast receiver that
4463 * you registered with {@link Context#registerReceiver} or through the
4464 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4465 * <p>
4466 * The operation Intent is delivered with two extras, a {@link Network} typed
4467 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4468 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4469 * the original requests parameters. It is important to create a new,
4470 * {@link NetworkCallback} based request before completing the processing of the
4471 * Intent to reserve the network or it will be released shortly after the Intent
4472 * is processed.
4473 * <p>
4474 * If there is already a request for this Intent registered (with the equality of
4475 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4476 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4477 * <p>
4478 * The request may be released normally by calling
4479 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4480 * <p>It is presently unsupported to request a network with either
4481 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4482 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4483 * as these {@code NetworkCapabilities} represent states that a particular
4484 * network may never attain, and whether a network will attain these states
4485 * is unknown prior to bringing up the network so the framework does not
4486 * know how to go about satisfying a request with these capabilities.
4487 *
4488 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4489 * number of outstanding requests to 100 per app (identified by their UID), shared with
4490 * all variants of this method, of {@link #registerNetworkCallback} as well as
4491 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4492 * Requesting a network with this method will count toward this limit. If this limit is
4493 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4494 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4495 * or {@link #releaseNetworkRequest(PendingIntent)}.
4496 *
4497 * <p>This method requires the caller to hold either the
4498 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4499 * or the ability to modify system settings as determined by
4500 * {@link android.provider.Settings.System#canWrite}.</p>
4501 *
4502 * @param request {@link NetworkRequest} describing this request.
4503 * @param operation Action to perform when the network is available (corresponds
4504 * to the {@link NetworkCallback#onAvailable} call. Typically
4505 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4506 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4507 * @throws SecurityException if missing the appropriate permissions.
4508 * @throws RuntimeException if the app already has too many callbacks registered.
4509 */
4510 public void requestNetwork(@NonNull NetworkRequest request,
4511 @NonNull PendingIntent operation) {
4512 printStackTrace();
4513 checkPendingIntentNotNull(operation);
4514 try {
4515 mService.pendingRequestForNetwork(
4516 request.networkCapabilities, operation, mContext.getOpPackageName(),
4517 getAttributionTag());
4518 } catch (RemoteException e) {
4519 throw e.rethrowFromSystemServer();
4520 } catch (ServiceSpecificException e) {
4521 throw convertServiceException(e);
4522 }
4523 }
4524
4525 /**
4526 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4527 * <p>
4528 * This method has the same behavior as
4529 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4530 * releasing network resources and disconnecting.
4531 *
4532 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4533 * PendingIntent passed to
4534 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4535 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4536 */
4537 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4538 printStackTrace();
4539 checkPendingIntentNotNull(operation);
4540 try {
4541 mService.releasePendingNetworkRequest(operation);
4542 } catch (RemoteException e) {
4543 throw e.rethrowFromSystemServer();
4544 }
4545 }
4546
4547 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004548 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004549 }
4550
4551 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004552 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004553 }
4554
4555 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004556 if (timeoutMs <= 0) {
4557 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4558 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004559 }
4560
4561 /**
4562 * Registers to receive notifications about all networks which satisfy the given
4563 * {@link NetworkRequest}. The callbacks will continue to be called until
4564 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4565 * called.
4566 *
4567 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4568 * number of outstanding requests to 100 per app (identified by their UID), shared with
4569 * all variants of this method, of {@link #requestNetwork} as well as
4570 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4571 * Requesting a network with this method will count toward this limit. If this limit is
4572 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4573 * make sure to unregister the callbacks with
4574 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4575 *
4576 * @param request {@link NetworkRequest} describing this request.
4577 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4578 * networks change state.
4579 * The callback is invoked on the default internal Handler.
4580 * @throws RuntimeException if the app already has too many callbacks registered.
4581 */
4582 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4583 public void registerNetworkCallback(@NonNull NetworkRequest request,
4584 @NonNull NetworkCallback networkCallback) {
4585 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4586 }
4587
4588 /**
4589 * Registers to receive notifications about all networks which satisfy the given
4590 * {@link NetworkRequest}. The callbacks will continue to be called until
4591 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4592 * called.
4593 *
4594 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4595 * number of outstanding requests to 100 per app (identified by their UID), shared with
4596 * all variants of this method, of {@link #requestNetwork} as well as
4597 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4598 * Requesting a network with this method will count toward this limit. If this limit is
4599 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4600 * make sure to unregister the callbacks with
4601 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4602 *
4603 *
4604 * @param request {@link NetworkRequest} describing this request.
4605 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4606 * networks change state.
4607 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4608 * @throws RuntimeException if the app already has too many callbacks registered.
4609 */
4610 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4611 public void registerNetworkCallback(@NonNull NetworkRequest request,
4612 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4613 CallbackHandler cbHandler = new CallbackHandler(handler);
4614 NetworkCapabilities nc = request.networkCapabilities;
4615 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4616 }
4617
4618 /**
4619 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4620 * {@link NetworkRequest}.
4621 *
4622 * This function behaves identically to the version that takes a NetworkCallback, but instead
4623 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4624 * the request may outlive the calling application and get called back when a suitable
4625 * network is found.
4626 * <p>
4627 * The operation is an Intent broadcast that goes to a broadcast receiver that
4628 * you registered with {@link Context#registerReceiver} or through the
4629 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4630 * <p>
4631 * The operation Intent is delivered with two extras, a {@link Network} typed
4632 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4633 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4634 * the original requests parameters.
4635 * <p>
4636 * If there is already a request for this Intent registered (with the equality of
4637 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4638 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4639 * <p>
4640 * The request may be released normally by calling
4641 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4642 *
4643 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4644 * number of outstanding requests to 100 per app (identified by their UID), shared with
4645 * all variants of this method, of {@link #requestNetwork} as well as
4646 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4647 * Requesting a network with this method will count toward this limit. If this limit is
4648 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4649 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4650 * or {@link #releaseNetworkRequest(PendingIntent)}.
4651 *
4652 * @param request {@link NetworkRequest} describing this request.
4653 * @param operation Action to perform when the network is available (corresponds
4654 * to the {@link NetworkCallback#onAvailable} call. Typically
4655 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4656 * @throws RuntimeException if the app already has too many callbacks registered.
4657 */
4658 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4659 public void registerNetworkCallback(@NonNull NetworkRequest request,
4660 @NonNull PendingIntent operation) {
4661 printStackTrace();
4662 checkPendingIntentNotNull(operation);
4663 try {
4664 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004665 request.networkCapabilities, operation, mContext.getOpPackageName(),
4666 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004667 } catch (RemoteException e) {
4668 throw e.rethrowFromSystemServer();
4669 } catch (ServiceSpecificException e) {
4670 throw convertServiceException(e);
4671 }
4672 }
4673
4674 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004675 * Registers to receive notifications about changes in the application's default network. This
4676 * may be a physical network or a virtual network, such as a VPN that applies to the
4677 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004678 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4679 *
4680 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4681 * number of outstanding requests to 100 per app (identified by their UID), shared with
4682 * all variants of this method, of {@link #requestNetwork} as well as
4683 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4684 * Requesting a network with this method will count toward this limit. If this limit is
4685 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4686 * make sure to unregister the callbacks with
4687 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4688 *
4689 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004690 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004691 * The callback is invoked on the default internal Handler.
4692 * @throws RuntimeException if the app already has too many callbacks registered.
4693 */
4694 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4695 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4696 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4697 }
4698
4699 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004700 * Registers to receive notifications about changes in the application's default network. This
4701 * may be a physical network or a virtual network, such as a VPN that applies to the
4702 * application. The callbacks will continue to be called until either the application exits or
4703 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4704 *
4705 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4706 * number of outstanding requests to 100 per app (identified by their UID), shared with
4707 * all variants of this method, of {@link #requestNetwork} as well as
4708 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4709 * Requesting a network with this method will count toward this limit. If this limit is
4710 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4711 * make sure to unregister the callbacks with
4712 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4713 *
4714 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4715 * application's default network changes.
4716 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4717 * @throws RuntimeException if the app already has too many callbacks registered.
4718 */
4719 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4720 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4721 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004722 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004723 }
4724
4725 /**
4726 * Registers to receive notifications about changes in the default network for the specified
4727 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4728 * UID. The callbacks will continue to be called until either the application exits or
4729 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4730 *
4731 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4732 * number of outstanding requests to 100 per app (identified by their UID), shared with
4733 * all variants of this method, of {@link #requestNetwork} as well as
4734 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4735 * Requesting a network with this method will count toward this limit. If this limit is
4736 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4737 * make sure to unregister the callbacks with
4738 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4739 *
4740 * @param uid the UID for which to track default network changes.
4741 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4742 * UID's default network changes.
4743 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4744 * @throws RuntimeException if the app already has too many callbacks registered.
4745 * @hide
4746 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004747 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004748 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4749 @RequiresPermission(anyOf = {
4750 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4751 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004752 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004753 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004754 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004755 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004756 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4757 }
4758
4759 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004760 * Registers to receive notifications about changes in the system default network. The callbacks
4761 * will continue to be called until either the application exits or
4762 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4763 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004764 * This method should not be used to determine networking state seen by applications, because in
4765 * many cases, most or even all application traffic may not use the default network directly,
4766 * and traffic from different applications may go on different networks by default. As an
4767 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4768 * and not onto the system default network. Applications or system components desiring to do
4769 * determine network state as seen by applications should use other methods such as
4770 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4771 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004772 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4773 * number of outstanding requests to 100 per app (identified by their UID), shared with
4774 * all variants of this method, of {@link #requestNetwork} as well as
4775 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4776 * Requesting a network with this method will count toward this limit. If this limit is
4777 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4778 * make sure to unregister the callbacks with
4779 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4780 *
4781 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4782 * system default network changes.
4783 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4784 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004785 *
4786 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004787 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004788 @SystemApi(client = MODULE_LIBRARIES)
4789 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4790 @RequiresPermission(anyOf = {
4791 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004792 android.Manifest.permission.NETWORK_SETTINGS,
4793 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004794 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004795 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004796 CallbackHandler cbHandler = new CallbackHandler(handler);
4797 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004798 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004799 }
4800
4801 /**
junyulaibd123062021-03-15 11:48:48 +08004802 * Registers to receive notifications about the best matching network which satisfy the given
4803 * {@link NetworkRequest}. The callbacks will continue to be called until
4804 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4805 * called.
4806 *
4807 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4808 * number of outstanding requests to 100 per app (identified by their UID), shared with
4809 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4810 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4811 * Requesting a network with this method will count toward this limit. If this limit is
4812 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4813 * make sure to unregister the callbacks with
4814 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4815 *
4816 *
4817 * @param request {@link NetworkRequest} describing this request.
4818 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4819 * networks change state.
4820 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4821 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004822 */
junyulai5a5c99b2021-03-05 15:51:17 +08004823 @SuppressLint("ExecutorRegistration")
4824 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4825 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4826 final NetworkCapabilities nc = request.networkCapabilities;
4827 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004828 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004829 }
4830
4831 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004832 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4833 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4834 * network connection for updated bandwidth information. The caller will be notified via
4835 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4836 * method assumes that the caller has previously called
4837 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4838 * changes.
4839 *
4840 * @param network {@link Network} specifying which network you're interested.
4841 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4842 */
4843 public boolean requestBandwidthUpdate(@NonNull Network network) {
4844 try {
4845 return mService.requestBandwidthUpdate(network);
4846 } catch (RemoteException e) {
4847 throw e.rethrowFromSystemServer();
4848 }
4849 }
4850
4851 /**
4852 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4853 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4854 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09004855 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
4856 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004857 *
4858 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4859 * triggering it as soon as this call returns.
4860 *
4861 * @param networkCallback The {@link NetworkCallback} used when making the request.
4862 */
4863 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4864 printStackTrace();
4865 checkCallbackNotNull(networkCallback);
4866 final List<NetworkRequest> reqs = new ArrayList<>();
4867 // Find all requests associated to this callback and stop callback triggers immediately.
4868 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4869 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004870 if (networkCallback.networkRequest == null) {
4871 throw new IllegalArgumentException("NetworkCallback was not registered");
4872 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004873 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4874 Log.d(TAG, "NetworkCallback was already unregistered");
4875 return;
4876 }
4877 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4878 if (e.getValue() == networkCallback) {
4879 reqs.add(e.getKey());
4880 }
4881 }
4882 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4883 for (NetworkRequest r : reqs) {
4884 try {
4885 mService.releaseNetworkRequest(r);
4886 } catch (RemoteException e) {
4887 throw e.rethrowFromSystemServer();
4888 }
4889 // Only remove mapping if rpc was successful.
4890 sCallbacks.remove(r);
4891 }
4892 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4893 }
4894 }
4895
4896 /**
4897 * Unregisters a callback previously registered via
4898 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4899 *
4900 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4901 * PendingIntent passed to
4902 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4903 * Cannot be null.
4904 */
4905 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4906 releaseNetworkRequest(operation);
4907 }
4908
4909 /**
4910 * Informs the system whether it should switch to {@code network} regardless of whether it is
4911 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4912 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4913 * the system default network regardless of any other network that's currently connected. If
4914 * {@code always} is true, then the choice is remembered, so that the next time the user
4915 * connects to this network, the system will switch to it.
4916 *
4917 * @param network The network to accept.
4918 * @param accept Whether to accept the network even if unvalidated.
4919 * @param always Whether to remember this choice in the future.
4920 *
4921 * @hide
4922 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004923 @SystemApi(client = MODULE_LIBRARIES)
4924 @RequiresPermission(anyOf = {
4925 android.Manifest.permission.NETWORK_SETTINGS,
4926 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4927 android.Manifest.permission.NETWORK_STACK,
4928 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4929 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004930 try {
4931 mService.setAcceptUnvalidated(network, accept, always);
4932 } catch (RemoteException e) {
4933 throw e.rethrowFromSystemServer();
4934 }
4935 }
4936
4937 /**
4938 * Informs the system whether it should consider the network as validated even if it only has
4939 * partial connectivity. If {@code accept} is true, then the network will be considered as
4940 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4941 * is remembered, so that the next time the user connects to this network, the system will
4942 * switch to it.
4943 *
4944 * @param network The network to accept.
4945 * @param accept Whether to consider the network as validated even if it has partial
4946 * connectivity.
4947 * @param always Whether to remember this choice in the future.
4948 *
4949 * @hide
4950 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004951 @SystemApi(client = MODULE_LIBRARIES)
4952 @RequiresPermission(anyOf = {
4953 android.Manifest.permission.NETWORK_SETTINGS,
4954 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4955 android.Manifest.permission.NETWORK_STACK,
4956 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4957 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4958 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004959 try {
4960 mService.setAcceptPartialConnectivity(network, accept, always);
4961 } catch (RemoteException e) {
4962 throw e.rethrowFromSystemServer();
4963 }
4964 }
4965
4966 /**
4967 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4968 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4969 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4970 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4971 *
4972 * @param network The network to accept.
4973 *
4974 * @hide
4975 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004976 @SystemApi(client = MODULE_LIBRARIES)
4977 @RequiresPermission(anyOf = {
4978 android.Manifest.permission.NETWORK_SETTINGS,
4979 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4980 android.Manifest.permission.NETWORK_STACK,
4981 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4982 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004983 try {
4984 mService.setAvoidUnvalidated(network);
4985 } catch (RemoteException e) {
4986 throw e.rethrowFromSystemServer();
4987 }
4988 }
4989
4990 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09004991 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004992 *
4993 * @param timeMs The expired current time. The value should be set within a limited time from
4994 * now.
4995 *
4996 * @hide
4997 */
4998 public void setTestAllowBadWifiUntil(long timeMs) {
4999 try {
5000 mService.setTestAllowBadWifiUntil(timeMs);
5001 } catch (RemoteException e) {
5002 throw e.rethrowFromSystemServer();
5003 }
5004 }
5005
5006 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005007 * Requests that the system open the captive portal app on the specified network.
5008 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005009 * <p>This is to be used on networks where a captive portal was detected, as per
5010 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5011 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005012 * @param network The network to log into.
5013 *
5014 * @hide
5015 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005016 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5017 @RequiresPermission(anyOf = {
5018 android.Manifest.permission.NETWORK_SETTINGS,
5019 android.Manifest.permission.NETWORK_STACK,
5020 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5021 })
5022 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005023 try {
5024 mService.startCaptivePortalApp(network);
5025 } catch (RemoteException e) {
5026 throw e.rethrowFromSystemServer();
5027 }
5028 }
5029
5030 /**
5031 * Requests that the system open the captive portal app with the specified extras.
5032 *
5033 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5034 * corresponding permission.
5035 * @param network Network on which the captive portal was detected.
5036 * @param appExtras Extras to include in the app start intent.
5037 * @hide
5038 */
5039 @SystemApi
5040 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5041 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5042 try {
5043 mService.startCaptivePortalAppInternal(network, appExtras);
5044 } catch (RemoteException e) {
5045 throw e.rethrowFromSystemServer();
5046 }
5047 }
5048
5049 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005050 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005051 * @hide
5052 */
5053 @SystemApi
5054 @RequiresPermission(anyOf = {
5055 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5056 android.Manifest.permission.NETWORK_STACK})
5057 public boolean shouldAvoidBadWifi() {
5058 try {
5059 return mService.shouldAvoidBadWifi();
5060 } catch (RemoteException e) {
5061 throw e.rethrowFromSystemServer();
5062 }
5063 }
5064
5065 /**
5066 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5067 * time-sensitive user-facing operations when the system default network is temporarily
5068 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5069 * this method), and the operation should be infrequent to ensure that data usage is limited.
5070 *
5071 * An example of such an operation might be a time-sensitive foreground activity, such as a
5072 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5073 */
5074 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5075
5076 /**
5077 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5078 * a backup channel for traffic that is primarily going over another network.
5079 *
5080 * An example might be maintaining backup connections to peers or servers for the purpose of
5081 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5082 * on backup paths should be negligible compared to the traffic on the main path.
5083 */
5084 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5085
5086 /**
5087 * It is acceptable to use metered data to improve network latency and performance.
5088 */
5089 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5090
5091 /**
5092 * Return value to use for unmetered networks. On such networks we currently set all the flags
5093 * to true.
5094 * @hide
5095 */
5096 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5097 MULTIPATH_PREFERENCE_HANDOVER |
5098 MULTIPATH_PREFERENCE_RELIABILITY |
5099 MULTIPATH_PREFERENCE_PERFORMANCE;
5100
Aaron Huangcff22942021-05-27 16:31:26 +08005101 /** @hide */
5102 @Retention(RetentionPolicy.SOURCE)
5103 @IntDef(flag = true, value = {
5104 MULTIPATH_PREFERENCE_HANDOVER,
5105 MULTIPATH_PREFERENCE_RELIABILITY,
5106 MULTIPATH_PREFERENCE_PERFORMANCE,
5107 })
5108 public @interface MultipathPreference {
5109 }
5110
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005111 /**
5112 * Provides a hint to the calling application on whether it is desirable to use the
5113 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5114 * for multipath data transfer on this network when it is not the system default network.
5115 * Applications desiring to use multipath network protocols should call this method before
5116 * each such operation.
5117 *
5118 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005119 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005120 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005121 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005122 */
5123 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5124 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5125 try {
5126 return mService.getMultipathPreference(network);
5127 } catch (RemoteException e) {
5128 throw e.rethrowFromSystemServer();
5129 }
5130 }
5131
5132 /**
5133 * Resets all connectivity manager settings back to factory defaults.
5134 * @hide
5135 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005136 @SystemApi(client = MODULE_LIBRARIES)
5137 @RequiresPermission(anyOf = {
5138 android.Manifest.permission.NETWORK_SETTINGS,
5139 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005140 public void factoryReset() {
5141 try {
5142 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005143 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005144 } catch (RemoteException e) {
5145 throw e.rethrowFromSystemServer();
5146 }
5147 }
5148
5149 /**
5150 * Binds the current process to {@code network}. All Sockets created in the future
5151 * (and not explicitly bound via a bound SocketFactory from
5152 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5153 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5154 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5155 * work and all host name resolutions will fail. This is by design so an application doesn't
5156 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5157 * To clear binding pass {@code null} for {@code network}. Using individually bound
5158 * Sockets created by Network.getSocketFactory().createSocket() and
5159 * performing network-specific host name resolutions via
5160 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5161 * {@code bindProcessToNetwork}.
5162 *
5163 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5164 * the current binding.
5165 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5166 */
5167 public boolean bindProcessToNetwork(@Nullable Network network) {
5168 // Forcing callers to call through non-static function ensures ConnectivityManager
5169 // instantiated.
5170 return setProcessDefaultNetwork(network);
5171 }
5172
5173 /**
5174 * Binds the current process to {@code network}. All Sockets created in the future
5175 * (and not explicitly bound via a bound SocketFactory from
5176 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5177 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5178 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5179 * work and all host name resolutions will fail. This is by design so an application doesn't
5180 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5181 * To clear binding pass {@code null} for {@code network}. Using individually bound
5182 * Sockets created by Network.getSocketFactory().createSocket() and
5183 * performing network-specific host name resolutions via
5184 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5185 * {@code setProcessDefaultNetwork}.
5186 *
5187 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5188 * the current binding.
5189 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5190 * @deprecated This function can throw {@link IllegalStateException}. Use
5191 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5192 * is a direct replacement.
5193 */
5194 @Deprecated
5195 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5196 int netId = (network == null) ? NETID_UNSET : network.netId;
5197 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5198
5199 if (netId != NETID_UNSET) {
5200 netId = network.getNetIdForResolv();
5201 }
5202
5203 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5204 return false;
5205 }
5206
5207 if (!isSameNetId) {
5208 // Set HTTP proxy system properties to match network.
5209 // TODO: Deprecate this static method and replace it with a non-static version.
5210 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005211 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005212 } catch (SecurityException e) {
5213 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5214 Log.e(TAG, "Can't set proxy properties", e);
5215 }
5216 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005217 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005218 // Must flush socket pool as idle sockets will be bound to previous network and may
5219 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005220 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005221 }
5222
5223 return true;
5224 }
5225
5226 /**
5227 * Returns the {@link Network} currently bound to this process via
5228 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5229 *
5230 * @return {@code Network} to which this process is bound, or {@code null}.
5231 */
5232 @Nullable
5233 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005234 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005235 // instantiated.
5236 return getProcessDefaultNetwork();
5237 }
5238
5239 /**
5240 * Returns the {@link Network} currently bound to this process via
5241 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5242 *
5243 * @return {@code Network} to which this process is bound, or {@code null}.
5244 * @deprecated Using this function can lead to other functions throwing
5245 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5246 * {@code getBoundNetworkForProcess} is a direct replacement.
5247 */
5248 @Deprecated
5249 @Nullable
5250 public static Network getProcessDefaultNetwork() {
5251 int netId = NetworkUtils.getBoundNetworkForProcess();
5252 if (netId == NETID_UNSET) return null;
5253 return new Network(netId);
5254 }
5255
5256 private void unsupportedStartingFrom(int version) {
5257 if (Process.myUid() == Process.SYSTEM_UID) {
5258 // The getApplicationInfo() call we make below is not supported in system context. Let
5259 // the call through here, and rely on the fact that ConnectivityService will refuse to
5260 // allow the system to use these APIs anyway.
5261 return;
5262 }
5263
5264 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5265 throw new UnsupportedOperationException(
5266 "This method is not supported in target SDK version " + version + " and above");
5267 }
5268 }
5269
5270 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5271 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5272 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5273 // remove these exemptions. Note that this check is not secure, and apps can still access these
5274 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5275 // so is unsupported and may break in the future. http://b/22728205
5276 private void checkLegacyRoutingApiAccess() {
5277 unsupportedStartingFrom(VERSION_CODES.M);
5278 }
5279
5280 /**
5281 * Binds host resolutions performed by this process to {@code network}.
5282 * {@link #bindProcessToNetwork} takes precedence over this setting.
5283 *
5284 * @param network The {@link Network} to bind host resolutions from the current process to, or
5285 * {@code null} to clear the current binding.
5286 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5287 * @hide
5288 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5289 */
5290 @Deprecated
5291 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5292 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5293 return NetworkUtils.bindProcessToNetworkForHostResolution(
5294 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5295 }
5296
5297 /**
5298 * Device is not restricting metered network activity while application is running on
5299 * background.
5300 */
5301 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5302
5303 /**
5304 * Device is restricting metered network activity while application is running on background,
5305 * but application is allowed to bypass it.
5306 * <p>
5307 * In this state, application should take action to mitigate metered network access.
5308 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5309 */
5310 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5311
5312 /**
5313 * Device is restricting metered network activity while application is running on background.
5314 * <p>
5315 * In this state, application should not try to use the network while running on background,
5316 * because it would be denied.
5317 */
5318 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5319
5320 /**
5321 * A change in the background metered network activity restriction has occurred.
5322 * <p>
5323 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5324 * applies to them.
5325 * <p>
5326 * This is only sent to registered receivers, not manifest receivers.
5327 */
5328 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5329 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5330 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5331
Aaron Huangcff22942021-05-27 16:31:26 +08005332 /** @hide */
5333 @Retention(RetentionPolicy.SOURCE)
5334 @IntDef(flag = false, value = {
5335 RESTRICT_BACKGROUND_STATUS_DISABLED,
5336 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5337 RESTRICT_BACKGROUND_STATUS_ENABLED,
5338 })
5339 public @interface RestrictBackgroundStatus {
5340 }
5341
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005342 /**
5343 * Determines if the calling application is subject to metered network restrictions while
5344 * running on background.
5345 *
5346 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5347 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5348 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5349 */
5350 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5351 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005352 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005353 } catch (RemoteException e) {
5354 throw e.rethrowFromSystemServer();
5355 }
5356 }
5357
5358 /**
5359 * The network watchlist is a list of domains and IP addresses that are associated with
5360 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5361 * currently used by the system for validation purposes.
5362 *
5363 * @return Hash of network watchlist config file. Null if config does not exist.
5364 */
5365 @Nullable
5366 public byte[] getNetworkWatchlistConfigHash() {
5367 try {
5368 return mService.getNetworkWatchlistConfigHash();
5369 } catch (RemoteException e) {
5370 Log.e(TAG, "Unable to get watchlist config hash");
5371 throw e.rethrowFromSystemServer();
5372 }
5373 }
5374
5375 /**
5376 * Returns the {@code uid} of the owner of a network connection.
5377 *
5378 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5379 * IPPROTO_UDP} currently supported.
5380 * @param local The local {@link InetSocketAddress} of a connection.
5381 * @param remote The remote {@link InetSocketAddress} of a connection.
5382 * @return {@code uid} if the connection is found and the app has permission to observe it
5383 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5384 * android.os.Process#INVALID_UID} if the connection is not found.
5385 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5386 * user.
5387 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5388 */
5389 public int getConnectionOwnerUid(
5390 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5391 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5392 try {
5393 return mService.getConnectionOwnerUid(connectionInfo);
5394 } catch (RemoteException e) {
5395 throw e.rethrowFromSystemServer();
5396 }
5397 }
5398
5399 private void printStackTrace() {
5400 if (DEBUG) {
5401 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5402 final StringBuffer sb = new StringBuffer();
5403 for (int i = 3; i < callStack.length; i++) {
5404 final String stackTrace = callStack[i].toString();
5405 if (stackTrace == null || stackTrace.contains("android.os")) {
5406 break;
5407 }
5408 sb.append(" [").append(stackTrace).append("]");
5409 }
5410 Log.d(TAG, "StackLog:" + sb.toString());
5411 }
5412 }
5413
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005414 /** @hide */
5415 public TestNetworkManager startOrGetTestNetworkManager() {
5416 final IBinder tnBinder;
5417 try {
5418 tnBinder = mService.startOrGetTestNetworkService();
5419 } catch (RemoteException e) {
5420 throw e.rethrowFromSystemServer();
5421 }
5422
5423 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5424 }
5425
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005426 /** @hide */
5427 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5428 return new ConnectivityDiagnosticsManager(mContext, mService);
5429 }
5430
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005431 /**
5432 * Simulates a Data Stall for the specified Network.
5433 *
5434 * <p>This method should only be used for tests.
5435 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005436 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5437 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005438 *
5439 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005440 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5441 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5442 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005443 * @param network The Network for which a Data Stall is being simluated.
5444 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5445 * @throws SecurityException if the caller is not the owner of the given network.
5446 * @hide
5447 */
5448 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5449 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5450 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005451 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005452 @NonNull Network network, @NonNull PersistableBundle extras) {
5453 try {
5454 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5455 } catch (RemoteException e) {
5456 e.rethrowFromSystemServer();
5457 }
5458 }
5459
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005460 @NonNull
5461 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5462
5463 /**
5464 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5465 * receive available QoS events related to the {@link Network} and local ip + port
5466 * specified within socketInfo.
5467 * <p/>
5468 * The same {@link QosCallback} must be unregistered before being registered a second time,
5469 * otherwise {@link QosCallbackRegistrationException} is thrown.
5470 * <p/>
5471 * This API does not, in itself, require any permission if called with a network that is not
5472 * restricted. However, the underlying implementation currently only supports the IMS network,
5473 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5474 * useful, because they'd never be called back on networks that they would have access to.
5475 *
5476 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5477 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5478 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5479 * @throws RuntimeException if the app already has too many callbacks registered.
5480 *
5481 * Exceptions after the time of registration is passed through
5482 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5483 *
5484 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005485 * @param executor The executor on which the callback will be invoked. The provided
5486 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005487 * callbacks cannot be guaranteed.onQosCallbackRegistered
5488 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005489 *
5490 * @hide
5491 */
5492 @SystemApi
5493 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005494 @CallbackExecutor @NonNull final Executor executor,
5495 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005496 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005497 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005498 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005499
5500 try {
5501 synchronized (mQosCallbackConnections) {
5502 if (getQosCallbackConnection(callback) == null) {
5503 final QosCallbackConnection connection =
5504 new QosCallbackConnection(this, callback, executor);
5505 mQosCallbackConnections.add(connection);
5506 mService.registerQosSocketCallback(socketInfo, connection);
5507 } else {
5508 Log.e(TAG, "registerQosCallback: Callback already registered");
5509 throw new QosCallbackRegistrationException();
5510 }
5511 }
5512 } catch (final RemoteException e) {
5513 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5514
5515 // The same unregister method method is called for consistency even though nothing
5516 // will be sent to the ConnectivityService since the callback was never successfully
5517 // registered.
5518 unregisterQosCallback(callback);
5519 e.rethrowFromSystemServer();
5520 } catch (final ServiceSpecificException e) {
5521 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5522 unregisterQosCallback(callback);
5523 throw convertServiceException(e);
5524 }
5525 }
5526
5527 /**
5528 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5529 * events once unregistered and can be registered a second time.
5530 * <p/>
5531 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5532 *
5533 * @param callback the callback being unregistered
5534 *
5535 * @hide
5536 */
5537 @SystemApi
5538 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5539 Objects.requireNonNull(callback, "The callback must be non-null");
5540 try {
5541 synchronized (mQosCallbackConnections) {
5542 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5543 if (connection != null) {
5544 connection.stopReceivingMessages();
5545 mService.unregisterQosCallback(connection);
5546 mQosCallbackConnections.remove(connection);
5547 } else {
5548 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5549 }
5550 }
5551 } catch (final RemoteException e) {
5552 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5553 e.rethrowFromSystemServer();
5554 }
5555 }
5556
5557 /**
5558 * Gets the connection related to the callback.
5559 *
5560 * @param callback the callback to look up
5561 * @return the related connection
5562 */
5563 @Nullable
5564 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5565 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5566 // Checking by reference here is intentional
5567 if (connection.getCallback() == callback) {
5568 return connection;
5569 }
5570 }
5571 return null;
5572 }
5573
5574 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005575 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005576 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5577 * be used to request that the system provide a network without causing the network to be
5578 * in the foreground.
5579 *
5580 * <p>This method will attempt to find the best network that matches the passed
5581 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5582 * criteria. The platform will evaluate which network is the best at its own discretion.
5583 * Throughput, latency, cost per byte, policy, user preference and other considerations
5584 * may be factored in the decision of what is considered the best network.
5585 *
5586 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5587 * matching this request, while always attempting to match the request to a better network if
5588 * possible. If a better match is found, the platform will switch this request to the now-best
5589 * network and inform the app of the newly best network by invoking
5590 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5591 * will not try to maintain any other network than the best one currently matching the request:
5592 * a network not matching any network request may be disconnected at any time.
5593 *
5594 * <p>For example, an application could use this method to obtain a connected cellular network
5595 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5596 * radio to consume additional power. Or, an application could inform the system that it wants
5597 * a network supporting sending MMSes and have the system let it know about the currently best
5598 * MMS-supporting network through the provided {@link NetworkCallback}.
5599 *
5600 * <p>The status of the request can be followed by listening to the various callbacks described
5601 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5602 * used to direct traffic to the network (although accessing some networks may be subject to
5603 * holding specific permissions). Callers will learn about the specific characteristics of the
5604 * network through
5605 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5606 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5607 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5608 * matching the request at any given time; therefore when a better network matching the request
5609 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5610 * with the new network after which no further updates are given about the previously-best
5611 * network, unless it becomes the best again at some later time. All callbacks are invoked
5612 * in order on the same thread, which by default is a thread created by the framework running
5613 * in the app.
5614 *
5615 * <p>This{@link NetworkRequest} will live until released via
5616 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5617 * which point the system may let go of the network at any time.
5618 *
5619 * <p>It is presently unsupported to request a network with mutable
5620 * {@link NetworkCapabilities} such as
5621 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5622 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5623 * as these {@code NetworkCapabilities} represent states that a particular
5624 * network may never attain, and whether a network will attain these states
5625 * is unknown prior to bringing up the network so the framework does not
5626 * know how to go about satisfying a request with these capabilities.
5627 *
5628 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5629 * number of outstanding requests to 100 per app (identified by their UID), shared with
5630 * all variants of this method, of {@link #registerNetworkCallback} as well as
5631 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5632 * Requesting a network with this method will count toward this limit. If this limit is
5633 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5634 * make sure to unregister the callbacks with
5635 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5636 *
5637 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005638 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5639 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005640 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5641 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005642 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5643 * @throws SecurityException if missing the appropriate permissions.
5644 * @throws RuntimeException if the app already has too many callbacks registered.
5645 *
5646 * @hide
5647 */
5648 @SystemApi(client = MODULE_LIBRARIES)
5649 @SuppressLint("ExecutorRegistration")
5650 @RequiresPermission(anyOf = {
5651 android.Manifest.permission.NETWORK_SETTINGS,
5652 android.Manifest.permission.NETWORK_STACK,
5653 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5654 })
5655 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005656 @NonNull NetworkCallback networkCallback,
5657 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005658 final NetworkCapabilities nc = request.networkCapabilities;
5659 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005660 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005661 }
James Mattis12aeab82021-01-10 14:24:24 -08005662
5663 /**
James Mattis12aeab82021-01-10 14:24:24 -08005664 * Used by automotive devices to set the network preferences used to direct traffic at an
5665 * application level as per the given OemNetworkPreferences. An example use-case would be an
5666 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5667 * vehicle via a particular network.
5668 *
5669 * Calling this will overwrite the existing preference.
5670 *
5671 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5672 * @param executor the executor on which listener will be invoked.
5673 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5674 * communicate completion of setOemNetworkPreference(). This will only be
5675 * called once upon successful completion of setOemNetworkPreference().
5676 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5677 * @throws SecurityException if missing the appropriate permissions.
5678 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005679 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005680 */
James Mattis6e2d7022021-01-26 16:23:52 -08005681 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005682 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005683 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005684 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005685 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005686 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5687 if (null != listener) {
5688 Objects.requireNonNull(executor, "Executor must be non-null");
5689 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005690 final IOnCompleteListener listenerInternal = listener == null ? null :
5691 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005692 @Override
5693 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005694 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005695 }
5696 };
5697
5698 try {
5699 mService.setOemNetworkPreference(preference, listenerInternal);
5700 } catch (RemoteException e) {
5701 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5702 throw e.rethrowFromSystemServer();
5703 }
5704 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005705
Chalard Jeanad565e22021-02-25 17:23:40 +09005706 /**
5707 * Request that a user profile is put by default on a network matching a given preference.
5708 *
5709 * See the documentation for the individual preferences for a description of the supported
5710 * behaviors.
5711 *
5712 * @param profile the profile concerned.
5713 * @param preference the preference for this profile.
5714 * @param executor an executor to execute the listener on. Optional if listener is null.
5715 * @param listener an optional listener to listen for completion of the operation.
5716 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5717 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005718 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5719 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005720 * @hide
5721 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005722 // This function is for establishing per-profile default networking and can only be called by
5723 // the device policy manager, running as the system server. It would make no sense to call it
5724 // on a context for a user because it does not establish a setting on behalf of a user, rather
5725 // it establishes a setting for a user on behalf of the DPM.
5726 @SuppressLint({"UserHandle"})
5727 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005728 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005729 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005730 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005731 @ProfileNetworkPreferencePolicy final int preference,
5732 @Nullable @CallbackExecutor final Executor executor,
5733 @Nullable final Runnable listener) {
5734
5735 ProfileNetworkPreference.Builder preferenceBuilder =
5736 new ProfileNetworkPreference.Builder();
5737 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005738 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5739 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5740 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005741 setProfileNetworkPreferences(profile,
5742 List.of(preferenceBuilder.build()), executor, listener);
5743 }
5744
5745 /**
5746 * Set a list of default network selection policies for a user profile.
5747 *
5748 * Calling this API with a user handle defines the entire policy for that user handle.
5749 * It will overwrite any setting previously set for the same user profile,
5750 * and not affect previously set settings for other handles.
5751 *
5752 * Call this API with an empty list to remove settings for this user profile.
5753 *
5754 * See {@link ProfileNetworkPreference} for more details on each preference
5755 * parameter.
5756 *
5757 * @param profile the user profile for which the preference is being set.
5758 * @param profileNetworkPreferences the list of profile network preferences for the
5759 * provided profile.
5760 * @param executor an executor to execute the listener on. Optional if listener is null.
5761 * @param listener an optional listener to listen for completion of the operation.
5762 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5763 * @throws SecurityException if missing the appropriate permissions.
5764 * @hide
5765 */
5766 @SystemApi(client = MODULE_LIBRARIES)
5767 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5768 public void setProfileNetworkPreferences(
5769 @NonNull final UserHandle profile,
5770 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005771 @Nullable @CallbackExecutor final Executor executor,
5772 @Nullable final Runnable listener) {
5773 if (null != listener) {
5774 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5775 }
5776 final IOnCompleteListener proxy;
5777 if (null == listener) {
5778 proxy = null;
5779 } else {
5780 proxy = new IOnCompleteListener.Stub() {
5781 @Override
5782 public void onComplete() {
5783 executor.execute(listener::run);
5784 }
5785 };
5786 }
5787 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005788 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005789 } catch (RemoteException e) {
5790 throw e.rethrowFromSystemServer();
5791 }
5792 }
5793
lucaslin5cdbcfb2021-03-12 00:46:33 +08005794 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005795 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005796 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005797 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005798
5799 /**
5800 * Get the network ID range reserved for IPSec tunnel interfaces.
5801 *
5802 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5803 * @hide
5804 */
5805 @SystemApi(client = MODULE_LIBRARIES)
5806 @NonNull
5807 public static Range<Integer> getIpSecNetIdRange() {
5808 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5809 }
markchien738ad912021-12-09 18:15:45 +08005810
5811 /**
markchiene46042b2022-03-02 18:07:35 +08005812 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5813 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005814 *
5815 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005816 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005817 * @hide
5818 */
5819 @SystemApi(client = MODULE_LIBRARIES)
5820 @RequiresPermission(anyOf = {
5821 android.Manifest.permission.NETWORK_SETTINGS,
5822 android.Manifest.permission.NETWORK_STACK,
5823 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5824 })
markchiene46042b2022-03-02 18:07:35 +08005825 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005826 try {
markchiene46042b2022-03-02 18:07:35 +08005827 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08005828 } catch (RemoteException e) {
5829 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005830 }
5831 }
5832
5833 /**
markchiene46042b2022-03-02 18:07:35 +08005834 * Removes the specified UID from the list of UIDs that are allowed to use background data on
5835 * metered networks when background data is restricted. The deny list takes precedence over
5836 * the allow list.
5837 *
5838 * @param uid uid of target app
5839 * @throws IllegalStateException if updating allow list failed.
5840 * @hide
5841 */
5842 @SystemApi(client = MODULE_LIBRARIES)
5843 @RequiresPermission(anyOf = {
5844 android.Manifest.permission.NETWORK_SETTINGS,
5845 android.Manifest.permission.NETWORK_STACK,
5846 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5847 })
5848 public void removeUidFromMeteredNetworkAllowList(final int uid) {
5849 try {
5850 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
5851 } catch (RemoteException e) {
5852 throw e.rethrowFromSystemServer();
5853 }
5854 }
5855
5856 /**
5857 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
5858 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08005859 *
5860 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005861 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08005862 * @hide
5863 */
5864 @SystemApi(client = MODULE_LIBRARIES)
5865 @RequiresPermission(anyOf = {
5866 android.Manifest.permission.NETWORK_SETTINGS,
5867 android.Manifest.permission.NETWORK_STACK,
5868 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5869 })
markchiene46042b2022-03-02 18:07:35 +08005870 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005871 try {
markchiene46042b2022-03-02 18:07:35 +08005872 mService.updateMeteredNetworkDenyList(uid, true /* add */);
5873 } catch (RemoteException e) {
5874 throw e.rethrowFromSystemServer();
5875 }
5876 }
5877
5878 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005879 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08005880 * networks if background data is not restricted. The deny list takes precedence over the
5881 * allow list.
5882 *
5883 * @param uid uid of target app
5884 * @throws IllegalStateException if updating deny list failed.
5885 * @hide
5886 */
5887 @SystemApi(client = MODULE_LIBRARIES)
5888 @RequiresPermission(anyOf = {
5889 android.Manifest.permission.NETWORK_SETTINGS,
5890 android.Manifest.permission.NETWORK_STACK,
5891 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5892 })
5893 public void removeUidFromMeteredNetworkDenyList(final int uid) {
5894 try {
5895 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08005896 } catch (RemoteException e) {
5897 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08005898 }
5899 }
5900
5901 /**
5902 * Sets a firewall rule for the specified UID on the specified chain.
5903 *
5904 * @param chain target chain.
5905 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08005906 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08005907 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08005908 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08005909 * @hide
5910 */
5911 @SystemApi(client = MODULE_LIBRARIES)
5912 @RequiresPermission(anyOf = {
5913 android.Manifest.permission.NETWORK_SETTINGS,
5914 android.Manifest.permission.NETWORK_STACK,
5915 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5916 })
markchien3c04e662022-03-22 16:29:56 +08005917 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
5918 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08005919 try {
markchien3c04e662022-03-22 16:29:56 +08005920 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08005921 } catch (RemoteException e) {
5922 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005923 }
5924 }
markchien98a6f952022-01-13 23:43:53 +08005925
5926 /**
5927 * Enables or disables the specified firewall chain.
5928 *
5929 * @param chain target chain.
5930 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00005931 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08005932 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08005933 * @hide
5934 */
5935 @SystemApi(client = MODULE_LIBRARIES)
5936 @RequiresPermission(anyOf = {
5937 android.Manifest.permission.NETWORK_SETTINGS,
5938 android.Manifest.permission.NETWORK_STACK,
5939 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5940 })
5941 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
5942 try {
5943 mService.setFirewallChainEnabled(chain, enable);
5944 } catch (RemoteException e) {
5945 throw e.rethrowFromSystemServer();
5946 }
5947 }
markchien00a0bed2022-01-13 23:46:13 +08005948
5949 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00005950 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00005951 *
5952 * @param chain target chain.
5953 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
5954 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00005955 * @throws ServiceSpecificException in case of failure, with an error code indicating the
5956 * cause of the failure.
5957 * @hide
5958 */
5959 @RequiresPermission(anyOf = {
5960 android.Manifest.permission.NETWORK_SETTINGS,
5961 android.Manifest.permission.NETWORK_STACK,
5962 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5963 })
5964 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
5965 try {
5966 return mService.getFirewallChainEnabled(chain);
5967 } catch (RemoteException e) {
5968 throw e.rethrowFromSystemServer();
5969 }
5970 }
5971
5972 /**
markchien00a0bed2022-01-13 23:46:13 +08005973 * Replaces the contents of the specified UID-based firewall chain.
5974 *
5975 * @param chain target chain to replace.
5976 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00005977 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08005978 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
5979 * @hide
5980 */
5981 @SystemApi(client = MODULE_LIBRARIES)
5982 @RequiresPermission(anyOf = {
5983 android.Manifest.permission.NETWORK_SETTINGS,
5984 android.Manifest.permission.NETWORK_STACK,
5985 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5986 })
5987 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
5988 Objects.requireNonNull(uids);
5989 try {
5990 mService.replaceFirewallChain(chain, uids);
5991 } catch (RemoteException e) {
5992 throw e.rethrowFromSystemServer();
5993 }
5994 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08005995
5996 /** @hide */
5997 public IBinder getCompanionDeviceManagerProxyService() {
5998 try {
5999 return mService.getCompanionDeviceManagerProxyService();
6000 } catch (RemoteException e) {
6001 throw e.rethrowFromSystemServer();
6002 }
6003 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006004}