blob: ef9a206b6967caa0284113f32672c040333f7f18 [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.
987 * Denylist of apps that will not have network access due to OEM-specific restrictions.
988 * @hide
989 */
Motomu Utsumi62385c82022-06-12 11:37:19 +0000990 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +0000991 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
992
993 /**
994 * Firewall chain used for OEM-specific application restrictions.
995 * Denylist of apps that will not have network access due to OEM-specific restrictions.
996 * @hide
997 */
Motomu Utsumi62385c82022-06-12 11:37:19 +0000998 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +0000999 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1000
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001001 /**
1002 * Firewall chain used for OEM-specific application restrictions.
1003 * Denylist of apps that will not have network access due to OEM-specific restrictions.
1004 * @hide
1005 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001006 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001007 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1008
markchiene1561fa2021-12-09 22:00:56 +08001009 /** @hide */
1010 @Retention(RetentionPolicy.SOURCE)
1011 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1012 FIREWALL_CHAIN_DOZABLE,
1013 FIREWALL_CHAIN_STANDBY,
1014 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001015 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001016 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Motomu Utsumid9801492022-06-01 13:57:27 +00001017 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001018 FIREWALL_CHAIN_OEM_DENY_2,
1019 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001020 })
1021 public @interface FirewallChain {}
Robert Horvathd945bf02022-01-27 19:55:16 +01001022 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
markchiene1561fa2021-12-09 22:00:56 +08001023
1024 /**
markchien011a7f52022-03-29 01:07:22 +08001025 * A firewall rule which allows or drops packets depending on existing policy.
1026 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1027 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001028 * @hide
1029 */
1030 @SystemApi(client = MODULE_LIBRARIES)
1031 public static final int FIREWALL_RULE_DEFAULT = 0;
1032
1033 /**
markchien011a7f52022-03-29 01:07:22 +08001034 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1035 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001036 * @hide
1037 */
1038 @SystemApi(client = MODULE_LIBRARIES)
1039 public static final int FIREWALL_RULE_ALLOW = 1;
1040
1041 /**
markchien011a7f52022-03-29 01:07:22 +08001042 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1043 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001044 * @hide
1045 */
1046 @SystemApi(client = MODULE_LIBRARIES)
1047 public static final int FIREWALL_RULE_DENY = 2;
1048
1049 /** @hide */
1050 @Retention(RetentionPolicy.SOURCE)
1051 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1052 FIREWALL_RULE_DEFAULT,
1053 FIREWALL_RULE_ALLOW,
1054 FIREWALL_RULE_DENY
1055 })
1056 public @interface FirewallRule {}
1057
1058 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001059 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1060 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1061 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1062 * methods that take a Context argument.
1063 */
1064 private static ConnectivityManager sInstance;
1065
1066 private final Context mContext;
1067
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001068 @GuardedBy("mTetheringEventCallbacks")
1069 private TetheringManager mTetheringManager;
1070
1071 private TetheringManager getTetheringManager() {
1072 synchronized (mTetheringEventCallbacks) {
1073 if (mTetheringManager == null) {
1074 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1075 }
1076 return mTetheringManager;
1077 }
1078 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001079
1080 /**
1081 * Tests if a given integer represents a valid network type.
1082 * @param networkType the type to be tested
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001083 * @return {@code true} if the type is valid, else {@code false}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001084 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1085 * validate a network type.
1086 */
1087 @Deprecated
1088 public static boolean isNetworkTypeValid(int networkType) {
1089 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1090 }
1091
1092 /**
1093 * Returns a non-localized string representing a given network type.
1094 * ONLY used for debugging output.
1095 * @param type the type needing naming
1096 * @return a String for the given type, or a string version of the type ("87")
1097 * if no name is known.
1098 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1099 * {@hide}
1100 */
1101 @Deprecated
1102 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1103 public static String getNetworkTypeName(int type) {
1104 switch (type) {
1105 case TYPE_NONE:
1106 return "NONE";
1107 case TYPE_MOBILE:
1108 return "MOBILE";
1109 case TYPE_WIFI:
1110 return "WIFI";
1111 case TYPE_MOBILE_MMS:
1112 return "MOBILE_MMS";
1113 case TYPE_MOBILE_SUPL:
1114 return "MOBILE_SUPL";
1115 case TYPE_MOBILE_DUN:
1116 return "MOBILE_DUN";
1117 case TYPE_MOBILE_HIPRI:
1118 return "MOBILE_HIPRI";
1119 case TYPE_WIMAX:
1120 return "WIMAX";
1121 case TYPE_BLUETOOTH:
1122 return "BLUETOOTH";
1123 case TYPE_DUMMY:
1124 return "DUMMY";
1125 case TYPE_ETHERNET:
1126 return "ETHERNET";
1127 case TYPE_MOBILE_FOTA:
1128 return "MOBILE_FOTA";
1129 case TYPE_MOBILE_IMS:
1130 return "MOBILE_IMS";
1131 case TYPE_MOBILE_CBS:
1132 return "MOBILE_CBS";
1133 case TYPE_WIFI_P2P:
1134 return "WIFI_P2P";
1135 case TYPE_MOBILE_IA:
1136 return "MOBILE_IA";
1137 case TYPE_MOBILE_EMERGENCY:
1138 return "MOBILE_EMERGENCY";
1139 case TYPE_PROXY:
1140 return "PROXY";
1141 case TYPE_VPN:
1142 return "VPN";
1143 default:
1144 return Integer.toString(type);
1145 }
1146 }
1147
1148 /**
1149 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001150 */
lucaslin10774b72021-03-17 14:16:01 +08001151 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001152 public void systemReady() {
1153 try {
1154 mService.systemReady();
1155 } catch (RemoteException e) {
1156 throw e.rethrowFromSystemServer();
1157 }
1158 }
1159
1160 /**
1161 * Checks if a given type uses the cellular data connection.
1162 * This should be replaced in the future by a network property.
1163 * @param networkType the type to check
1164 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1165 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1166 * {@hide}
1167 */
1168 @Deprecated
1169 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1170 public static boolean isNetworkTypeMobile(int networkType) {
1171 switch (networkType) {
1172 case TYPE_MOBILE:
1173 case TYPE_MOBILE_MMS:
1174 case TYPE_MOBILE_SUPL:
1175 case TYPE_MOBILE_DUN:
1176 case TYPE_MOBILE_HIPRI:
1177 case TYPE_MOBILE_FOTA:
1178 case TYPE_MOBILE_IMS:
1179 case TYPE_MOBILE_CBS:
1180 case TYPE_MOBILE_IA:
1181 case TYPE_MOBILE_EMERGENCY:
1182 return true;
1183 default:
1184 return false;
1185 }
1186 }
1187
1188 /**
1189 * Checks if the given network type is backed by a Wi-Fi radio.
1190 *
1191 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1192 * @hide
1193 */
1194 @Deprecated
1195 public static boolean isNetworkTypeWifi(int networkType) {
1196 switch (networkType) {
1197 case TYPE_WIFI:
1198 case TYPE_WIFI_P2P:
1199 return true;
1200 default:
1201 return false;
1202 }
1203 }
1204
1205 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001206 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001207 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001208 * Specify that the traffic for this user should by follow the default rules.
1209 * @hide
1210 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001211 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001212 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1213
1214 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001215 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001216 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001217 * Specify that the traffic for this user should by default go on a network with
1218 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1219 * if no such network is available.
1220 * @hide
1221 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001222 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001223 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1224
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001225 /**
1226 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001227 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001228 * Specify that the traffic for this user should by default go on a network with
1229 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
1230 * should not go on the system default network
1231 * @hide
1232 */
1233 @SystemApi(client = MODULE_LIBRARIES)
1234 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1235
Chalard Jeanad565e22021-02-25 17:23:40 +09001236 /** @hide */
1237 @Retention(RetentionPolicy.SOURCE)
1238 @IntDef(value = {
1239 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001240 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1241 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001242 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001243 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001244 }
1245
1246 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001247 * Specifies the preferred network type. When the device has more
1248 * than one type available the preferred network type will be used.
1249 *
1250 * @param preference the network type to prefer over all others. It is
1251 * unspecified what happens to the old preferred network in the
1252 * overall ordering.
1253 * @deprecated Functionality has been removed as it no longer makes sense,
1254 * with many more than two networks - we'd need an array to express
1255 * preference. Instead we use dynamic network properties of
1256 * the networks to describe their precedence.
1257 */
1258 @Deprecated
1259 public void setNetworkPreference(int preference) {
1260 }
1261
1262 /**
1263 * Retrieves the current preferred network type.
1264 *
1265 * @return an integer representing the preferred network type
1266 *
1267 * @deprecated Functionality has been removed as it no longer makes sense,
1268 * with many more than two networks - we'd need an array to express
1269 * preference. Instead we use dynamic network properties of
1270 * the networks to describe their precedence.
1271 */
1272 @Deprecated
1273 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1274 public int getNetworkPreference() {
1275 return TYPE_NONE;
1276 }
1277
1278 /**
1279 * Returns details about the currently active default data network. When
1280 * connected, this network is the default route for outgoing connections.
1281 * You should always check {@link NetworkInfo#isConnected()} before initiating
1282 * network traffic. This may return {@code null} when there is no default
1283 * network.
1284 * Note that if the default network is a VPN, this method will return the
1285 * NetworkInfo for one of its underlying networks instead, or null if the
1286 * VPN agent did not specify any. Apps interested in learning about VPNs
1287 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1288 *
1289 * @return a {@link NetworkInfo} object for the current default network
1290 * or {@code null} if no default network is currently active
1291 * @deprecated See {@link NetworkInfo}.
1292 */
1293 @Deprecated
1294 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1295 @Nullable
1296 public NetworkInfo getActiveNetworkInfo() {
1297 try {
1298 return mService.getActiveNetworkInfo();
1299 } catch (RemoteException e) {
1300 throw e.rethrowFromSystemServer();
1301 }
1302 }
1303
1304 /**
1305 * Returns a {@link Network} object corresponding to the currently active
1306 * default data network. In the event that the current active default data
1307 * network disconnects, the returned {@code Network} object will no longer
1308 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001309 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001310 *
1311 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001312 * {@code null} if no default network is currently active or if
1313 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001314 */
1315 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1316 @Nullable
1317 public Network getActiveNetwork() {
1318 try {
1319 return mService.getActiveNetwork();
1320 } catch (RemoteException e) {
1321 throw e.rethrowFromSystemServer();
1322 }
1323 }
1324
1325 /**
1326 * Returns a {@link Network} object corresponding to the currently active
1327 * default data network for a specific UID. In the event that the default data
1328 * network disconnects, the returned {@code Network} object will no longer
1329 * be usable. This will return {@code null} when there is no default
1330 * network for the UID.
1331 *
1332 * @return a {@link Network} object for the current default network for the
1333 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001334 *
1335 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001336 */
1337 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1338 @Nullable
1339 public Network getActiveNetworkForUid(int uid) {
1340 return getActiveNetworkForUid(uid, false);
1341 }
1342
1343 /** {@hide} */
1344 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1345 try {
1346 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1347 } catch (RemoteException e) {
1348 throw e.rethrowFromSystemServer();
1349 }
1350 }
1351
1352 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001353 * Adds or removes a requirement for given UID ranges to use the VPN.
1354 *
1355 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1356 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1357 * otherwise have permission to bypass the VPN (e.g., because they have the
1358 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1359 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1360 * set to {@code false}, a previously-added restriction is removed.
1361 * <p>
1362 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1363 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1364 * remove a previously-added range, the exact range must be removed as is.
1365 * <p>
1366 * The changes are applied asynchronously and may not have been applied by the time the method
1367 * returns. Apps will be notified about any changes that apply to them via
1368 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1369 * effect.
1370 * <p>
1371 * This method should be called only by the VPN code.
1372 *
1373 * @param ranges the UID ranges to restrict
1374 * @param requireVpn whether the specified UID ranges must use a VPN
1375 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001376 * @hide
1377 */
1378 @RequiresPermission(anyOf = {
1379 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001380 android.Manifest.permission.NETWORK_STACK,
1381 android.Manifest.permission.NETWORK_SETTINGS})
1382 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001383 public void setRequireVpnForUids(boolean requireVpn,
1384 @NonNull Collection<Range<Integer>> ranges) {
1385 Objects.requireNonNull(ranges);
1386 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1387 // This method is not necessarily expected to be used outside the system server, so
1388 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1389 // stack process, or by tests.
1390 UidRange[] rangesArray = new UidRange[ranges.size()];
1391 int index = 0;
1392 for (Range<Integer> range : ranges) {
1393 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1394 }
1395 try {
1396 mService.setRequireVpnForUids(requireVpn, rangesArray);
1397 } catch (RemoteException e) {
1398 throw e.rethrowFromSystemServer();
1399 }
1400 }
1401
1402 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001403 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1404 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1405 * but is still supported for backwards compatibility.
1406 * <p>
1407 * This type of VPN is assumed always to use the system default network, and must always declare
1408 * exactly one underlying network, which is the network that was the default when the VPN
1409 * connected.
1410 * <p>
1411 * Calling this method with {@code true} enables legacy behaviour, specifically:
1412 * <ul>
1413 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1414 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1415 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1416 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1417 * underlying the VPN.</li>
1418 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1419 * similarly replaced by the VPN network state.</li>
1420 * <li>Information on current network interfaces passed to NetworkStatsService will not
1421 * include any VPN interfaces.</li>
1422 * </ul>
1423 *
1424 * @param enabled whether legacy lockdown VPN is enabled or disabled
1425 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001426 * @hide
1427 */
1428 @RequiresPermission(anyOf = {
1429 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001430 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001431 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001432 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001433 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1434 try {
1435 mService.setLegacyLockdownVpnEnabled(enabled);
1436 } catch (RemoteException e) {
1437 throw e.rethrowFromSystemServer();
1438 }
1439 }
1440
1441 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001442 * Returns details about the currently active default data network for a given uid.
1443 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001444 *
1445 * @return a {@link NetworkInfo} object for the current default network
1446 * for the given uid or {@code null} if no default network is
1447 * available for the specified uid.
1448 *
1449 * {@hide}
1450 */
1451 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1452 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1453 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1454 return getActiveNetworkInfoForUid(uid, false);
1455 }
1456
1457 /** {@hide} */
1458 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1459 try {
1460 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1461 } catch (RemoteException e) {
1462 throw e.rethrowFromSystemServer();
1463 }
1464 }
1465
1466 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001467 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001468 *
1469 * @param networkType integer specifying which networkType in
1470 * which you're interested.
1471 * @return a {@link NetworkInfo} object for the requested
1472 * network type or {@code null} if the type is not
1473 * supported by the device. If {@code networkType} is
1474 * TYPE_VPN and a VPN is active for the calling app,
1475 * then this method will try to return one of the
1476 * underlying networks for the VPN or null if the
1477 * VPN agent didn't specify any.
1478 *
1479 * @deprecated This method does not support multiple connected networks
1480 * of the same type. Use {@link #getAllNetworks} and
1481 * {@link #getNetworkInfo(android.net.Network)} instead.
1482 */
1483 @Deprecated
1484 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1485 @Nullable
1486 public NetworkInfo getNetworkInfo(int networkType) {
1487 try {
1488 return mService.getNetworkInfo(networkType);
1489 } catch (RemoteException e) {
1490 throw e.rethrowFromSystemServer();
1491 }
1492 }
1493
1494 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001495 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001496 *
1497 * @param network {@link Network} specifying which network
1498 * in which you're interested.
1499 * @return a {@link NetworkInfo} object for the requested
1500 * network or {@code null} if the {@code Network}
1501 * is not valid.
1502 * @deprecated See {@link NetworkInfo}.
1503 */
1504 @Deprecated
1505 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1506 @Nullable
1507 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1508 return getNetworkInfoForUid(network, Process.myUid(), false);
1509 }
1510
1511 /** {@hide} */
1512 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1513 try {
1514 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1515 } catch (RemoteException e) {
1516 throw e.rethrowFromSystemServer();
1517 }
1518 }
1519
1520 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001521 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001522 *
1523 * @return an array of {@link NetworkInfo} objects. Check each
1524 * {@link NetworkInfo#getType} for which type each applies.
1525 *
1526 * @deprecated This method does not support multiple connected networks
1527 * of the same type. Use {@link #getAllNetworks} and
1528 * {@link #getNetworkInfo(android.net.Network)} instead.
1529 */
1530 @Deprecated
1531 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1532 @NonNull
1533 public NetworkInfo[] getAllNetworkInfo() {
1534 try {
1535 return mService.getAllNetworkInfo();
1536 } catch (RemoteException e) {
1537 throw e.rethrowFromSystemServer();
1538 }
1539 }
1540
1541 /**
junyulaib1211372021-03-03 12:09:05 +08001542 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1543 * connected.
1544 * @hide
1545 */
1546 @SystemApi(client = MODULE_LIBRARIES)
1547 @RequiresPermission(anyOf = {
1548 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1549 android.Manifest.permission.NETWORK_STACK,
1550 android.Manifest.permission.NETWORK_SETTINGS})
1551 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001552 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001553 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001554 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001555 } catch (RemoteException e) {
1556 throw e.rethrowFromSystemServer();
1557 }
1558 }
1559
1560 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001561 * Returns the {@link Network} object currently serving a given type, or
1562 * null if the given type is not connected.
1563 *
1564 * @hide
1565 * @deprecated This method does not support multiple connected networks
1566 * of the same type. Use {@link #getAllNetworks} and
1567 * {@link #getNetworkInfo(android.net.Network)} instead.
1568 */
1569 @Deprecated
1570 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1571 @UnsupportedAppUsage
1572 public Network getNetworkForType(int networkType) {
1573 try {
1574 return mService.getNetworkForType(networkType);
1575 } catch (RemoteException e) {
1576 throw e.rethrowFromSystemServer();
1577 }
1578 }
1579
1580 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001581 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001582 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001583 * @deprecated This method does not provide any notification of network state changes, forcing
1584 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1585 * Apps should use methods such as
1586 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1587 * Apps that desire to obtain information about networks that do not apply to them
1588 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1589 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001590 * @return an array of {@link Network} objects.
1591 */
1592 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1593 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001594 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001595 public Network[] getAllNetworks() {
1596 try {
1597 return mService.getAllNetworks();
1598 } catch (RemoteException e) {
1599 throw e.rethrowFromSystemServer();
1600 }
1601 }
1602
1603 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001604 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001605 * the Networks that applications run by the given user will use by default.
1606 * @hide
1607 */
1608 @UnsupportedAppUsage
1609 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1610 try {
1611 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001612 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001613 } catch (RemoteException e) {
1614 throw e.rethrowFromSystemServer();
1615 }
1616 }
1617
1618 /**
1619 * Returns the IP information for the current default network.
1620 *
1621 * @return a {@link LinkProperties} object describing the IP info
1622 * for the current default network, or {@code null} if there
1623 * is no current default network.
1624 *
1625 * {@hide}
1626 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1627 * value of {@link #getActiveNetwork()} instead. In particular,
1628 * this method will return non-null LinkProperties even if the
1629 * app is blocked by policy from using this network.
1630 */
1631 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1632 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1633 public LinkProperties getActiveLinkProperties() {
1634 try {
1635 return mService.getActiveLinkProperties();
1636 } catch (RemoteException e) {
1637 throw e.rethrowFromSystemServer();
1638 }
1639 }
1640
1641 /**
1642 * Returns the IP information for a given network type.
1643 *
1644 * @param networkType the network type of interest.
1645 * @return a {@link LinkProperties} object describing the IP info
1646 * for the given networkType, or {@code null} if there is
1647 * no current default network.
1648 *
1649 * {@hide}
1650 * @deprecated This method does not support multiple connected networks
1651 * of the same type. Use {@link #getAllNetworks},
1652 * {@link #getNetworkInfo(android.net.Network)}, and
1653 * {@link #getLinkProperties(android.net.Network)} instead.
1654 */
1655 @Deprecated
1656 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1657 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1658 public LinkProperties getLinkProperties(int networkType) {
1659 try {
1660 return mService.getLinkPropertiesForType(networkType);
1661 } catch (RemoteException e) {
1662 throw e.rethrowFromSystemServer();
1663 }
1664 }
1665
1666 /**
1667 * Get the {@link LinkProperties} for the given {@link Network}. This
1668 * will return {@code null} if the network is unknown.
1669 *
1670 * @param network The {@link Network} object identifying the network in question.
1671 * @return The {@link LinkProperties} for the network, or {@code null}.
1672 */
1673 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1674 @Nullable
1675 public LinkProperties getLinkProperties(@Nullable Network network) {
1676 try {
1677 return mService.getLinkProperties(network);
1678 } catch (RemoteException e) {
1679 throw e.rethrowFromSystemServer();
1680 }
1681 }
1682
1683 /**
lucaslinc582d502022-01-27 09:07:00 +08001684 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001685 *
lucaslinc582d502022-01-27 09:07:00 +08001686 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1687 * given package, considering its permissions.
1688 *
1689 * @param lp A {@link LinkProperties} which will be redacted.
1690 * @param uid The target uid.
1691 * @param packageName The name of the package, for appops logging.
1692 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1693 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1694 * @hide
1695 */
1696 @RequiresPermission(anyOf = {
1697 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1698 android.Manifest.permission.NETWORK_STACK,
1699 android.Manifest.permission.NETWORK_SETTINGS})
1700 @SystemApi(client = MODULE_LIBRARIES)
1701 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001702 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001703 @NonNull String packageName) {
1704 try {
lucaslind2b06132022-03-02 10:56:57 +08001705 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001706 lp, uid, packageName, getAttributionTag());
1707 } catch (RemoteException e) {
1708 throw e.rethrowFromSystemServer();
1709 }
1710 }
1711
1712 /**
1713 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1714 *
1715 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1716 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1717 * sensitive information. To retrieve this location sensitive information (subject to
1718 * the caller's location permissions), use a {@link NetworkCallback} with the
1719 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1720 *
1721 * This method returns {@code null} if the network is unknown or if the |network| argument
1722 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001723 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001724 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001725 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001726 */
1727 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1728 @Nullable
1729 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1730 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001731 return mService.getNetworkCapabilities(
1732 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001733 } catch (RemoteException e) {
1734 throw e.rethrowFromSystemServer();
1735 }
1736 }
1737
1738 /**
lucaslinc582d502022-01-27 09:07:00 +08001739 * Redact {@link NetworkCapabilities} for a given package.
1740 *
1741 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001742 * to the given package, considering its permissions. If the passed capabilities contain
1743 * location-sensitive information, they will be redacted to the correct degree for the location
1744 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1745 * that level of location. If the UID holds no location permission, the returned object will
1746 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001747 *
1748 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1749 * @param uid The target uid.
1750 * @param packageName The name of the package, for appops logging.
1751 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1752 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1753 * @hide
1754 */
1755 @RequiresPermission(anyOf = {
1756 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1757 android.Manifest.permission.NETWORK_STACK,
1758 android.Manifest.permission.NETWORK_SETTINGS})
1759 @SystemApi(client = MODULE_LIBRARIES)
1760 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001761 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001762 @NonNull NetworkCapabilities nc,
1763 int uid, @NonNull String packageName) {
1764 try {
lucaslind2b06132022-03-02 10:56:57 +08001765 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001766 getAttributionTag());
1767 } catch (RemoteException e) {
1768 throw e.rethrowFromSystemServer();
1769 }
1770 }
1771
1772 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001773 * Gets a URL that can be used for resolving whether a captive portal is present.
1774 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1775 * portal is present.
1776 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1777 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1778 *
1779 * The system network validation may be using different strategies to detect captive portals,
1780 * so this method does not necessarily return a URL used by the system. It only returns a URL
1781 * that may be relevant for other components trying to detect captive portals.
1782 *
1783 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001784 * @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 +09001785 * system.
1786 */
1787 @Deprecated
1788 @SystemApi
1789 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1790 public String getCaptivePortalServerUrl() {
1791 try {
1792 return mService.getCaptivePortalServerUrl();
1793 } catch (RemoteException e) {
1794 throw e.rethrowFromSystemServer();
1795 }
1796 }
1797
1798 /**
1799 * Tells the underlying networking system that the caller wants to
1800 * begin using the named feature. The interpretation of {@code feature}
1801 * is completely up to each networking implementation.
1802 *
1803 * <p>This method requires the caller to hold either the
1804 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1805 * or the ability to modify system settings as determined by
1806 * {@link android.provider.Settings.System#canWrite}.</p>
1807 *
1808 * @param networkType specifies which network the request pertains to
1809 * @param feature the name of the feature to be used
1810 * @return an integer value representing the outcome of the request.
1811 * The interpretation of this value is specific to each networking
1812 * implementation+feature combination, except that the value {@code -1}
1813 * always indicates failure.
1814 *
1815 * @deprecated Deprecated in favor of the cleaner
1816 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1817 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1818 * throw {@code UnsupportedOperationException} if called.
1819 * @removed
1820 */
1821 @Deprecated
1822 public int startUsingNetworkFeature(int networkType, String feature) {
1823 checkLegacyRoutingApiAccess();
1824 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1825 if (netCap == null) {
1826 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1827 feature);
1828 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1829 }
1830
1831 NetworkRequest request = null;
1832 synchronized (sLegacyRequests) {
1833 LegacyRequest l = sLegacyRequests.get(netCap);
1834 if (l != null) {
1835 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1836 renewRequestLocked(l);
1837 if (l.currentNetwork != null) {
1838 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1839 } else {
1840 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1841 }
1842 }
1843
1844 request = requestNetworkForFeatureLocked(netCap);
1845 }
1846 if (request != null) {
1847 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1848 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1849 } else {
1850 Log.d(TAG, " request Failed");
1851 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1852 }
1853 }
1854
1855 /**
1856 * Tells the underlying networking system that the caller is finished
1857 * using the named feature. The interpretation of {@code feature}
1858 * is completely up to each networking implementation.
1859 *
1860 * <p>This method requires the caller to hold either the
1861 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1862 * or the ability to modify system settings as determined by
1863 * {@link android.provider.Settings.System#canWrite}.</p>
1864 *
1865 * @param networkType specifies which network the request pertains to
1866 * @param feature the name of the feature that is no longer needed
1867 * @return an integer value representing the outcome of the request.
1868 * The interpretation of this value is specific to each networking
1869 * implementation+feature combination, except that the value {@code -1}
1870 * always indicates failure.
1871 *
1872 * @deprecated Deprecated in favor of the cleaner
1873 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1874 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1875 * throw {@code UnsupportedOperationException} if called.
1876 * @removed
1877 */
1878 @Deprecated
1879 public int stopUsingNetworkFeature(int networkType, String feature) {
1880 checkLegacyRoutingApiAccess();
1881 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1882 if (netCap == null) {
1883 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1884 feature);
1885 return -1;
1886 }
1887
1888 if (removeRequestForFeature(netCap)) {
1889 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1890 }
1891 return 1;
1892 }
1893
1894 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1895 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1896 if (networkType == TYPE_MOBILE) {
1897 switch (feature) {
1898 case "enableCBS":
1899 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1900 case "enableDUN":
1901 case "enableDUNAlways":
1902 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1903 case "enableFOTA":
1904 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1905 case "enableHIPRI":
1906 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1907 case "enableIMS":
1908 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1909 case "enableMMS":
1910 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1911 case "enableSUPL":
1912 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1913 default:
1914 return null;
1915 }
1916 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1917 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1918 }
1919 return null;
1920 }
1921
1922 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1923 if (netCap == null) return TYPE_NONE;
1924 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1925 return TYPE_MOBILE_CBS;
1926 }
1927 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1928 return TYPE_MOBILE_IMS;
1929 }
1930 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1931 return TYPE_MOBILE_FOTA;
1932 }
1933 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1934 return TYPE_MOBILE_DUN;
1935 }
1936 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1937 return TYPE_MOBILE_SUPL;
1938 }
1939 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1940 return TYPE_MOBILE_MMS;
1941 }
1942 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1943 return TYPE_MOBILE_HIPRI;
1944 }
1945 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1946 return TYPE_WIFI_P2P;
1947 }
1948 return TYPE_NONE;
1949 }
1950
1951 private static class LegacyRequest {
1952 NetworkCapabilities networkCapabilities;
1953 NetworkRequest networkRequest;
1954 int expireSequenceNumber;
1955 Network currentNetwork;
1956 int delay = -1;
1957
1958 private void clearDnsBinding() {
1959 if (currentNetwork != null) {
1960 currentNetwork = null;
1961 setProcessDefaultNetworkForHostResolution(null);
1962 }
1963 }
1964
1965 NetworkCallback networkCallback = new NetworkCallback() {
1966 @Override
1967 public void onAvailable(Network network) {
1968 currentNetwork = network;
1969 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1970 setProcessDefaultNetworkForHostResolution(network);
1971 }
1972 @Override
1973 public void onLost(Network network) {
1974 if (network.equals(currentNetwork)) clearDnsBinding();
1975 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1976 }
1977 };
1978 }
1979
1980 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1981 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1982 new HashMap<>();
1983
1984 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1985 synchronized (sLegacyRequests) {
1986 LegacyRequest l = sLegacyRequests.get(netCap);
1987 if (l != null) return l.networkRequest;
1988 }
1989 return null;
1990 }
1991
1992 private void renewRequestLocked(LegacyRequest l) {
1993 l.expireSequenceNumber++;
1994 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1995 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1996 }
1997
1998 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1999 int ourSeqNum = -1;
2000 synchronized (sLegacyRequests) {
2001 LegacyRequest l = sLegacyRequests.get(netCap);
2002 if (l == null) return;
2003 ourSeqNum = l.expireSequenceNumber;
2004 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2005 }
2006 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2007 }
2008
2009 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2010 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2011 int delay = -1;
2012 int type = legacyTypeForNetworkCapabilities(netCap);
2013 try {
2014 delay = mService.getRestoreDefaultNetworkDelay(type);
2015 } catch (RemoteException e) {
2016 throw e.rethrowFromSystemServer();
2017 }
2018 LegacyRequest l = new LegacyRequest();
2019 l.networkCapabilities = netCap;
2020 l.delay = delay;
2021 l.expireSequenceNumber = 0;
2022 l.networkRequest = sendRequestForNetwork(
2023 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2024 if (l.networkRequest == null) return null;
2025 sLegacyRequests.put(netCap, l);
2026 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2027 return l.networkRequest;
2028 }
2029
2030 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2031 if (delay >= 0) {
2032 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2033 CallbackHandler handler = getDefaultHandler();
2034 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2035 handler.sendMessageDelayed(msg, delay);
2036 }
2037 }
2038
2039 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2040 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2041 final LegacyRequest l;
2042 synchronized (sLegacyRequests) {
2043 l = sLegacyRequests.remove(netCap);
2044 }
2045 if (l == null) return false;
2046 unregisterNetworkCallback(l.networkCallback);
2047 l.clearDnsBinding();
2048 return true;
2049 }
2050
2051 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2052 static {
2053 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2054 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2055 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2056 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2057 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2058 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2059 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2060 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2061 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2062 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2063 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2064 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2065 }
2066
2067 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2068 static {
2069 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2070 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2071 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2072 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2073 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2074 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2075 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2076 }
2077
2078 /**
2079 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2080 * instance suitable for registering a request or callback. Throws an
2081 * IllegalArgumentException if no mapping from the legacy type to
2082 * NetworkCapabilities is known.
2083 *
2084 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2085 * to find the network instead.
2086 * @hide
2087 */
2088 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2089 final NetworkCapabilities nc = new NetworkCapabilities();
2090
2091 // Map from type to transports.
2092 final int NOT_FOUND = -1;
2093 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002094 if (transport == NOT_FOUND) {
2095 throw new IllegalArgumentException("unknown legacy type: " + type);
2096 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002097 nc.addTransportType(transport);
2098
2099 // Map from type to capabilities.
2100 nc.addCapability(sLegacyTypeToCapability.get(
2101 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2102 nc.maybeMarkCapabilitiesRestricted();
2103 return nc;
2104 }
2105
2106 /** @hide */
2107 public static class PacketKeepaliveCallback {
2108 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2109 public PacketKeepaliveCallback() {
2110 }
2111 /** The requested keepalive was successfully started. */
2112 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2113 public void onStarted() {}
2114 /** The keepalive was successfully stopped. */
2115 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2116 public void onStopped() {}
2117 /** An error occurred. */
2118 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2119 public void onError(int error) {}
2120 }
2121
2122 /**
2123 * Allows applications to request that the system periodically send specific packets on their
2124 * behalf, using hardware offload to save battery power.
2125 *
2126 * To request that the system send keepalives, call one of the methods that return a
2127 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2128 * passing in a non-null callback. If the callback is successfully started, the callback's
2129 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2130 * specifying one of the {@code ERROR_*} constants in this class.
2131 *
2132 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2133 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2134 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2135 *
2136 * @deprecated Use {@link SocketKeepalive} instead.
2137 *
2138 * @hide
2139 */
2140 public class PacketKeepalive {
2141
2142 private static final String TAG = "PacketKeepalive";
2143
2144 /** @hide */
2145 public static final int SUCCESS = 0;
2146
2147 /** @hide */
2148 public static final int NO_KEEPALIVE = -1;
2149
2150 /** @hide */
2151 public static final int BINDER_DIED = -10;
2152
2153 /** The specified {@code Network} is not connected. */
2154 public static final int ERROR_INVALID_NETWORK = -20;
2155 /** The specified IP addresses are invalid. For example, the specified source IP address is
2156 * not configured on the specified {@code Network}. */
2157 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2158 /** The requested port is invalid. */
2159 public static final int ERROR_INVALID_PORT = -22;
2160 /** The packet length is invalid (e.g., too long). */
2161 public static final int ERROR_INVALID_LENGTH = -23;
2162 /** The packet transmission interval is invalid (e.g., too short). */
2163 public static final int ERROR_INVALID_INTERVAL = -24;
2164
2165 /** The hardware does not support this request. */
2166 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2167 /** The hardware returned an error. */
2168 public static final int ERROR_HARDWARE_ERROR = -31;
2169
2170 /** The NAT-T destination port for IPsec */
2171 public static final int NATT_PORT = 4500;
2172
2173 /** The minimum interval in seconds between keepalive packet transmissions */
2174 public static final int MIN_INTERVAL = 10;
2175
2176 private final Network mNetwork;
2177 private final ISocketKeepaliveCallback mCallback;
2178 private final ExecutorService mExecutor;
2179
2180 private volatile Integer mSlot;
2181
2182 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2183 public void stop() {
2184 try {
2185 mExecutor.execute(() -> {
2186 try {
2187 if (mSlot != null) {
2188 mService.stopKeepalive(mNetwork, mSlot);
2189 }
2190 } catch (RemoteException e) {
2191 Log.e(TAG, "Error stopping packet keepalive: ", e);
2192 throw e.rethrowFromSystemServer();
2193 }
2194 });
2195 } catch (RejectedExecutionException e) {
2196 // The internal executor has already stopped due to previous event.
2197 }
2198 }
2199
2200 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002201 Objects.requireNonNull(network, "network cannot be null");
2202 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002203 mNetwork = network;
2204 mExecutor = Executors.newSingleThreadExecutor();
2205 mCallback = new ISocketKeepaliveCallback.Stub() {
2206 @Override
2207 public void onStarted(int slot) {
2208 final long token = Binder.clearCallingIdentity();
2209 try {
2210 mExecutor.execute(() -> {
2211 mSlot = slot;
2212 callback.onStarted();
2213 });
2214 } finally {
2215 Binder.restoreCallingIdentity(token);
2216 }
2217 }
2218
2219 @Override
2220 public void onStopped() {
2221 final long token = Binder.clearCallingIdentity();
2222 try {
2223 mExecutor.execute(() -> {
2224 mSlot = null;
2225 callback.onStopped();
2226 });
2227 } finally {
2228 Binder.restoreCallingIdentity(token);
2229 }
2230 mExecutor.shutdown();
2231 }
2232
2233 @Override
2234 public void onError(int error) {
2235 final long token = Binder.clearCallingIdentity();
2236 try {
2237 mExecutor.execute(() -> {
2238 mSlot = null;
2239 callback.onError(error);
2240 });
2241 } finally {
2242 Binder.restoreCallingIdentity(token);
2243 }
2244 mExecutor.shutdown();
2245 }
2246
2247 @Override
2248 public void onDataReceived() {
2249 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2250 // this callback when data is received.
2251 }
2252 };
2253 }
2254 }
2255
2256 /**
2257 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2258 *
2259 * @deprecated Use {@link #createSocketKeepalive} instead.
2260 *
2261 * @hide
2262 */
2263 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2264 public PacketKeepalive startNattKeepalive(
2265 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2266 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2267 final PacketKeepalive k = new PacketKeepalive(network, callback);
2268 try {
2269 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2270 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2271 } catch (RemoteException e) {
2272 Log.e(TAG, "Error starting packet keepalive: ", e);
2273 throw e.rethrowFromSystemServer();
2274 }
2275 return k;
2276 }
2277
2278 // Construct an invalid fd.
2279 private ParcelFileDescriptor createInvalidFd() {
2280 final int invalidFd = -1;
2281 return ParcelFileDescriptor.adoptFd(invalidFd);
2282 }
2283
2284 /**
2285 * Request that keepalives be started on a IPsec NAT-T socket.
2286 *
2287 * @param network The {@link Network} the socket is on.
2288 * @param socket The socket that needs to be kept alive.
2289 * @param source The source address of the {@link UdpEncapsulationSocket}.
2290 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2291 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2292 * must run callback sequentially, otherwise the order of callbacks cannot be
2293 * guaranteed.
2294 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2295 * changes. Must be extended by applications that use this API.
2296 *
2297 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2298 * given socket.
2299 **/
2300 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2301 @NonNull UdpEncapsulationSocket socket,
2302 @NonNull InetAddress source,
2303 @NonNull InetAddress destination,
2304 @NonNull @CallbackExecutor Executor executor,
2305 @NonNull Callback callback) {
2306 ParcelFileDescriptor dup;
2307 try {
2308 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2309 // which cannot be obtained by the app process.
2310 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2311 } catch (IOException ignored) {
2312 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2313 // ERROR_INVALID_SOCKET.
2314 dup = createInvalidFd();
2315 }
2316 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2317 destination, executor, callback);
2318 }
2319
2320 /**
2321 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2322 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2323 *
2324 * @param network The {@link Network} the socket is on.
2325 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2326 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2327 * from that port.
2328 * @param source The source address of the {@link UdpEncapsulationSocket}.
2329 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2330 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2331 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2332 * must run callback sequentially, otherwise the order of callbacks cannot be
2333 * guaranteed.
2334 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2335 * changes. Must be extended by applications that use this API.
2336 *
2337 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2338 * given socket.
2339 * @hide
2340 */
2341 @SystemApi
2342 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2343 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2344 @NonNull ParcelFileDescriptor pfd,
2345 @NonNull InetAddress source,
2346 @NonNull InetAddress destination,
2347 @NonNull @CallbackExecutor Executor executor,
2348 @NonNull Callback callback) {
2349 ParcelFileDescriptor dup;
2350 try {
2351 // TODO: Consider remove unnecessary dup.
2352 dup = pfd.dup();
2353 } catch (IOException ignored) {
2354 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2355 // ERROR_INVALID_SOCKET.
2356 dup = createInvalidFd();
2357 }
2358 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002359 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002360 }
2361
2362 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002363 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002364 *
2365 * @param network The {@link Network} the socket is on.
2366 * @param socket The socket that needs to be kept alive.
2367 * @param executor The executor on which callback will be invoked. This implementation assumes
2368 * the provided {@link Executor} runs the callbacks in sequence with no
2369 * concurrency. Failing this, no guarantee of correctness can be made. It is
2370 * the responsibility of the caller to ensure the executor provides this
2371 * guarantee. A simple way of creating such an executor is with the standard
2372 * tool {@code Executors.newSingleThreadExecutor}.
2373 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2374 * changes. Must be extended by applications that use this API.
2375 *
2376 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2377 * given socket.
2378 * @hide
2379 */
2380 @SystemApi
2381 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2382 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2383 @NonNull Socket socket,
2384 @NonNull Executor executor,
2385 @NonNull Callback callback) {
2386 ParcelFileDescriptor dup;
2387 try {
2388 dup = ParcelFileDescriptor.fromSocket(socket);
2389 } catch (UncheckedIOException ignored) {
2390 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2391 // ERROR_INVALID_SOCKET.
2392 dup = createInvalidFd();
2393 }
2394 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2395 }
2396
2397 /**
2398 * Ensure that a network route exists to deliver traffic to the specified
2399 * host via the specified network interface. An attempt to add a route that
2400 * already exists is ignored, but treated as successful.
2401 *
2402 * <p>This method requires the caller to hold either the
2403 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2404 * or the ability to modify system settings as determined by
2405 * {@link android.provider.Settings.System#canWrite}.</p>
2406 *
2407 * @param networkType the type of the network over which traffic to the specified
2408 * host is to be routed
2409 * @param hostAddress the IP address of the host to which the route is desired
2410 * @return {@code true} on success, {@code false} on failure
2411 *
2412 * @deprecated Deprecated in favor of the
2413 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2414 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2415 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2416 * throw {@code UnsupportedOperationException} if called.
2417 * @removed
2418 */
2419 @Deprecated
2420 public boolean requestRouteToHost(int networkType, int hostAddress) {
2421 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2422 }
2423
2424 /**
2425 * Ensure that a network route exists to deliver traffic to the specified
2426 * host via the specified network interface. An attempt to add a route that
2427 * already exists is ignored, but treated as successful.
2428 *
2429 * <p>This method requires the caller to hold either the
2430 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2431 * or the ability to modify system settings as determined by
2432 * {@link android.provider.Settings.System#canWrite}.</p>
2433 *
2434 * @param networkType the type of the network over which traffic to the specified
2435 * host is to be routed
2436 * @param hostAddress the IP address of the host to which the route is desired
2437 * @return {@code true} on success, {@code false} on failure
2438 * @hide
2439 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2440 * {@link #bindProcessToNetwork} API.
2441 */
2442 @Deprecated
2443 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002444 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002445 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2446 checkLegacyRoutingApiAccess();
2447 try {
2448 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2449 mContext.getOpPackageName(), getAttributionTag());
2450 } catch (RemoteException e) {
2451 throw e.rethrowFromSystemServer();
2452 }
2453 }
2454
2455 /**
2456 * @return the context's attribution tag
2457 */
2458 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2459 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002460 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002461 }
2462
2463 /**
2464 * Returns the value of the setting for background data usage. If false,
2465 * applications should not use the network if the application is not in the
2466 * foreground. Developers should respect this setting, and check the value
2467 * of this before performing any background data operations.
2468 * <p>
2469 * All applications that have background services that use the network
2470 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2471 * <p>
2472 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2473 * background data depends on several combined factors, and this method will
2474 * always return {@code true}. Instead, when background data is unavailable,
2475 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2476 *
2477 * @return Whether background data usage is allowed.
2478 */
2479 @Deprecated
2480 public boolean getBackgroundDataSetting() {
2481 // assume that background data is allowed; final authority is
2482 // NetworkInfo which may be blocked.
2483 return true;
2484 }
2485
2486 /**
2487 * Sets the value of the setting for background data usage.
2488 *
2489 * @param allowBackgroundData Whether an application should use data while
2490 * it is in the background.
2491 *
2492 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2493 * @see #getBackgroundDataSetting()
2494 * @hide
2495 */
2496 @Deprecated
2497 @UnsupportedAppUsage
2498 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2499 // ignored
2500 }
2501
2502 /**
2503 * @hide
2504 * @deprecated Talk to TelephonyManager directly
2505 */
2506 @Deprecated
2507 @UnsupportedAppUsage
2508 public boolean getMobileDataEnabled() {
2509 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2510 if (tm != null) {
2511 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2512 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2513 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2514 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2515 + " retVal=" + retVal);
2516 return retVal;
2517 }
2518 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2519 return false;
2520 }
2521
2522 /**
2523 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2524 * to find out when the system default network has gone in to a high power state.
2525 */
2526 public interface OnNetworkActiveListener {
2527 /**
2528 * Called on the main thread of the process to report that the current data network
2529 * has become active, and it is now a good time to perform any pending network
2530 * operations. Note that this listener only tells you when the network becomes
2531 * active; if at any other time you want to know whether it is active (and thus okay
2532 * to initiate network traffic), you can retrieve its instantaneous state with
2533 * {@link ConnectivityManager#isDefaultNetworkActive}.
2534 */
2535 void onNetworkActive();
2536 }
2537
Chiachang Wang2de41682021-09-23 10:46:03 +08002538 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002539 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2540 mNetworkActivityListeners = new ArrayMap<>();
2541
2542 /**
2543 * Start listening to reports when the system's default data network is active, meaning it is
2544 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2545 * to determine the current state of the system's default network after registering the
2546 * listener.
2547 * <p>
2548 * If the process default network has been set with
2549 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2550 * reflect the process's default, but the system default.
2551 *
2552 * @param l The listener to be told when the network is active.
2553 */
2554 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002555 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002556 @Override
2557 public void onNetworkActive() throws RemoteException {
2558 l.onNetworkActive();
2559 }
2560 };
2561
Chiachang Wang2de41682021-09-23 10:46:03 +08002562 synchronized (mNetworkActivityListeners) {
2563 try {
2564 mService.registerNetworkActivityListener(rl);
2565 mNetworkActivityListeners.put(l, rl);
2566 } catch (RemoteException e) {
2567 throw e.rethrowFromSystemServer();
2568 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002569 }
2570 }
2571
2572 /**
2573 * Remove network active listener previously registered with
2574 * {@link #addDefaultNetworkActiveListener}.
2575 *
2576 * @param l Previously registered listener.
2577 */
2578 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002579 synchronized (mNetworkActivityListeners) {
2580 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2581 if (rl == null) {
2582 throw new IllegalArgumentException("Listener was not registered.");
2583 }
2584 try {
2585 mService.unregisterNetworkActivityListener(rl);
2586 mNetworkActivityListeners.remove(l);
2587 } catch (RemoteException e) {
2588 throw e.rethrowFromSystemServer();
2589 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002590 }
2591 }
2592
2593 /**
2594 * Return whether the data network is currently active. An active network means that
2595 * it is currently in a high power state for performing data transmission. On some
2596 * types of networks, it may be expensive to move and stay in such a state, so it is
2597 * more power efficient to batch network traffic together when the radio is already in
2598 * this state. This method tells you whether right now is currently a good time to
2599 * initiate network traffic, as the network is already active.
2600 */
2601 public boolean isDefaultNetworkActive() {
2602 try {
lucaslin709eb842021-01-21 02:04:15 +08002603 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002604 } catch (RemoteException e) {
2605 throw e.rethrowFromSystemServer();
2606 }
2607 }
2608
2609 /**
2610 * {@hide}
2611 */
2612 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002613 this(context, service, true /* newStatic */);
2614 }
2615
2616 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002617 mContext = Objects.requireNonNull(context, "missing context");
2618 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002619 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2620 // different ConnectivityManager, but that's still OK considering its usage.
2621 if (sInstance == null && newStatic) {
2622 final Context appContext = mContext.getApplicationContext();
2623 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2624 // If the application context is null, we're either in the system process or
2625 // it's the application context very early in app initialization. In both these
2626 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2627 // service. http://b/27532714 .
2628 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2629 false /* newStatic */);
2630 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002631 }
2632
2633 /** {@hide} */
2634 @UnsupportedAppUsage
2635 public static ConnectivityManager from(Context context) {
2636 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2637 }
2638
2639 /** @hide */
2640 public NetworkRequest getDefaultRequest() {
2641 try {
2642 // This is not racy as the default request is final in ConnectivityService.
2643 return mService.getDefaultRequest();
2644 } catch (RemoteException e) {
2645 throw e.rethrowFromSystemServer();
2646 }
2647 }
2648
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002649 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002650 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002651 * happened.
2652 *
2653 * @return {@code true} iff the package is allowed to write settings.
2654 */
2655 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2656 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2657 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2658 boolean throwException) {
2659 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002660 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002661 }
2662
2663 /**
2664 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2665 * situations where a Context pointer is unavailable.
2666 * @hide
2667 */
2668 @Deprecated
2669 static ConnectivityManager getInstanceOrNull() {
2670 return sInstance;
2671 }
2672
2673 /**
2674 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2675 * situations where a Context pointer is unavailable.
2676 * @hide
2677 */
2678 @Deprecated
2679 @UnsupportedAppUsage
2680 private static ConnectivityManager getInstance() {
2681 if (getInstanceOrNull() == null) {
2682 throw new IllegalStateException("No ConnectivityManager yet constructed");
2683 }
2684 return getInstanceOrNull();
2685 }
2686
2687 /**
2688 * Get the set of tetherable, available interfaces. This list is limited by
2689 * device configuration and current interface existence.
2690 *
2691 * @return an array of 0 or more Strings of tetherable interface names.
2692 *
2693 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2694 * {@hide}
2695 */
2696 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2697 @UnsupportedAppUsage
2698 @Deprecated
2699 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002700 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002701 }
2702
2703 /**
2704 * Get the set of tethered interfaces.
2705 *
2706 * @return an array of 0 or more String of currently tethered interface names.
2707 *
2708 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2709 * {@hide}
2710 */
2711 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2712 @UnsupportedAppUsage
2713 @Deprecated
2714 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002715 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002716 }
2717
2718 /**
2719 * Get the set of interface names which attempted to tether but
2720 * failed. Re-attempting to tether may cause them to reset to the Tethered
2721 * state. Alternatively, causing the interface to be destroyed and recreated
2722 * may cause them to reset to the available state.
2723 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2724 * information on the cause of the errors.
2725 *
2726 * @return an array of 0 or more String indicating the interface names
2727 * which failed to tether.
2728 *
2729 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2730 * {@hide}
2731 */
2732 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2733 @UnsupportedAppUsage
2734 @Deprecated
2735 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002736 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002737 }
2738
2739 /**
2740 * Get the set of tethered dhcp ranges.
2741 *
2742 * @deprecated This method is not supported.
2743 * TODO: remove this function when all of clients are removed.
2744 * {@hide}
2745 */
2746 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2747 @Deprecated
2748 public String[] getTetheredDhcpRanges() {
2749 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2750 }
2751
2752 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002753 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002754 * on the interface, forward and NAT IP packets and forward DNS requests
2755 * to the best active upstream network interface. Note that if no upstream
2756 * IP network interface is available, dhcp will still run and traffic will be
2757 * allowed between the tethered devices and this device, though upstream net
2758 * access will of course fail until an upstream network interface becomes
2759 * active.
2760 *
2761 * <p>This method requires the caller to hold either the
2762 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2763 * or the ability to modify system settings as determined by
2764 * {@link android.provider.Settings.System#canWrite}.</p>
2765 *
2766 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2767 * and WifiStateMachine which need direct access. All other clients should use
2768 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2769 * logic.</p>
2770 *
2771 * @param iface the interface name to tether.
2772 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2773 * @deprecated Use {@link TetheringManager#startTethering} instead
2774 *
2775 * {@hide}
2776 */
2777 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2778 @Deprecated
2779 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002780 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002781 }
2782
2783 /**
2784 * Stop tethering the named interface.
2785 *
2786 * <p>This method requires the caller to hold either the
2787 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2788 * or the ability to modify system settings as determined by
2789 * {@link android.provider.Settings.System#canWrite}.</p>
2790 *
2791 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2792 * and WifiStateMachine which need direct access. All other clients should use
2793 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2794 * logic.</p>
2795 *
2796 * @param iface the interface name to untether.
2797 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2798 *
2799 * {@hide}
2800 */
2801 @UnsupportedAppUsage
2802 @Deprecated
2803 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002804 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002805 }
2806
2807 /**
2808 * Check if the device allows for tethering. It may be disabled via
2809 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2810 * due to device configuration.
2811 *
2812 * <p>If this app does not have permission to use this API, it will always
2813 * return false rather than throw an exception.</p>
2814 *
2815 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2816 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2817 *
2818 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2819 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2820 *
2821 * @return a boolean - {@code true} indicating Tethering is supported.
2822 *
2823 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2824 * {@hide}
2825 */
2826 @SystemApi
2827 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2828 android.Manifest.permission.WRITE_SETTINGS})
2829 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002830 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002831 }
2832
2833 /**
2834 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2835 *
2836 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2837 * @hide
2838 */
2839 @SystemApi
2840 @Deprecated
2841 public static abstract class OnStartTetheringCallback {
2842 /**
2843 * Called when tethering has been successfully started.
2844 */
2845 public void onTetheringStarted() {}
2846
2847 /**
2848 * Called when starting tethering failed.
2849 */
2850 public void onTetheringFailed() {}
2851 }
2852
2853 /**
2854 * Convenient overload for
2855 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2856 * handler to run on the current thread's {@link Looper}.
2857 *
2858 * @deprecated Use {@link TetheringManager#startTethering} instead.
2859 * @hide
2860 */
2861 @SystemApi
2862 @Deprecated
2863 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2864 public void startTethering(int type, boolean showProvisioningUi,
2865 final OnStartTetheringCallback callback) {
2866 startTethering(type, showProvisioningUi, callback, null);
2867 }
2868
2869 /**
2870 * Runs tether provisioning for the given type if needed and then starts tethering if
2871 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2872 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2873 * schedules tether provisioning re-checks if appropriate.
2874 *
2875 * @param type The type of tethering to start. Must be one of
2876 * {@link ConnectivityManager.TETHERING_WIFI},
2877 * {@link ConnectivityManager.TETHERING_USB}, or
2878 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2879 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2880 * is one. This should be true the first time this function is called and also any time
2881 * the user can see this UI. It gives users information from their carrier about the
2882 * check failing and how they can sign up for tethering if possible.
2883 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2884 * of the result of trying to tether.
2885 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
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, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002895 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002896
2897 final Executor executor = new Executor() {
2898 @Override
2899 public void execute(Runnable command) {
2900 if (handler == null) {
2901 command.run();
2902 } else {
2903 handler.post(command);
2904 }
2905 }
2906 };
2907
2908 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2909 @Override
2910 public void onTetheringStarted() {
2911 callback.onTetheringStarted();
2912 }
2913
2914 @Override
2915 public void onTetheringFailed(final int error) {
2916 callback.onTetheringFailed();
2917 }
2918 };
2919
2920 final TetheringRequest request = new TetheringRequest.Builder(type)
2921 .setShouldShowEntitlementUi(showProvisioningUi).build();
2922
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002923 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002924 }
2925
2926 /**
2927 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2928 * applicable.
2929 *
2930 * @param type The type of tethering to stop. Must be one of
2931 * {@link ConnectivityManager.TETHERING_WIFI},
2932 * {@link ConnectivityManager.TETHERING_USB}, or
2933 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2934 *
2935 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2936 * @hide
2937 */
2938 @SystemApi
2939 @Deprecated
2940 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2941 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002942 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002943 }
2944
2945 /**
2946 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2947 * upstream status.
2948 *
2949 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2950 * @hide
2951 */
2952 @SystemApi
2953 @Deprecated
2954 public abstract static class OnTetheringEventCallback {
2955
2956 /**
2957 * Called when tethering upstream changed. This can be called multiple times and can be
2958 * called any time.
2959 *
2960 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2961 * have any upstream.
2962 */
2963 public void onUpstreamChanged(@Nullable Network network) {}
2964 }
2965
2966 @GuardedBy("mTetheringEventCallbacks")
2967 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2968 mTetheringEventCallbacks = new ArrayMap<>();
2969
2970 /**
2971 * Start listening to tethering change events. Any new added callback will receive the last
2972 * tethering status right away. If callback is registered when tethering has no upstream or
2973 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2974 * with a null argument. The same callback object cannot be registered twice.
2975 *
2976 * @param executor the executor on which callback will be invoked.
2977 * @param callback the callback to be called when tethering has change events.
2978 *
2979 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2980 * @hide
2981 */
2982 @SystemApi
2983 @Deprecated
2984 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2985 public void registerTetheringEventCallback(
2986 @NonNull @CallbackExecutor Executor executor,
2987 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002988 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002989
2990 final TetheringEventCallback tetherCallback =
2991 new TetheringEventCallback() {
2992 @Override
2993 public void onUpstreamChanged(@Nullable Network network) {
2994 callback.onUpstreamChanged(network);
2995 }
2996 };
2997
2998 synchronized (mTetheringEventCallbacks) {
2999 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003000 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003001 }
3002 }
3003
3004 /**
3005 * Remove tethering event callback previously registered with
3006 * {@link #registerTetheringEventCallback}.
3007 *
3008 * @param callback previously registered callback.
3009 *
3010 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3011 * @hide
3012 */
3013 @SystemApi
3014 @Deprecated
3015 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3016 public void unregisterTetheringEventCallback(
3017 @NonNull final OnTetheringEventCallback callback) {
3018 Objects.requireNonNull(callback, "The callback must be non-null");
3019 synchronized (mTetheringEventCallbacks) {
3020 final TetheringEventCallback tetherCallback =
3021 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003022 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003023 }
3024 }
3025
3026
3027 /**
3028 * Get the list of regular expressions that define any tetherable
3029 * USB network interfaces. If USB tethering is not supported by the
3030 * device, this list should be empty.
3031 *
3032 * @return an array of 0 or more regular expression Strings defining
3033 * what interfaces are considered tetherable usb interfaces.
3034 *
3035 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3036 * {@hide}
3037 */
3038 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3039 @UnsupportedAppUsage
3040 @Deprecated
3041 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003042 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003043 }
3044
3045 /**
3046 * Get the list of regular expressions that define any tetherable
3047 * Wifi network interfaces. If Wifi tethering is not supported by the
3048 * device, this list should be empty.
3049 *
3050 * @return an array of 0 or more regular expression Strings defining
3051 * what interfaces are considered tetherable wifi interfaces.
3052 *
3053 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3054 * {@hide}
3055 */
3056 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3057 @UnsupportedAppUsage
3058 @Deprecated
3059 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003060 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003061 }
3062
3063 /**
3064 * Get the list of regular expressions that define any tetherable
3065 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3066 * device, this list should be empty.
3067 *
3068 * @return an array of 0 or more regular expression Strings defining
3069 * what interfaces are considered tetherable bluetooth interfaces.
3070 *
3071 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3072 *TetheringManager.TetheringInterfaceRegexps)} instead.
3073 * {@hide}
3074 */
3075 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3076 @UnsupportedAppUsage
3077 @Deprecated
3078 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003079 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003080 }
3081
3082 /**
3083 * Attempt to both alter the mode of USB and Tethering of USB. A
3084 * utility method to deal with some of the complexity of USB - will
3085 * attempt to switch to Rndis and subsequently tether the resulting
3086 * interface on {@code true} or turn off tethering and switch off
3087 * Rndis on {@code false}.
3088 *
3089 * <p>This method requires the caller to hold either the
3090 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3091 * or the ability to modify system settings as determined by
3092 * {@link android.provider.Settings.System#canWrite}.</p>
3093 *
3094 * @param enable a boolean - {@code true} to enable tethering
3095 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3096 * @deprecated Use {@link TetheringManager#startTethering} instead
3097 *
3098 * {@hide}
3099 */
3100 @UnsupportedAppUsage
3101 @Deprecated
3102 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003103 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003104 }
3105
3106 /**
3107 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3108 * {@hide}
3109 */
3110 @SystemApi
3111 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003112 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003113 /**
3114 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3115 * {@hide}
3116 */
3117 @Deprecated
3118 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3119 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3120 /**
3121 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3122 * {@hide}
3123 */
3124 @Deprecated
3125 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3126 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3127 /**
3128 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3129 * {@hide}
3130 */
3131 @Deprecated
3132 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3133 /**
3134 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3135 * {@hide}
3136 */
3137 @Deprecated
3138 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3139 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3140 /**
3141 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3142 * {@hide}
3143 */
3144 @Deprecated
3145 public static final int TETHER_ERROR_MASTER_ERROR =
3146 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3147 /**
3148 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3149 * {@hide}
3150 */
3151 @Deprecated
3152 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3153 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3154 /**
3155 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3156 * {@hide}
3157 */
3158 @Deprecated
3159 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3160 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3161 /**
3162 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3163 * {@hide}
3164 */
3165 @Deprecated
3166 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3167 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3168 /**
3169 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3170 * {@hide}
3171 */
3172 @Deprecated
3173 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3174 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3175 /**
3176 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3177 * {@hide}
3178 */
3179 @Deprecated
3180 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3181 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3182 /**
3183 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3184 * {@hide}
3185 */
3186 @SystemApi
3187 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003188 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003189 /**
3190 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3191 * {@hide}
3192 */
3193 @Deprecated
3194 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3195 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3196 /**
3197 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3198 * {@hide}
3199 */
3200 @SystemApi
3201 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003202 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003203
3204 /**
3205 * Get a more detailed error code after a Tethering or Untethering
3206 * request asynchronously failed.
3207 *
3208 * @param iface The name of the interface of interest
3209 * @return error The error code of the last error tethering or untethering the named
3210 * interface
3211 *
3212 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3213 * {@hide}
3214 */
3215 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3216 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3217 @Deprecated
3218 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003219 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003220 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3221 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3222 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3223 // instead.
3224 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3225 }
3226 return error;
3227 }
3228
3229 /** @hide */
3230 @Retention(RetentionPolicy.SOURCE)
3231 @IntDef(value = {
3232 TETHER_ERROR_NO_ERROR,
3233 TETHER_ERROR_PROVISION_FAILED,
3234 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3235 })
3236 public @interface EntitlementResultCode {
3237 }
3238
3239 /**
3240 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3241 * entitlement succeeded.
3242 *
3243 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3244 * @hide
3245 */
3246 @SystemApi
3247 @Deprecated
3248 public interface OnTetheringEntitlementResultListener {
3249 /**
3250 * Called to notify entitlement result.
3251 *
3252 * @param resultCode an int value of entitlement result. It may be one of
3253 * {@link #TETHER_ERROR_NO_ERROR},
3254 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3255 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3256 */
3257 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3258 }
3259
3260 /**
3261 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003262 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3263 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003264 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003265 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003266 * any reason will update the cached value.
3267 *
3268 * @param type the downstream type of tethering. Must be one of
3269 * {@link #TETHERING_WIFI},
3270 * {@link #TETHERING_USB}, or
3271 * {@link #TETHERING_BLUETOOTH}.
3272 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3273 * @param executor the executor on which callback will be invoked.
3274 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3275 * notify the caller of the result of entitlement check. The listener may be called zero
3276 * or one time.
3277 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3278 * {@hide}
3279 */
3280 @SystemApi
3281 @Deprecated
3282 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3283 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3284 @NonNull @CallbackExecutor Executor executor,
3285 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003286 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003287 ResultReceiver wrappedListener = new ResultReceiver(null) {
3288 @Override
3289 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003290 final long token = Binder.clearCallingIdentity();
3291 try {
3292 executor.execute(() -> {
3293 listener.onTetheringEntitlementResult(resultCode);
3294 });
3295 } finally {
3296 Binder.restoreCallingIdentity(token);
3297 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003298 }
3299 };
3300
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003301 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003302 showEntitlementUi);
3303 }
3304
3305 /**
3306 * Report network connectivity status. This is currently used only
3307 * to alter status bar UI.
3308 * <p>This method requires the caller to hold the permission
3309 * {@link android.Manifest.permission#STATUS_BAR}.
3310 *
3311 * @param networkType The type of network you want to report on
3312 * @param percentage The quality of the connection 0 is bad, 100 is good
3313 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3314 * {@hide}
3315 */
3316 public void reportInetCondition(int networkType, int percentage) {
3317 printStackTrace();
3318 try {
3319 mService.reportInetCondition(networkType, percentage);
3320 } catch (RemoteException e) {
3321 throw e.rethrowFromSystemServer();
3322 }
3323 }
3324
3325 /**
3326 * Report a problem network to the framework. This provides a hint to the system
3327 * that there might be connectivity problems on this network and may cause
3328 * the framework to re-evaluate network connectivity and/or switch to another
3329 * network.
3330 *
3331 * @param network The {@link Network} the application was attempting to use
3332 * or {@code null} to indicate the current default network.
3333 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3334 * working and non-working connectivity.
3335 */
3336 @Deprecated
3337 public void reportBadNetwork(@Nullable Network network) {
3338 printStackTrace();
3339 try {
3340 // One of these will be ignored because it matches system's current state.
3341 // The other will trigger the necessary reevaluation.
3342 mService.reportNetworkConnectivity(network, true);
3343 mService.reportNetworkConnectivity(network, false);
3344 } catch (RemoteException e) {
3345 throw e.rethrowFromSystemServer();
3346 }
3347 }
3348
3349 /**
3350 * Report to the framework whether a network has working connectivity.
3351 * This provides a hint to the system that a particular network is providing
3352 * working connectivity or not. In response the framework may re-evaluate
3353 * the network's connectivity and might take further action thereafter.
3354 *
3355 * @param network The {@link Network} the application was attempting to use
3356 * or {@code null} to indicate the current default network.
3357 * @param hasConnectivity {@code true} if the application was able to successfully access the
3358 * Internet using {@code network} or {@code false} if not.
3359 */
3360 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3361 printStackTrace();
3362 try {
3363 mService.reportNetworkConnectivity(network, hasConnectivity);
3364 } catch (RemoteException e) {
3365 throw e.rethrowFromSystemServer();
3366 }
3367 }
3368
3369 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003370 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003371 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003372 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3373 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3374 * accessing any network, regardless of what the settings for that network are.
3375 *
3376 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3377 * proxy is likely to break networking on multiple networks. This method is only meant
3378 * for device policy clients looking to do general internal filtering or similar use cases.
3379 *
chiachangwang9473c592022-07-15 02:25:52 +00003380 * @see #getGlobalProxy
3381 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003382 *
3383 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3384 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003385 * @hide
3386 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003387 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003388 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003389 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003390 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003391 try {
3392 mService.setGlobalProxy(p);
3393 } catch (RemoteException e) {
3394 throw e.rethrowFromSystemServer();
3395 }
3396 }
3397
3398 /**
3399 * Retrieve any network-independent global HTTP proxy.
3400 *
3401 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3402 * if no global HTTP proxy is set.
3403 * @hide
3404 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003405 @SystemApi(client = MODULE_LIBRARIES)
3406 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003407 public ProxyInfo getGlobalProxy() {
3408 try {
3409 return mService.getGlobalProxy();
3410 } catch (RemoteException e) {
3411 throw e.rethrowFromSystemServer();
3412 }
3413 }
3414
3415 /**
3416 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3417 * network-specific HTTP proxy. If {@code network} is null, the
3418 * network-specific proxy returned is the proxy of the default active
3419 * network.
3420 *
3421 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3422 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3423 * or when {@code network} is {@code null},
3424 * the {@code ProxyInfo} for the default active network. Returns
3425 * {@code null} when no proxy applies or the caller doesn't have
3426 * permission to use {@code network}.
3427 * @hide
3428 */
3429 public ProxyInfo getProxyForNetwork(Network network) {
3430 try {
3431 return mService.getProxyForNetwork(network);
3432 } catch (RemoteException e) {
3433 throw e.rethrowFromSystemServer();
3434 }
3435 }
3436
3437 /**
3438 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3439 * otherwise if this process is bound to a {@link Network} using
3440 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3441 * the default network's proxy is returned.
3442 *
3443 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3444 * HTTP proxy is active.
3445 */
3446 @Nullable
3447 public ProxyInfo getDefaultProxy() {
3448 return getProxyForNetwork(getBoundNetworkForProcess());
3449 }
3450
3451 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003452 * Returns whether the hardware supports the given network type.
3453 *
3454 * This doesn't indicate there is coverage or such a network is available, just whether the
3455 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3456 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003457 *
3458 * @param networkType The network type we'd like to check
3459 * @return {@code true} if supported, else {@code false}
3460 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3461 * @hide
3462 */
3463 @Deprecated
3464 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3465 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3466 public boolean isNetworkSupported(int networkType) {
3467 try {
3468 return mService.isNetworkSupported(networkType);
3469 } catch (RemoteException e) {
3470 throw e.rethrowFromSystemServer();
3471 }
3472 }
3473
3474 /**
3475 * Returns if the currently active data network is metered. A network is
3476 * classified as metered when the user is sensitive to heavy data usage on
3477 * that connection due to monetary costs, data limitations or
3478 * battery/performance issues. You should check this before doing large
3479 * data transfers, and warn the user or delay the operation until another
3480 * network is available.
3481 *
3482 * @return {@code true} if large transfers should be avoided, otherwise
3483 * {@code false}.
3484 */
3485 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3486 public boolean isActiveNetworkMetered() {
3487 try {
3488 return mService.isActiveNetworkMetered();
3489 } catch (RemoteException e) {
3490 throw e.rethrowFromSystemServer();
3491 }
3492 }
3493
3494 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003495 * Set sign in error notification to visible or invisible
3496 *
3497 * @hide
3498 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3499 */
3500 @Deprecated
3501 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3502 String action) {
3503 try {
3504 mService.setProvisioningNotificationVisible(visible, networkType, action);
3505 } catch (RemoteException e) {
3506 throw e.rethrowFromSystemServer();
3507 }
3508 }
3509
3510 /**
3511 * Set the value for enabling/disabling airplane mode
3512 *
3513 * @param enable whether to enable airplane mode or not
3514 *
3515 * @hide
3516 */
3517 @RequiresPermission(anyOf = {
3518 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3519 android.Manifest.permission.NETWORK_SETTINGS,
3520 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3521 android.Manifest.permission.NETWORK_STACK})
3522 @SystemApi
3523 public void setAirplaneMode(boolean enable) {
3524 try {
3525 mService.setAirplaneMode(enable);
3526 } catch (RemoteException e) {
3527 throw e.rethrowFromSystemServer();
3528 }
3529 }
3530
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003531 /**
3532 * Registers the specified {@link NetworkProvider}.
3533 * Each listener must only be registered once. The listener can be unregistered with
3534 * {@link #unregisterNetworkProvider}.
3535 *
3536 * @param provider the provider to register
3537 * @return the ID of the provider. This ID must be used by the provider when registering
3538 * {@link android.net.NetworkAgent}s.
3539 * @hide
3540 */
3541 @SystemApi
3542 @RequiresPermission(anyOf = {
3543 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3544 android.Manifest.permission.NETWORK_FACTORY})
3545 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3546 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3547 throw new IllegalStateException("NetworkProviders can only be registered once");
3548 }
3549
3550 try {
3551 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3552 provider.getName());
3553 provider.setProviderId(providerId);
3554 } catch (RemoteException e) {
3555 throw e.rethrowFromSystemServer();
3556 }
3557 return provider.getProviderId();
3558 }
3559
3560 /**
3561 * Unregisters the specified NetworkProvider.
3562 *
3563 * @param provider the provider to unregister
3564 * @hide
3565 */
3566 @SystemApi
3567 @RequiresPermission(anyOf = {
3568 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3569 android.Manifest.permission.NETWORK_FACTORY})
3570 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3571 try {
3572 mService.unregisterNetworkProvider(provider.getMessenger());
3573 } catch (RemoteException e) {
3574 throw e.rethrowFromSystemServer();
3575 }
3576 provider.setProviderId(NetworkProvider.ID_NONE);
3577 }
3578
Chalard Jeand1b498b2021-01-05 08:40:09 +09003579 /**
3580 * Register or update a network offer with ConnectivityService.
3581 *
3582 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003583 * them to networking requests made by apps or the system. A callback identifies an offer
3584 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3585 * score and the capabilities of the network it might be able to bring up ; these act as
3586 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003587 * provider.
3588 *
3589 * The provider is under no obligation to be able to bring up the network it offers at any
3590 * given time. Instead, this mechanism is meant to limit requests received by providers
3591 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3592 * the quality of the network satisfying a given request to their own offer.
3593 *
3594 * An offer can be updated by calling this again with the same callback object. This is
3595 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3596 * provider with the changes caused by the changes in the offer.
3597 *
3598 * @param provider The provider making this offer.
3599 * @param score The prospective score of the network.
3600 * @param caps The prospective capabilities of the network.
3601 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003602 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003603 */
3604 @RequiresPermission(anyOf = {
3605 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3606 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003607 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003608 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3609 @NonNull final INetworkOfferCallback callback) {
3610 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003611 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003612 Objects.requireNonNull(score, "null score"),
3613 Objects.requireNonNull(caps, "null caps"),
3614 Objects.requireNonNull(callback, "null callback"));
3615 } catch (RemoteException e) {
3616 throw e.rethrowFromSystemServer();
3617 }
3618 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003619
Chalard Jeand1b498b2021-01-05 08:40:09 +09003620 /**
3621 * Withdraw a network offer made with {@link #offerNetwork}.
3622 *
3623 * @param callback The callback passed at registration time. This must be the same object
3624 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003625 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003626 */
3627 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3628 try {
3629 mService.unofferNetwork(Objects.requireNonNull(callback));
3630 } catch (RemoteException e) {
3631 throw e.rethrowFromSystemServer();
3632 }
3633 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003634 /** @hide exposed via the NetworkProvider class. */
3635 @RequiresPermission(anyOf = {
3636 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3637 android.Manifest.permission.NETWORK_FACTORY})
3638 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3639 try {
3640 mService.declareNetworkRequestUnfulfillable(request);
3641 } catch (RemoteException e) {
3642 throw e.rethrowFromSystemServer();
3643 }
3644 }
3645
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003646 /**
3647 * @hide
3648 * Register a NetworkAgent with ConnectivityService.
3649 * @return Network corresponding to NetworkAgent.
3650 */
3651 @RequiresPermission(anyOf = {
3652 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3653 android.Manifest.permission.NETWORK_FACTORY})
3654 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003655 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3656 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003657 try {
3658 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3659 } catch (RemoteException e) {
3660 throw e.rethrowFromSystemServer();
3661 }
3662 }
3663
3664 /**
3665 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3666 * changes. Should be extended by applications wanting notifications.
3667 *
3668 * A {@code NetworkCallback} is registered by calling
3669 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3670 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3671 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3672 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3673 * A {@code NetworkCallback} should be registered at most once at any time.
3674 * A {@code NetworkCallback} that has been unregistered can be registered again.
3675 */
3676 public static class NetworkCallback {
3677 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003678 * No flags associated with this callback.
3679 * @hide
3680 */
3681 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003682
Roshan Piuse08bc182020-12-22 15:10:42 -08003683 /**
lucaslinc582d502022-01-27 09:07:00 +08003684 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3685 *
3686 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3687 * Prior to Android 12, this information is always returned to apps holding the appropriate
3688 * permission, possibly noting that the app has used location.
3689 * <p>In Android 12 and above, by default the sent objects do not contain any location
3690 * information, even if the app holds the necessary permissions, and the system does not
3691 * take note of location usage by the app. Apps can request that location information is
3692 * included, in which case the system will check location permission and the location
3693 * toggle state, and take note of location usage by the app if any such information is
3694 * returned.
3695 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003696 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3697 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3698 * <p>
3699 * These include:
3700 * <li> Some transport info instances (retrieved via
3701 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3702 * contain location sensitive information.
3703 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003704 * sensitive for wifi suggestor apps (i.e using
3705 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003706 * </p>
3707 * <p>
3708 * Note:
3709 * <li> Retrieving this location sensitive information (subject to app's location
3710 * permissions) will be noted by system. </li>
3711 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003712 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003713 */
Roshan Pius189d0092021-03-11 21:16:44 -08003714 // Note: Some existing fields which are location sensitive may still be included without
3715 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003716 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3717
3718 /** @hide */
3719 @Retention(RetentionPolicy.SOURCE)
3720 @IntDef(flag = true, prefix = "FLAG_", value = {
3721 FLAG_NONE,
3722 FLAG_INCLUDE_LOCATION_INFO
3723 })
3724 public @interface Flag { }
3725
3726 /**
3727 * All the valid flags for error checking.
3728 */
3729 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3730
3731 public NetworkCallback() {
3732 this(FLAG_NONE);
3733 }
3734
3735 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003736 if ((flags & VALID_FLAGS) != flags) {
3737 throw new IllegalArgumentException("Invalid flags");
3738 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003739 mFlags = flags;
3740 }
3741
3742 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003743 * Called when the framework connects to a new network to evaluate whether it satisfies this
3744 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3745 * callback. There is no guarantee that this new network will satisfy any requests, or that
3746 * the network will stay connected for longer than the time necessary to evaluate it.
3747 * <p>
3748 * Most applications <b>should not</b> act on this callback, and should instead use
3749 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3750 * the framework in properly evaluating the network &mdash; for example, an application that
3751 * can automatically log in to a captive portal without user intervention.
3752 *
3753 * @param network The {@link Network} of the network that is being evaluated.
3754 *
3755 * @hide
3756 */
3757 public void onPreCheck(@NonNull Network network) {}
3758
3759 /**
3760 * Called when the framework connects and has declared a new network ready for use.
3761 * This callback may be called more than once if the {@link Network} that is
3762 * satisfying the request changes.
3763 *
3764 * @param network The {@link Network} of the satisfying network.
3765 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3766 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3767 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3768 * @hide
3769 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003770 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003771 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003772 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003773 // Internally only this method is called when a new network is available, and
3774 // it calls the callback in the same way and order that older versions used
3775 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003776 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3777 onBlockedStatusChanged(network, blocked);
3778 }
3779
3780 /**
3781 * Legacy variant of onAvailable that takes a boolean blocked reason.
3782 *
3783 * This method has never been public API, but it's not final, so there may be apps that
3784 * implemented it and rely on it being called. Do our best not to break them.
3785 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3786 * this method is called. There does not seem to be a way to avoid this.
3787 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3788 *
3789 * @hide
3790 */
3791 public void onAvailable(@NonNull Network network,
3792 @NonNull NetworkCapabilities networkCapabilities,
3793 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003794 onAvailable(network);
3795 if (!networkCapabilities.hasCapability(
3796 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3797 onNetworkSuspended(network);
3798 }
3799 onCapabilitiesChanged(network, networkCapabilities);
3800 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003801 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003802 }
3803
3804 /**
3805 * Called when the framework connects and has declared a new network ready for use.
3806 *
3807 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3808 * be available at the same time, and onAvailable will be called for each of these as they
3809 * appear.
3810 *
3811 * <p>For callbacks registered with {@link #requestNetwork} and
3812 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3813 * is the new best network for this request and is now tracked by this callback ; this
3814 * callback will no longer receive method calls about other networks that may have been
3815 * passed to this method previously. The previously-best network may have disconnected, or
3816 * it may still be around and the newly-best network may simply be better.
3817 *
3818 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3819 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3820 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3821 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3822 *
3823 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3824 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3825 * this callback as this is prone to race conditions (there is no guarantee the objects
3826 * returned by these methods will be current). Instead, wait for a call to
3827 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3828 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3829 * to be well-ordered with respect to other callbacks.
3830 *
3831 * @param network The {@link Network} of the satisfying network.
3832 */
3833 public void onAvailable(@NonNull Network network) {}
3834
3835 /**
3836 * Called when the network is about to be lost, typically because there are no outstanding
3837 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3838 * with the new replacement network for graceful handover. This method is not guaranteed
3839 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3840 * network is suddenly disconnected.
3841 *
3842 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3843 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3844 * this callback as this is prone to race conditions ; calling these methods while in a
3845 * callback may return an outdated or even a null object.
3846 *
3847 * @param network The {@link Network} that is about to be lost.
3848 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3849 * connected for graceful handover; note that the network may still
3850 * suffer a hard loss at any time.
3851 */
3852 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3853
3854 /**
3855 * Called when a network disconnects or otherwise no longer satisfies this request or
3856 * callback.
3857 *
3858 * <p>If the callback was registered with requestNetwork() or
3859 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3860 * returned by onAvailable() when that network is lost and no other network satisfies
3861 * the criteria of the request.
3862 *
3863 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3864 * each network which no longer satisfies the criteria of the callback.
3865 *
3866 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3867 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3868 * this callback as this is prone to race conditions ; calling these methods while in a
3869 * callback may return an outdated or even a null object.
3870 *
3871 * @param network The {@link Network} lost.
3872 */
3873 public void onLost(@NonNull Network network) {}
3874
3875 /**
3876 * Called if no network is found within the timeout time specified in
3877 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3878 * requested network request cannot be fulfilled (whether or not a timeout was
3879 * specified). When this callback is invoked the associated
3880 * {@link NetworkRequest} will have already been removed and released, as if
3881 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3882 */
3883 public void onUnavailable() {}
3884
3885 /**
3886 * Called when the network corresponding to this request changes capabilities but still
3887 * satisfies the requested criteria.
3888 *
3889 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3890 * to be called immediately after {@link #onAvailable}.
3891 *
3892 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3893 * ConnectivityManager methods in this callback as this is prone to race conditions :
3894 * calling these methods while in a callback may return an outdated or even a null object.
3895 *
3896 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003897 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003898 * network.
3899 */
3900 public void onCapabilitiesChanged(@NonNull Network network,
3901 @NonNull NetworkCapabilities networkCapabilities) {}
3902
3903 /**
3904 * Called when the network corresponding to this request changes {@link LinkProperties}.
3905 *
3906 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3907 * to be called immediately after {@link #onAvailable}.
3908 *
3909 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3910 * ConnectivityManager methods in this callback as this is prone to race conditions :
3911 * calling these methods while in a callback may return an outdated or even a null object.
3912 *
3913 * @param network The {@link Network} whose link properties have changed.
3914 * @param linkProperties The new {@link LinkProperties} for this network.
3915 */
3916 public void onLinkPropertiesChanged(@NonNull Network network,
3917 @NonNull LinkProperties linkProperties) {}
3918
3919 /**
3920 * Called when the network the framework connected to for this request suspends data
3921 * transmission temporarily.
3922 *
3923 * <p>This generally means that while the TCP connections are still live temporarily
3924 * network data fails to transfer. To give a specific example, this is used on cellular
3925 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3926 * means read operations on sockets on this network will block once the buffers are
3927 * drained, and write operations will block once the buffers are full.
3928 *
3929 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3930 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3931 * this callback as this is prone to race conditions (there is no guarantee the objects
3932 * returned by these methods will be current).
3933 *
3934 * @hide
3935 */
3936 public void onNetworkSuspended(@NonNull Network network) {}
3937
3938 /**
3939 * Called when the network the framework connected to for this request
3940 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3941 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3942
3943 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3944 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3945 * this callback as this is prone to race conditions : calling these methods while in a
3946 * callback may return an outdated or even a null object.
3947 *
3948 * @hide
3949 */
3950 public void onNetworkResumed(@NonNull Network network) {}
3951
3952 /**
3953 * Called when access to the specified network is blocked or unblocked.
3954 *
3955 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3956 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3957 * this callback as this is prone to race conditions : calling these methods while in a
3958 * callback may return an outdated or even a null object.
3959 *
3960 * @param network The {@link Network} whose blocked status has changed.
3961 * @param blocked The blocked status of this {@link Network}.
3962 */
3963 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3964
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003965 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09003966 * Called when access to the specified network is blocked or unblocked, or the reason for
3967 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003968 *
3969 * If a NetworkCallback object implements this method,
3970 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
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 * @param network The {@link Network} whose blocked status has changed.
3978 * @param blocked The blocked status of this {@link Network}.
3979 * @hide
3980 */
3981 @SystemApi(client = MODULE_LIBRARIES)
3982 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3983 onBlockedStatusChanged(network, blocked != 0);
3984 }
3985
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003986 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08003987 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003988 }
3989
3990 /**
3991 * Constant error codes used by ConnectivityService to communicate about failures and errors
3992 * across a Binder boundary.
3993 * @hide
3994 */
3995 public interface Errors {
3996 int TOO_MANY_REQUESTS = 1;
3997 }
3998
3999 /** @hide */
4000 public static class TooManyRequestsException extends RuntimeException {}
4001
4002 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4003 switch (e.errorCode) {
4004 case Errors.TOO_MANY_REQUESTS:
4005 return new TooManyRequestsException();
4006 default:
4007 Log.w(TAG, "Unknown service error code " + e.errorCode);
4008 return new RuntimeException(e);
4009 }
4010 }
4011
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004012 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004013 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004014 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004015 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004016 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004017 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004018 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004019 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004020 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004021 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004022 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004023 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004024 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004025 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004026 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004027 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004028 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004029 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004030 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004031 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004032 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004033 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004034
4035 /** @hide */
4036 public static String getCallbackName(int whichCallback) {
4037 switch (whichCallback) {
4038 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4039 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4040 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4041 case CALLBACK_LOST: return "CALLBACK_LOST";
4042 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4043 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4044 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4045 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4046 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4047 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4048 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4049 default:
4050 return Integer.toString(whichCallback);
4051 }
4052 }
4053
4054 private class CallbackHandler extends Handler {
4055 private static final String TAG = "ConnectivityManager.CallbackHandler";
4056 private static final boolean DBG = false;
4057
4058 CallbackHandler(Looper looper) {
4059 super(looper);
4060 }
4061
4062 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004063 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004064 }
4065
4066 @Override
4067 public void handleMessage(Message message) {
4068 if (message.what == EXPIRE_LEGACY_REQUEST) {
4069 expireRequest((NetworkCapabilities) message.obj, message.arg1);
4070 return;
4071 }
4072
4073 final NetworkRequest request = getObject(message, NetworkRequest.class);
4074 final Network network = getObject(message, Network.class);
4075 final NetworkCallback callback;
4076 synchronized (sCallbacks) {
4077 callback = sCallbacks.get(request);
4078 if (callback == null) {
4079 Log.w(TAG,
4080 "callback not found for " + getCallbackName(message.what) + " message");
4081 return;
4082 }
4083 if (message.what == CALLBACK_UNAVAIL) {
4084 sCallbacks.remove(request);
4085 callback.networkRequest = ALREADY_UNREGISTERED;
4086 }
4087 }
4088 if (DBG) {
4089 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4090 }
4091
4092 switch (message.what) {
4093 case CALLBACK_PRECHECK: {
4094 callback.onPreCheck(network);
4095 break;
4096 }
4097 case CALLBACK_AVAILABLE: {
4098 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4099 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004100 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004101 break;
4102 }
4103 case CALLBACK_LOSING: {
4104 callback.onLosing(network, message.arg1);
4105 break;
4106 }
4107 case CALLBACK_LOST: {
4108 callback.onLost(network);
4109 break;
4110 }
4111 case CALLBACK_UNAVAIL: {
4112 callback.onUnavailable();
4113 break;
4114 }
4115 case CALLBACK_CAP_CHANGED: {
4116 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4117 callback.onCapabilitiesChanged(network, cap);
4118 break;
4119 }
4120 case CALLBACK_IP_CHANGED: {
4121 LinkProperties lp = getObject(message, LinkProperties.class);
4122 callback.onLinkPropertiesChanged(network, lp);
4123 break;
4124 }
4125 case CALLBACK_SUSPENDED: {
4126 callback.onNetworkSuspended(network);
4127 break;
4128 }
4129 case CALLBACK_RESUMED: {
4130 callback.onNetworkResumed(network);
4131 break;
4132 }
4133 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004134 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004135 }
4136 }
4137 }
4138
4139 private <T> T getObject(Message msg, Class<T> c) {
4140 return (T) msg.getData().getParcelable(c.getSimpleName());
4141 }
4142 }
4143
4144 private CallbackHandler getDefaultHandler() {
4145 synchronized (sCallbacks) {
4146 if (sCallbackHandler == null) {
4147 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4148 }
4149 return sCallbackHandler;
4150 }
4151 }
4152
4153 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4154 private static CallbackHandler sCallbackHandler;
4155
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004156 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4157 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4158 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004159 printStackTrace();
4160 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004161 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4162 throw new IllegalArgumentException("null NetworkCapabilities");
4163 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004164 final NetworkRequest request;
4165 final String callingPackageName = mContext.getOpPackageName();
4166 try {
4167 synchronized(sCallbacks) {
4168 if (callback.networkRequest != null
4169 && callback.networkRequest != ALREADY_UNREGISTERED) {
4170 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4171 // and requests (http://b/20701525).
4172 Log.e(TAG, "NetworkCallback was already registered");
4173 }
4174 Messenger messenger = new Messenger(handler);
4175 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004176 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004177 if (reqType == LISTEN) {
4178 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004179 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004180 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004181 } else {
4182 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004183 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4184 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004185 }
4186 if (request != null) {
4187 sCallbacks.put(request, callback);
4188 }
4189 callback.networkRequest = request;
4190 }
4191 } catch (RemoteException e) {
4192 throw e.rethrowFromSystemServer();
4193 } catch (ServiceSpecificException e) {
4194 throw convertServiceException(e);
4195 }
4196 return request;
4197 }
4198
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004199 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4200 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4201 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4202 legacyType, handler);
4203 }
4204
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004205 /**
4206 * Helper function to request a network with a particular legacy type.
4207 *
4208 * This API is only for use in internal system code that requests networks with legacy type and
4209 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4210 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4211 *
4212 * @param request {@link NetworkRequest} describing this request.
4213 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4214 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4215 * be a positive value (i.e. >0).
4216 * @param legacyType to specify the network type(#TYPE_*).
4217 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4218 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4219 * the callback must not be shared - it uniquely specifies this request.
4220 *
4221 * @hide
4222 */
4223 @SystemApi
4224 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4225 public void requestNetwork(@NonNull NetworkRequest request,
4226 int timeoutMs, int legacyType, @NonNull Handler handler,
4227 @NonNull NetworkCallback networkCallback) {
4228 if (legacyType == TYPE_NONE) {
4229 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4230 }
4231 CallbackHandler cbHandler = new CallbackHandler(handler);
4232 NetworkCapabilities nc = request.networkCapabilities;
4233 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4234 }
4235
4236 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004237 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004238 *
4239 * <p>This method will attempt to find the best network that matches the passed
4240 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4241 * criteria. The platform will evaluate which network is the best at its own discretion.
4242 * Throughput, latency, cost per byte, policy, user preference and other considerations
4243 * may be factored in the decision of what is considered the best network.
4244 *
4245 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4246 * matching this request, while always attempting to match the request to a better network if
4247 * possible. If a better match is found, the platform will switch this request to the now-best
4248 * network and inform the app of the newly best network by invoking
4249 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4250 * will not try to maintain any other network than the best one currently matching the request:
4251 * a network not matching any network request may be disconnected at any time.
4252 *
4253 * <p>For example, an application could use this method to obtain a connected cellular network
4254 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4255 * radio to consume additional power. Or, an application could inform the system that it wants
4256 * a network supporting sending MMSes and have the system let it know about the currently best
4257 * MMS-supporting network through the provided {@link NetworkCallback}.
4258 *
4259 * <p>The status of the request can be followed by listening to the various callbacks described
4260 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4261 * used to direct traffic to the network (although accessing some networks may be subject to
4262 * holding specific permissions). Callers will learn about the specific characteristics of the
4263 * network through
4264 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4265 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4266 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4267 * matching the request at any given time; therefore when a better network matching the request
4268 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4269 * with the new network after which no further updates are given about the previously-best
4270 * network, unless it becomes the best again at some later time. All callbacks are invoked
4271 * in order on the same thread, which by default is a thread created by the framework running
4272 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004273 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004274 * callbacks are invoked.
4275 *
4276 * <p>This{@link NetworkRequest} will live until released via
4277 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4278 * which point the system may let go of the network at any time.
4279 *
4280 * <p>A version of this method which takes a timeout is
4281 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4282 * wait for a limited amount of time for the network to become unavailable.
4283 *
4284 * <p>It is presently unsupported to request a network with mutable
4285 * {@link NetworkCapabilities} such as
4286 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4287 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4288 * as these {@code NetworkCapabilities} represent states that a particular
4289 * network may never attain, and whether a network will attain these states
4290 * is unknown prior to bringing up the network so the framework does not
4291 * know how to go about satisfying a request with these capabilities.
4292 *
4293 * <p>This method requires the caller to hold either the
4294 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4295 * or the ability to modify system settings as determined by
4296 * {@link android.provider.Settings.System#canWrite}.</p>
4297 *
4298 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4299 * number of outstanding requests to 100 per app (identified by their UID), shared with
4300 * all variants of this method, of {@link #registerNetworkCallback} as well as
4301 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4302 * Requesting a network with this method will count toward this limit. If this limit is
4303 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4304 * make sure to unregister the callbacks with
4305 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4306 *
4307 * @param request {@link NetworkRequest} describing this request.
4308 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4309 * the callback must not be shared - it uniquely specifies this request.
4310 * The callback is invoked on the default internal Handler.
4311 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4312 * @throws SecurityException if missing the appropriate permissions.
4313 * @throws RuntimeException if the app already has too many callbacks registered.
4314 */
4315 public void requestNetwork(@NonNull NetworkRequest request,
4316 @NonNull NetworkCallback networkCallback) {
4317 requestNetwork(request, networkCallback, getDefaultHandler());
4318 }
4319
4320 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004321 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004322 *
4323 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4324 * but runs all the callbacks on the passed Handler.
4325 *
4326 * <p>This method has the same permission requirements as
4327 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4328 * and throws the same exceptions in the same conditions.
4329 *
4330 * @param request {@link NetworkRequest} describing this request.
4331 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4332 * the callback must not be shared - it uniquely specifies this request.
4333 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4334 */
4335 public void requestNetwork(@NonNull NetworkRequest request,
4336 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4337 CallbackHandler cbHandler = new CallbackHandler(handler);
4338 NetworkCapabilities nc = request.networkCapabilities;
4339 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4340 }
4341
4342 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004343 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004344 * by a timeout.
4345 *
4346 * This function behaves identically to the non-timed-out version
4347 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4348 * is not found within the given time (in milliseconds) the
4349 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4350 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4351 * not have to be released if timed-out (it is automatically released). Unregistering a
4352 * request that timed out is not an error.
4353 *
4354 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4355 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4356 * for that purpose. Calling this method will attempt to bring up the requested network.
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 timeoutMs The time in milliseconds to attempt looking for a suitable network
4366 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4367 * be a positive value (i.e. >0).
4368 */
4369 public void requestNetwork(@NonNull NetworkRequest request,
4370 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4371 checkTimeout(timeoutMs);
4372 NetworkCapabilities nc = request.networkCapabilities;
4373 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4374 getDefaultHandler());
4375 }
4376
4377 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004378 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004379 * by a timeout.
4380 *
4381 * This method behaves identically to
4382 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4383 * on the passed Handler.
4384 *
4385 * <p>This method has the same permission requirements as
4386 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4387 * and throws the same exceptions in the same conditions.
4388 *
4389 * @param request {@link NetworkRequest} describing this request.
4390 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4391 * the callback must not be shared - it uniquely specifies this request.
4392 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4393 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4394 * before {@link NetworkCallback#onUnavailable} is called.
4395 */
4396 public void requestNetwork(@NonNull NetworkRequest request,
4397 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4398 checkTimeout(timeoutMs);
4399 CallbackHandler cbHandler = new CallbackHandler(handler);
4400 NetworkCapabilities nc = request.networkCapabilities;
4401 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4402 }
4403
4404 /**
4405 * The lookup key for a {@link Network} object included with the intent after
4406 * successfully finding a network for the applications request. Retrieve it with
4407 * {@link android.content.Intent#getParcelableExtra(String)}.
4408 * <p>
4409 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4410 * then you must get a ConnectivityManager instance before doing so.
4411 */
4412 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4413
4414 /**
4415 * The lookup key for a {@link NetworkRequest} object included with the intent after
4416 * successfully finding a network for the applications request. Retrieve it with
4417 * {@link android.content.Intent#getParcelableExtra(String)}.
4418 */
4419 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4420
4421
4422 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004423 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004424 *
4425 * This function behaves identically to the version that takes a NetworkCallback, but instead
4426 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4427 * the request may outlive the calling application and get called back when a suitable
4428 * network is found.
4429 * <p>
4430 * The operation is an Intent broadcast that goes to a broadcast receiver that
4431 * you registered with {@link Context#registerReceiver} or through the
4432 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4433 * <p>
4434 * The operation Intent is delivered with two extras, a {@link Network} typed
4435 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4436 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4437 * the original requests parameters. It is important to create a new,
4438 * {@link NetworkCallback} based request before completing the processing of the
4439 * Intent to reserve the network or it will be released shortly after the Intent
4440 * is processed.
4441 * <p>
4442 * If there is already a request for this Intent registered (with the equality of
4443 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4444 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4445 * <p>
4446 * The request may be released normally by calling
4447 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4448 * <p>It is presently unsupported to request a network with either
4449 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4450 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4451 * as these {@code NetworkCapabilities} represent states that a particular
4452 * network may never attain, and whether a network will attain these states
4453 * is unknown prior to bringing up the network so the framework does not
4454 * know how to go about satisfying a request with these capabilities.
4455 *
4456 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4457 * number of outstanding requests to 100 per app (identified by their UID), shared with
4458 * all variants of this method, of {@link #registerNetworkCallback} as well as
4459 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4460 * Requesting a network with this method will count toward this limit. If this limit is
4461 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4462 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4463 * or {@link #releaseNetworkRequest(PendingIntent)}.
4464 *
4465 * <p>This method requires the caller to hold either the
4466 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4467 * or the ability to modify system settings as determined by
4468 * {@link android.provider.Settings.System#canWrite}.</p>
4469 *
4470 * @param request {@link NetworkRequest} describing this request.
4471 * @param operation Action to perform when the network is available (corresponds
4472 * to the {@link NetworkCallback#onAvailable} call. Typically
4473 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4474 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4475 * @throws SecurityException if missing the appropriate permissions.
4476 * @throws RuntimeException if the app already has too many callbacks registered.
4477 */
4478 public void requestNetwork(@NonNull NetworkRequest request,
4479 @NonNull PendingIntent operation) {
4480 printStackTrace();
4481 checkPendingIntentNotNull(operation);
4482 try {
4483 mService.pendingRequestForNetwork(
4484 request.networkCapabilities, operation, mContext.getOpPackageName(),
4485 getAttributionTag());
4486 } catch (RemoteException e) {
4487 throw e.rethrowFromSystemServer();
4488 } catch (ServiceSpecificException e) {
4489 throw convertServiceException(e);
4490 }
4491 }
4492
4493 /**
4494 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4495 * <p>
4496 * This method has the same behavior as
4497 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4498 * releasing network resources and disconnecting.
4499 *
4500 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4501 * PendingIntent passed to
4502 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4503 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4504 */
4505 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4506 printStackTrace();
4507 checkPendingIntentNotNull(operation);
4508 try {
4509 mService.releasePendingNetworkRequest(operation);
4510 } catch (RemoteException e) {
4511 throw e.rethrowFromSystemServer();
4512 }
4513 }
4514
4515 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004516 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004517 }
4518
4519 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004520 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004521 }
4522
4523 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004524 if (timeoutMs <= 0) {
4525 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4526 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004527 }
4528
4529 /**
4530 * Registers to receive notifications about all networks which satisfy the given
4531 * {@link NetworkRequest}. The callbacks will continue to be called until
4532 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4533 * called.
4534 *
4535 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4536 * number of outstanding requests to 100 per app (identified by their UID), shared with
4537 * all variants of this method, of {@link #requestNetwork} as well as
4538 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4539 * Requesting a network with this method will count toward this limit. If this limit is
4540 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4541 * make sure to unregister the callbacks with
4542 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4543 *
4544 * @param request {@link NetworkRequest} describing this request.
4545 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4546 * networks change state.
4547 * The callback is invoked on the default internal Handler.
4548 * @throws RuntimeException if the app already has too many callbacks registered.
4549 */
4550 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4551 public void registerNetworkCallback(@NonNull NetworkRequest request,
4552 @NonNull NetworkCallback networkCallback) {
4553 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4554 }
4555
4556 /**
4557 * Registers to receive notifications about all networks which satisfy the given
4558 * {@link NetworkRequest}. The callbacks will continue to be called until
4559 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4560 * called.
4561 *
4562 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4563 * number of outstanding requests to 100 per app (identified by their UID), shared with
4564 * all variants of this method, of {@link #requestNetwork} as well as
4565 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4566 * Requesting a network with this method will count toward this limit. If this limit is
4567 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4568 * make sure to unregister the callbacks with
4569 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4570 *
4571 *
4572 * @param request {@link NetworkRequest} describing this request.
4573 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4574 * networks change state.
4575 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4576 * @throws RuntimeException if the app already has too many callbacks registered.
4577 */
4578 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4579 public void registerNetworkCallback(@NonNull NetworkRequest request,
4580 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4581 CallbackHandler cbHandler = new CallbackHandler(handler);
4582 NetworkCapabilities nc = request.networkCapabilities;
4583 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4584 }
4585
4586 /**
4587 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4588 * {@link NetworkRequest}.
4589 *
4590 * This function behaves identically to the version that takes a NetworkCallback, but instead
4591 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4592 * the request may outlive the calling application and get called back when a suitable
4593 * network is found.
4594 * <p>
4595 * The operation is an Intent broadcast that goes to a broadcast receiver that
4596 * you registered with {@link Context#registerReceiver} or through the
4597 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4598 * <p>
4599 * The operation Intent is delivered with two extras, a {@link Network} typed
4600 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4601 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4602 * the original requests parameters.
4603 * <p>
4604 * If there is already a request for this Intent registered (with the equality of
4605 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4606 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4607 * <p>
4608 * The request may be released normally by calling
4609 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4610 *
4611 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4612 * number of outstanding requests to 100 per app (identified by their UID), shared with
4613 * all variants of this method, of {@link #requestNetwork} as well as
4614 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4615 * Requesting a network with this method will count toward this limit. If this limit is
4616 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4617 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4618 * or {@link #releaseNetworkRequest(PendingIntent)}.
4619 *
4620 * @param request {@link NetworkRequest} describing this request.
4621 * @param operation Action to perform when the network is available (corresponds
4622 * to the {@link NetworkCallback#onAvailable} call. Typically
4623 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4624 * @throws RuntimeException if the app already has too many callbacks registered.
4625 */
4626 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4627 public void registerNetworkCallback(@NonNull NetworkRequest request,
4628 @NonNull PendingIntent operation) {
4629 printStackTrace();
4630 checkPendingIntentNotNull(operation);
4631 try {
4632 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004633 request.networkCapabilities, operation, mContext.getOpPackageName(),
4634 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004635 } catch (RemoteException e) {
4636 throw e.rethrowFromSystemServer();
4637 } catch (ServiceSpecificException e) {
4638 throw convertServiceException(e);
4639 }
4640 }
4641
4642 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004643 * Registers to receive notifications about changes in the application's default network. This
4644 * may be a physical network or a virtual network, such as a VPN that applies to the
4645 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004646 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4647 *
4648 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4649 * number of outstanding requests to 100 per app (identified by their UID), shared with
4650 * all variants of this method, of {@link #requestNetwork} as well as
4651 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4652 * Requesting a network with this method will count toward this limit. If this limit is
4653 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4654 * make sure to unregister the callbacks with
4655 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4656 *
4657 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004658 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004659 * The callback is invoked on the default internal Handler.
4660 * @throws RuntimeException if the app already has too many callbacks registered.
4661 */
4662 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4663 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4664 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4665 }
4666
4667 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004668 * Registers to receive notifications about changes in the application's default network. This
4669 * may be a physical network or a virtual network, such as a VPN that applies to the
4670 * application. The callbacks will continue to be called until either the application exits or
4671 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4672 *
4673 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4674 * number of outstanding requests to 100 per app (identified by their UID), shared with
4675 * all variants of this method, of {@link #requestNetwork} as well as
4676 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4677 * Requesting a network with this method will count toward this limit. If this limit is
4678 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4679 * make sure to unregister the callbacks with
4680 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4681 *
4682 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4683 * application's default network changes.
4684 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4685 * @throws RuntimeException if the app already has too many callbacks registered.
4686 */
4687 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4688 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4689 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004690 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004691 }
4692
4693 /**
4694 * Registers to receive notifications about changes in the default network for the specified
4695 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4696 * UID. The callbacks will continue to be called until either the application exits or
4697 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4698 *
4699 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4700 * number of outstanding requests to 100 per app (identified by their UID), shared with
4701 * all variants of this method, of {@link #requestNetwork} as well as
4702 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4703 * Requesting a network with this method will count toward this limit. If this limit is
4704 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4705 * make sure to unregister the callbacks with
4706 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4707 *
4708 * @param uid the UID for which to track default network changes.
4709 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4710 * UID's default network changes.
4711 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4712 * @throws RuntimeException if the app already has too many callbacks registered.
4713 * @hide
4714 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004715 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004716 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4717 @RequiresPermission(anyOf = {
4718 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4719 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004720 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004721 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004722 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004723 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004724 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4725 }
4726
4727 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004728 * Registers to receive notifications about changes in the system default network. The callbacks
4729 * will continue to be called until either the application exits or
4730 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4731 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004732 * This method should not be used to determine networking state seen by applications, because in
4733 * many cases, most or even all application traffic may not use the default network directly,
4734 * and traffic from different applications may go on different networks by default. As an
4735 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4736 * and not onto the system default network. Applications or system components desiring to do
4737 * determine network state as seen by applications should use other methods such as
4738 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4739 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004740 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4741 * number of outstanding requests to 100 per app (identified by their UID), shared with
4742 * all variants of this method, of {@link #requestNetwork} as well as
4743 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4744 * Requesting a network with this method will count toward this limit. If this limit is
4745 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4746 * make sure to unregister the callbacks with
4747 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4748 *
4749 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4750 * system default network changes.
4751 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4752 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004753 *
4754 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004755 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004756 @SystemApi(client = MODULE_LIBRARIES)
4757 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4758 @RequiresPermission(anyOf = {
4759 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4760 android.Manifest.permission.NETWORK_SETTINGS})
4761 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004762 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004763 CallbackHandler cbHandler = new CallbackHandler(handler);
4764 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004765 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004766 }
4767
4768 /**
junyulaibd123062021-03-15 11:48:48 +08004769 * Registers to receive notifications about the best matching network which satisfy the given
4770 * {@link NetworkRequest}. The callbacks will continue to be called until
4771 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4772 * called.
4773 *
4774 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4775 * number of outstanding requests to 100 per app (identified by their UID), shared with
4776 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4777 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4778 * Requesting a network with this method will count toward this limit. If this limit is
4779 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4780 * make sure to unregister the callbacks with
4781 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4782 *
4783 *
4784 * @param request {@link NetworkRequest} describing this request.
4785 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4786 * networks change state.
4787 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4788 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004789 */
junyulai5a5c99b2021-03-05 15:51:17 +08004790 @SuppressLint("ExecutorRegistration")
4791 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4792 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4793 final NetworkCapabilities nc = request.networkCapabilities;
4794 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004795 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004796 }
4797
4798 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004799 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4800 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4801 * network connection for updated bandwidth information. The caller will be notified via
4802 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4803 * method assumes that the caller has previously called
4804 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4805 * changes.
4806 *
4807 * @param network {@link Network} specifying which network you're interested.
4808 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4809 */
4810 public boolean requestBandwidthUpdate(@NonNull Network network) {
4811 try {
4812 return mService.requestBandwidthUpdate(network);
4813 } catch (RemoteException e) {
4814 throw e.rethrowFromSystemServer();
4815 }
4816 }
4817
4818 /**
4819 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4820 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4821 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09004822 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
4823 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004824 *
4825 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4826 * triggering it as soon as this call returns.
4827 *
4828 * @param networkCallback The {@link NetworkCallback} used when making the request.
4829 */
4830 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4831 printStackTrace();
4832 checkCallbackNotNull(networkCallback);
4833 final List<NetworkRequest> reqs = new ArrayList<>();
4834 // Find all requests associated to this callback and stop callback triggers immediately.
4835 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4836 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004837 if (networkCallback.networkRequest == null) {
4838 throw new IllegalArgumentException("NetworkCallback was not registered");
4839 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004840 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4841 Log.d(TAG, "NetworkCallback was already unregistered");
4842 return;
4843 }
4844 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4845 if (e.getValue() == networkCallback) {
4846 reqs.add(e.getKey());
4847 }
4848 }
4849 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4850 for (NetworkRequest r : reqs) {
4851 try {
4852 mService.releaseNetworkRequest(r);
4853 } catch (RemoteException e) {
4854 throw e.rethrowFromSystemServer();
4855 }
4856 // Only remove mapping if rpc was successful.
4857 sCallbacks.remove(r);
4858 }
4859 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4860 }
4861 }
4862
4863 /**
4864 * Unregisters a callback previously registered via
4865 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4866 *
4867 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4868 * PendingIntent passed to
4869 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4870 * Cannot be null.
4871 */
4872 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4873 releaseNetworkRequest(operation);
4874 }
4875
4876 /**
4877 * Informs the system whether it should switch to {@code network} regardless of whether it is
4878 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4879 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4880 * the system default network regardless of any other network that's currently connected. If
4881 * {@code always} is true, then the choice is remembered, so that the next time the user
4882 * connects to this network, the system will switch to it.
4883 *
4884 * @param network The network to accept.
4885 * @param accept Whether to accept the network even if unvalidated.
4886 * @param always Whether to remember this choice in the future.
4887 *
4888 * @hide
4889 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004890 @SystemApi(client = MODULE_LIBRARIES)
4891 @RequiresPermission(anyOf = {
4892 android.Manifest.permission.NETWORK_SETTINGS,
4893 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4894 android.Manifest.permission.NETWORK_STACK,
4895 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4896 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004897 try {
4898 mService.setAcceptUnvalidated(network, accept, always);
4899 } catch (RemoteException e) {
4900 throw e.rethrowFromSystemServer();
4901 }
4902 }
4903
4904 /**
4905 * Informs the system whether it should consider the network as validated even if it only has
4906 * partial connectivity. If {@code accept} is true, then the network will be considered as
4907 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4908 * is remembered, so that the next time the user connects to this network, the system will
4909 * switch to it.
4910 *
4911 * @param network The network to accept.
4912 * @param accept Whether to consider the network as validated even if it has partial
4913 * connectivity.
4914 * @param always Whether to remember this choice in the future.
4915 *
4916 * @hide
4917 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004918 @SystemApi(client = MODULE_LIBRARIES)
4919 @RequiresPermission(anyOf = {
4920 android.Manifest.permission.NETWORK_SETTINGS,
4921 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4922 android.Manifest.permission.NETWORK_STACK,
4923 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4924 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4925 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004926 try {
4927 mService.setAcceptPartialConnectivity(network, accept, always);
4928 } catch (RemoteException e) {
4929 throw e.rethrowFromSystemServer();
4930 }
4931 }
4932
4933 /**
4934 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4935 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4936 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4937 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4938 *
4939 * @param network The network to accept.
4940 *
4941 * @hide
4942 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004943 @SystemApi(client = MODULE_LIBRARIES)
4944 @RequiresPermission(anyOf = {
4945 android.Manifest.permission.NETWORK_SETTINGS,
4946 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4947 android.Manifest.permission.NETWORK_STACK,
4948 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4949 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004950 try {
4951 mService.setAvoidUnvalidated(network);
4952 } catch (RemoteException e) {
4953 throw e.rethrowFromSystemServer();
4954 }
4955 }
4956
4957 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09004958 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004959 *
4960 * @param timeMs The expired current time. The value should be set within a limited time from
4961 * now.
4962 *
4963 * @hide
4964 */
4965 public void setTestAllowBadWifiUntil(long timeMs) {
4966 try {
4967 mService.setTestAllowBadWifiUntil(timeMs);
4968 } catch (RemoteException e) {
4969 throw e.rethrowFromSystemServer();
4970 }
4971 }
4972
4973 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004974 * Requests that the system open the captive portal app on the specified network.
4975 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004976 * <p>This is to be used on networks where a captive portal was detected, as per
4977 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4978 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004979 * @param network The network to log into.
4980 *
4981 * @hide
4982 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004983 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4984 @RequiresPermission(anyOf = {
4985 android.Manifest.permission.NETWORK_SETTINGS,
4986 android.Manifest.permission.NETWORK_STACK,
4987 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4988 })
4989 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004990 try {
4991 mService.startCaptivePortalApp(network);
4992 } catch (RemoteException e) {
4993 throw e.rethrowFromSystemServer();
4994 }
4995 }
4996
4997 /**
4998 * Requests that the system open the captive portal app with the specified extras.
4999 *
5000 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5001 * corresponding permission.
5002 * @param network Network on which the captive portal was detected.
5003 * @param appExtras Extras to include in the app start intent.
5004 * @hide
5005 */
5006 @SystemApi
5007 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5008 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5009 try {
5010 mService.startCaptivePortalAppInternal(network, appExtras);
5011 } catch (RemoteException e) {
5012 throw e.rethrowFromSystemServer();
5013 }
5014 }
5015
5016 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005017 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005018 * @hide
5019 */
5020 @SystemApi
5021 @RequiresPermission(anyOf = {
5022 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5023 android.Manifest.permission.NETWORK_STACK})
5024 public boolean shouldAvoidBadWifi() {
5025 try {
5026 return mService.shouldAvoidBadWifi();
5027 } catch (RemoteException e) {
5028 throw e.rethrowFromSystemServer();
5029 }
5030 }
5031
5032 /**
5033 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5034 * time-sensitive user-facing operations when the system default network is temporarily
5035 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5036 * this method), and the operation should be infrequent to ensure that data usage is limited.
5037 *
5038 * An example of such an operation might be a time-sensitive foreground activity, such as a
5039 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5040 */
5041 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5042
5043 /**
5044 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5045 * a backup channel for traffic that is primarily going over another network.
5046 *
5047 * An example might be maintaining backup connections to peers or servers for the purpose of
5048 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5049 * on backup paths should be negligible compared to the traffic on the main path.
5050 */
5051 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5052
5053 /**
5054 * It is acceptable to use metered data to improve network latency and performance.
5055 */
5056 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5057
5058 /**
5059 * Return value to use for unmetered networks. On such networks we currently set all the flags
5060 * to true.
5061 * @hide
5062 */
5063 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5064 MULTIPATH_PREFERENCE_HANDOVER |
5065 MULTIPATH_PREFERENCE_RELIABILITY |
5066 MULTIPATH_PREFERENCE_PERFORMANCE;
5067
Aaron Huangcff22942021-05-27 16:31:26 +08005068 /** @hide */
5069 @Retention(RetentionPolicy.SOURCE)
5070 @IntDef(flag = true, value = {
5071 MULTIPATH_PREFERENCE_HANDOVER,
5072 MULTIPATH_PREFERENCE_RELIABILITY,
5073 MULTIPATH_PREFERENCE_PERFORMANCE,
5074 })
5075 public @interface MultipathPreference {
5076 }
5077
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005078 /**
5079 * Provides a hint to the calling application on whether it is desirable to use the
5080 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5081 * for multipath data transfer on this network when it is not the system default network.
5082 * Applications desiring to use multipath network protocols should call this method before
5083 * each such operation.
5084 *
5085 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005086 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005087 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005088 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005089 */
5090 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5091 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5092 try {
5093 return mService.getMultipathPreference(network);
5094 } catch (RemoteException e) {
5095 throw e.rethrowFromSystemServer();
5096 }
5097 }
5098
5099 /**
5100 * Resets all connectivity manager settings back to factory defaults.
5101 * @hide
5102 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005103 @SystemApi(client = MODULE_LIBRARIES)
5104 @RequiresPermission(anyOf = {
5105 android.Manifest.permission.NETWORK_SETTINGS,
5106 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005107 public void factoryReset() {
5108 try {
5109 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005110 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005111 } catch (RemoteException e) {
5112 throw e.rethrowFromSystemServer();
5113 }
5114 }
5115
5116 /**
5117 * Binds the current process to {@code network}. All Sockets created in the future
5118 * (and not explicitly bound via a bound SocketFactory from
5119 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5120 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5121 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5122 * work and all host name resolutions will fail. This is by design so an application doesn't
5123 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5124 * To clear binding pass {@code null} for {@code network}. Using individually bound
5125 * Sockets created by Network.getSocketFactory().createSocket() and
5126 * performing network-specific host name resolutions via
5127 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5128 * {@code bindProcessToNetwork}.
5129 *
5130 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5131 * the current binding.
5132 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5133 */
5134 public boolean bindProcessToNetwork(@Nullable Network network) {
5135 // Forcing callers to call through non-static function ensures ConnectivityManager
5136 // instantiated.
5137 return setProcessDefaultNetwork(network);
5138 }
5139
5140 /**
5141 * Binds the current process to {@code network}. All Sockets created in the future
5142 * (and not explicitly bound via a bound SocketFactory from
5143 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5144 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5145 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5146 * work and all host name resolutions will fail. This is by design so an application doesn't
5147 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5148 * To clear binding pass {@code null} for {@code network}. Using individually bound
5149 * Sockets created by Network.getSocketFactory().createSocket() and
5150 * performing network-specific host name resolutions via
5151 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5152 * {@code setProcessDefaultNetwork}.
5153 *
5154 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5155 * the current binding.
5156 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5157 * @deprecated This function can throw {@link IllegalStateException}. Use
5158 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5159 * is a direct replacement.
5160 */
5161 @Deprecated
5162 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5163 int netId = (network == null) ? NETID_UNSET : network.netId;
5164 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5165
5166 if (netId != NETID_UNSET) {
5167 netId = network.getNetIdForResolv();
5168 }
5169
5170 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5171 return false;
5172 }
5173
5174 if (!isSameNetId) {
5175 // Set HTTP proxy system properties to match network.
5176 // TODO: Deprecate this static method and replace it with a non-static version.
5177 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005178 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005179 } catch (SecurityException e) {
5180 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5181 Log.e(TAG, "Can't set proxy properties", e);
5182 }
5183 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005184 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005185 // Must flush socket pool as idle sockets will be bound to previous network and may
5186 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005187 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005188 }
5189
5190 return true;
5191 }
5192
5193 /**
5194 * Returns the {@link Network} currently bound to this process via
5195 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5196 *
5197 * @return {@code Network} to which this process is bound, or {@code null}.
5198 */
5199 @Nullable
5200 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005201 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005202 // instantiated.
5203 return getProcessDefaultNetwork();
5204 }
5205
5206 /**
5207 * Returns the {@link Network} currently bound to this process via
5208 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5209 *
5210 * @return {@code Network} to which this process is bound, or {@code null}.
5211 * @deprecated Using this function can lead to other functions throwing
5212 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5213 * {@code getBoundNetworkForProcess} is a direct replacement.
5214 */
5215 @Deprecated
5216 @Nullable
5217 public static Network getProcessDefaultNetwork() {
5218 int netId = NetworkUtils.getBoundNetworkForProcess();
5219 if (netId == NETID_UNSET) return null;
5220 return new Network(netId);
5221 }
5222
5223 private void unsupportedStartingFrom(int version) {
5224 if (Process.myUid() == Process.SYSTEM_UID) {
5225 // The getApplicationInfo() call we make below is not supported in system context. Let
5226 // the call through here, and rely on the fact that ConnectivityService will refuse to
5227 // allow the system to use these APIs anyway.
5228 return;
5229 }
5230
5231 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5232 throw new UnsupportedOperationException(
5233 "This method is not supported in target SDK version " + version + " and above");
5234 }
5235 }
5236
5237 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5238 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5239 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5240 // remove these exemptions. Note that this check is not secure, and apps can still access these
5241 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5242 // so is unsupported and may break in the future. http://b/22728205
5243 private void checkLegacyRoutingApiAccess() {
5244 unsupportedStartingFrom(VERSION_CODES.M);
5245 }
5246
5247 /**
5248 * Binds host resolutions performed by this process to {@code network}.
5249 * {@link #bindProcessToNetwork} takes precedence over this setting.
5250 *
5251 * @param network The {@link Network} to bind host resolutions from the current process to, or
5252 * {@code null} to clear the current binding.
5253 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5254 * @hide
5255 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5256 */
5257 @Deprecated
5258 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5259 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5260 return NetworkUtils.bindProcessToNetworkForHostResolution(
5261 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5262 }
5263
5264 /**
5265 * Device is not restricting metered network activity while application is running on
5266 * background.
5267 */
5268 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5269
5270 /**
5271 * Device is restricting metered network activity while application is running on background,
5272 * but application is allowed to bypass it.
5273 * <p>
5274 * In this state, application should take action to mitigate metered network access.
5275 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5276 */
5277 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5278
5279 /**
5280 * Device is restricting metered network activity while application is running on background.
5281 * <p>
5282 * In this state, application should not try to use the network while running on background,
5283 * because it would be denied.
5284 */
5285 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5286
5287 /**
5288 * A change in the background metered network activity restriction has occurred.
5289 * <p>
5290 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5291 * applies to them.
5292 * <p>
5293 * This is only sent to registered receivers, not manifest receivers.
5294 */
5295 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5296 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5297 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5298
Aaron Huangcff22942021-05-27 16:31:26 +08005299 /** @hide */
5300 @Retention(RetentionPolicy.SOURCE)
5301 @IntDef(flag = false, value = {
5302 RESTRICT_BACKGROUND_STATUS_DISABLED,
5303 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5304 RESTRICT_BACKGROUND_STATUS_ENABLED,
5305 })
5306 public @interface RestrictBackgroundStatus {
5307 }
5308
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005309 /**
5310 * Determines if the calling application is subject to metered network restrictions while
5311 * running on background.
5312 *
5313 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5314 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5315 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5316 */
5317 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5318 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005319 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005320 } catch (RemoteException e) {
5321 throw e.rethrowFromSystemServer();
5322 }
5323 }
5324
5325 /**
5326 * The network watchlist is a list of domains and IP addresses that are associated with
5327 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5328 * currently used by the system for validation purposes.
5329 *
5330 * @return Hash of network watchlist config file. Null if config does not exist.
5331 */
5332 @Nullable
5333 public byte[] getNetworkWatchlistConfigHash() {
5334 try {
5335 return mService.getNetworkWatchlistConfigHash();
5336 } catch (RemoteException e) {
5337 Log.e(TAG, "Unable to get watchlist config hash");
5338 throw e.rethrowFromSystemServer();
5339 }
5340 }
5341
5342 /**
5343 * Returns the {@code uid} of the owner of a network connection.
5344 *
5345 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5346 * IPPROTO_UDP} currently supported.
5347 * @param local The local {@link InetSocketAddress} of a connection.
5348 * @param remote The remote {@link InetSocketAddress} of a connection.
5349 * @return {@code uid} if the connection is found and the app has permission to observe it
5350 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5351 * android.os.Process#INVALID_UID} if the connection is not found.
5352 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5353 * user.
5354 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5355 */
5356 public int getConnectionOwnerUid(
5357 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5358 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5359 try {
5360 return mService.getConnectionOwnerUid(connectionInfo);
5361 } catch (RemoteException e) {
5362 throw e.rethrowFromSystemServer();
5363 }
5364 }
5365
5366 private void printStackTrace() {
5367 if (DEBUG) {
5368 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5369 final StringBuffer sb = new StringBuffer();
5370 for (int i = 3; i < callStack.length; i++) {
5371 final String stackTrace = callStack[i].toString();
5372 if (stackTrace == null || stackTrace.contains("android.os")) {
5373 break;
5374 }
5375 sb.append(" [").append(stackTrace).append("]");
5376 }
5377 Log.d(TAG, "StackLog:" + sb.toString());
5378 }
5379 }
5380
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005381 /** @hide */
5382 public TestNetworkManager startOrGetTestNetworkManager() {
5383 final IBinder tnBinder;
5384 try {
5385 tnBinder = mService.startOrGetTestNetworkService();
5386 } catch (RemoteException e) {
5387 throw e.rethrowFromSystemServer();
5388 }
5389
5390 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5391 }
5392
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005393 /** @hide */
5394 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5395 return new ConnectivityDiagnosticsManager(mContext, mService);
5396 }
5397
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005398 /**
5399 * Simulates a Data Stall for the specified Network.
5400 *
5401 * <p>This method should only be used for tests.
5402 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005403 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5404 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005405 *
5406 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005407 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5408 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5409 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005410 * @param network The Network for which a Data Stall is being simluated.
5411 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5412 * @throws SecurityException if the caller is not the owner of the given network.
5413 * @hide
5414 */
5415 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5416 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5417 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005418 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005419 @NonNull Network network, @NonNull PersistableBundle extras) {
5420 try {
5421 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5422 } catch (RemoteException e) {
5423 e.rethrowFromSystemServer();
5424 }
5425 }
5426
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005427 @NonNull
5428 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5429
5430 /**
5431 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5432 * receive available QoS events related to the {@link Network} and local ip + port
5433 * specified within socketInfo.
5434 * <p/>
5435 * The same {@link QosCallback} must be unregistered before being registered a second time,
5436 * otherwise {@link QosCallbackRegistrationException} is thrown.
5437 * <p/>
5438 * This API does not, in itself, require any permission if called with a network that is not
5439 * restricted. However, the underlying implementation currently only supports the IMS network,
5440 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5441 * useful, because they'd never be called back on networks that they would have access to.
5442 *
5443 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5444 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5445 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5446 * @throws RuntimeException if the app already has too many callbacks registered.
5447 *
5448 * Exceptions after the time of registration is passed through
5449 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5450 *
5451 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005452 * @param executor The executor on which the callback will be invoked. The provided
5453 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005454 * callbacks cannot be guaranteed.onQosCallbackRegistered
5455 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005456 *
5457 * @hide
5458 */
5459 @SystemApi
5460 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005461 @CallbackExecutor @NonNull final Executor executor,
5462 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005463 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005464 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005465 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005466
5467 try {
5468 synchronized (mQosCallbackConnections) {
5469 if (getQosCallbackConnection(callback) == null) {
5470 final QosCallbackConnection connection =
5471 new QosCallbackConnection(this, callback, executor);
5472 mQosCallbackConnections.add(connection);
5473 mService.registerQosSocketCallback(socketInfo, connection);
5474 } else {
5475 Log.e(TAG, "registerQosCallback: Callback already registered");
5476 throw new QosCallbackRegistrationException();
5477 }
5478 }
5479 } catch (final RemoteException e) {
5480 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5481
5482 // The same unregister method method is called for consistency even though nothing
5483 // will be sent to the ConnectivityService since the callback was never successfully
5484 // registered.
5485 unregisterQosCallback(callback);
5486 e.rethrowFromSystemServer();
5487 } catch (final ServiceSpecificException e) {
5488 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5489 unregisterQosCallback(callback);
5490 throw convertServiceException(e);
5491 }
5492 }
5493
5494 /**
5495 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5496 * events once unregistered and can be registered a second time.
5497 * <p/>
5498 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5499 *
5500 * @param callback the callback being unregistered
5501 *
5502 * @hide
5503 */
5504 @SystemApi
5505 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5506 Objects.requireNonNull(callback, "The callback must be non-null");
5507 try {
5508 synchronized (mQosCallbackConnections) {
5509 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5510 if (connection != null) {
5511 connection.stopReceivingMessages();
5512 mService.unregisterQosCallback(connection);
5513 mQosCallbackConnections.remove(connection);
5514 } else {
5515 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5516 }
5517 }
5518 } catch (final RemoteException e) {
5519 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5520 e.rethrowFromSystemServer();
5521 }
5522 }
5523
5524 /**
5525 * Gets the connection related to the callback.
5526 *
5527 * @param callback the callback to look up
5528 * @return the related connection
5529 */
5530 @Nullable
5531 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5532 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5533 // Checking by reference here is intentional
5534 if (connection.getCallback() == callback) {
5535 return connection;
5536 }
5537 }
5538 return null;
5539 }
5540
5541 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005542 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005543 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5544 * be used to request that the system provide a network without causing the network to be
5545 * in the foreground.
5546 *
5547 * <p>This method will attempt to find the best network that matches the passed
5548 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5549 * criteria. The platform will evaluate which network is the best at its own discretion.
5550 * Throughput, latency, cost per byte, policy, user preference and other considerations
5551 * may be factored in the decision of what is considered the best network.
5552 *
5553 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5554 * matching this request, while always attempting to match the request to a better network if
5555 * possible. If a better match is found, the platform will switch this request to the now-best
5556 * network and inform the app of the newly best network by invoking
5557 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5558 * will not try to maintain any other network than the best one currently matching the request:
5559 * a network not matching any network request may be disconnected at any time.
5560 *
5561 * <p>For example, an application could use this method to obtain a connected cellular network
5562 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5563 * radio to consume additional power. Or, an application could inform the system that it wants
5564 * a network supporting sending MMSes and have the system let it know about the currently best
5565 * MMS-supporting network through the provided {@link NetworkCallback}.
5566 *
5567 * <p>The status of the request can be followed by listening to the various callbacks described
5568 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5569 * used to direct traffic to the network (although accessing some networks may be subject to
5570 * holding specific permissions). Callers will learn about the specific characteristics of the
5571 * network through
5572 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5573 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5574 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5575 * matching the request at any given time; therefore when a better network matching the request
5576 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5577 * with the new network after which no further updates are given about the previously-best
5578 * network, unless it becomes the best again at some later time. All callbacks are invoked
5579 * in order on the same thread, which by default is a thread created by the framework running
5580 * in the app.
5581 *
5582 * <p>This{@link NetworkRequest} will live until released via
5583 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5584 * which point the system may let go of the network at any time.
5585 *
5586 * <p>It is presently unsupported to request a network with mutable
5587 * {@link NetworkCapabilities} such as
5588 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5589 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5590 * as these {@code NetworkCapabilities} represent states that a particular
5591 * network may never attain, and whether a network will attain these states
5592 * is unknown prior to bringing up the network so the framework does not
5593 * know how to go about satisfying a request with these capabilities.
5594 *
5595 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5596 * number of outstanding requests to 100 per app (identified by their UID), shared with
5597 * all variants of this method, of {@link #registerNetworkCallback} as well as
5598 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5599 * Requesting a network with this method will count toward this limit. If this limit is
5600 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5601 * make sure to unregister the callbacks with
5602 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5603 *
5604 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005605 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5606 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005607 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5608 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005609 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5610 * @throws SecurityException if missing the appropriate permissions.
5611 * @throws RuntimeException if the app already has too many callbacks registered.
5612 *
5613 * @hide
5614 */
5615 @SystemApi(client = MODULE_LIBRARIES)
5616 @SuppressLint("ExecutorRegistration")
5617 @RequiresPermission(anyOf = {
5618 android.Manifest.permission.NETWORK_SETTINGS,
5619 android.Manifest.permission.NETWORK_STACK,
5620 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5621 })
5622 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005623 @NonNull NetworkCallback networkCallback,
5624 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005625 final NetworkCapabilities nc = request.networkCapabilities;
5626 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005627 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005628 }
James Mattis12aeab82021-01-10 14:24:24 -08005629
5630 /**
James Mattis12aeab82021-01-10 14:24:24 -08005631 * Used by automotive devices to set the network preferences used to direct traffic at an
5632 * application level as per the given OemNetworkPreferences. An example use-case would be an
5633 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5634 * vehicle via a particular network.
5635 *
5636 * Calling this will overwrite the existing preference.
5637 *
5638 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5639 * @param executor the executor on which listener will be invoked.
5640 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5641 * communicate completion of setOemNetworkPreference(). This will only be
5642 * called once upon successful completion of setOemNetworkPreference().
5643 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5644 * @throws SecurityException if missing the appropriate permissions.
5645 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005646 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005647 */
James Mattis6e2d7022021-01-26 16:23:52 -08005648 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005649 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005650 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005651 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005652 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005653 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5654 if (null != listener) {
5655 Objects.requireNonNull(executor, "Executor must be non-null");
5656 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005657 final IOnCompleteListener listenerInternal = listener == null ? null :
5658 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005659 @Override
5660 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005661 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005662 }
5663 };
5664
5665 try {
5666 mService.setOemNetworkPreference(preference, listenerInternal);
5667 } catch (RemoteException e) {
5668 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5669 throw e.rethrowFromSystemServer();
5670 }
5671 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005672
Chalard Jeanad565e22021-02-25 17:23:40 +09005673 /**
5674 * Request that a user profile is put by default on a network matching a given preference.
5675 *
5676 * See the documentation for the individual preferences for a description of the supported
5677 * behaviors.
5678 *
5679 * @param profile the profile concerned.
5680 * @param preference the preference for this profile.
5681 * @param executor an executor to execute the listener on. Optional if listener is null.
5682 * @param listener an optional listener to listen for completion of the operation.
5683 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5684 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005685 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5686 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005687 * @hide
5688 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005689 // This function is for establishing per-profile default networking and can only be called by
5690 // the device policy manager, running as the system server. It would make no sense to call it
5691 // on a context for a user because it does not establish a setting on behalf of a user, rather
5692 // it establishes a setting for a user on behalf of the DPM.
5693 @SuppressLint({"UserHandle"})
5694 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005695 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005696 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005697 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005698 @ProfileNetworkPreferencePolicy final int preference,
5699 @Nullable @CallbackExecutor final Executor executor,
5700 @Nullable final Runnable listener) {
5701
5702 ProfileNetworkPreference.Builder preferenceBuilder =
5703 new ProfileNetworkPreference.Builder();
5704 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005705 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5706 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5707 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005708 setProfileNetworkPreferences(profile,
5709 List.of(preferenceBuilder.build()), executor, listener);
5710 }
5711
5712 /**
5713 * Set a list of default network selection policies for a user profile.
5714 *
5715 * Calling this API with a user handle defines the entire policy for that user handle.
5716 * It will overwrite any setting previously set for the same user profile,
5717 * and not affect previously set settings for other handles.
5718 *
5719 * Call this API with an empty list to remove settings for this user profile.
5720 *
5721 * See {@link ProfileNetworkPreference} for more details on each preference
5722 * parameter.
5723 *
5724 * @param profile the user profile for which the preference is being set.
5725 * @param profileNetworkPreferences the list of profile network preferences for the
5726 * provided profile.
5727 * @param executor an executor to execute the listener on. Optional if listener is null.
5728 * @param listener an optional listener to listen for completion of the operation.
5729 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5730 * @throws SecurityException if missing the appropriate permissions.
5731 * @hide
5732 */
5733 @SystemApi(client = MODULE_LIBRARIES)
5734 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5735 public void setProfileNetworkPreferences(
5736 @NonNull final UserHandle profile,
5737 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005738 @Nullable @CallbackExecutor final Executor executor,
5739 @Nullable final Runnable listener) {
5740 if (null != listener) {
5741 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5742 }
5743 final IOnCompleteListener proxy;
5744 if (null == listener) {
5745 proxy = null;
5746 } else {
5747 proxy = new IOnCompleteListener.Stub() {
5748 @Override
5749 public void onComplete() {
5750 executor.execute(listener::run);
5751 }
5752 };
5753 }
5754 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005755 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005756 } catch (RemoteException e) {
5757 throw e.rethrowFromSystemServer();
5758 }
5759 }
5760
lucaslin5cdbcfb2021-03-12 00:46:33 +08005761 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005762 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005763 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005764 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005765
5766 /**
5767 * Get the network ID range reserved for IPSec tunnel interfaces.
5768 *
5769 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5770 * @hide
5771 */
5772 @SystemApi(client = MODULE_LIBRARIES)
5773 @NonNull
5774 public static Range<Integer> getIpSecNetIdRange() {
5775 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5776 }
markchien738ad912021-12-09 18:15:45 +08005777
5778 /**
markchiene46042b2022-03-02 18:07:35 +08005779 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5780 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005781 *
5782 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005783 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005784 * @hide
5785 */
5786 @SystemApi(client = MODULE_LIBRARIES)
5787 @RequiresPermission(anyOf = {
5788 android.Manifest.permission.NETWORK_SETTINGS,
5789 android.Manifest.permission.NETWORK_STACK,
5790 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5791 })
markchiene46042b2022-03-02 18:07:35 +08005792 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005793 try {
markchiene46042b2022-03-02 18:07:35 +08005794 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08005795 } catch (RemoteException e) {
5796 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005797 }
5798 }
5799
5800 /**
markchiene46042b2022-03-02 18:07:35 +08005801 * Removes the specified UID from the list of UIDs that are allowed to use background data on
5802 * metered networks when background data is restricted. The deny list takes precedence over
5803 * the allow list.
5804 *
5805 * @param uid uid of target app
5806 * @throws IllegalStateException if updating allow list failed.
5807 * @hide
5808 */
5809 @SystemApi(client = MODULE_LIBRARIES)
5810 @RequiresPermission(anyOf = {
5811 android.Manifest.permission.NETWORK_SETTINGS,
5812 android.Manifest.permission.NETWORK_STACK,
5813 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5814 })
5815 public void removeUidFromMeteredNetworkAllowList(final int uid) {
5816 try {
5817 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
5818 } catch (RemoteException e) {
5819 throw e.rethrowFromSystemServer();
5820 }
5821 }
5822
5823 /**
5824 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
5825 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08005826 *
5827 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005828 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08005829 * @hide
5830 */
5831 @SystemApi(client = MODULE_LIBRARIES)
5832 @RequiresPermission(anyOf = {
5833 android.Manifest.permission.NETWORK_SETTINGS,
5834 android.Manifest.permission.NETWORK_STACK,
5835 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5836 })
markchiene46042b2022-03-02 18:07:35 +08005837 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005838 try {
markchiene46042b2022-03-02 18:07:35 +08005839 mService.updateMeteredNetworkDenyList(uid, true /* add */);
5840 } catch (RemoteException e) {
5841 throw e.rethrowFromSystemServer();
5842 }
5843 }
5844
5845 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005846 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08005847 * networks if background data is not restricted. The deny list takes precedence over the
5848 * allow list.
5849 *
5850 * @param uid uid of target app
5851 * @throws IllegalStateException if updating deny list failed.
5852 * @hide
5853 */
5854 @SystemApi(client = MODULE_LIBRARIES)
5855 @RequiresPermission(anyOf = {
5856 android.Manifest.permission.NETWORK_SETTINGS,
5857 android.Manifest.permission.NETWORK_STACK,
5858 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5859 })
5860 public void removeUidFromMeteredNetworkDenyList(final int uid) {
5861 try {
5862 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08005863 } catch (RemoteException e) {
5864 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08005865 }
5866 }
5867
5868 /**
5869 * Sets a firewall rule for the specified UID on the specified chain.
5870 *
5871 * @param chain target chain.
5872 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08005873 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08005874 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08005875 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08005876 * @hide
5877 */
5878 @SystemApi(client = MODULE_LIBRARIES)
5879 @RequiresPermission(anyOf = {
5880 android.Manifest.permission.NETWORK_SETTINGS,
5881 android.Manifest.permission.NETWORK_STACK,
5882 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5883 })
markchien3c04e662022-03-22 16:29:56 +08005884 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
5885 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08005886 try {
markchien3c04e662022-03-22 16:29:56 +08005887 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08005888 } catch (RemoteException e) {
5889 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005890 }
5891 }
markchien98a6f952022-01-13 23:43:53 +08005892
5893 /**
5894 * Enables or disables the specified firewall chain.
5895 *
5896 * @param chain target chain.
5897 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00005898 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08005899 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08005900 * @hide
5901 */
5902 @SystemApi(client = MODULE_LIBRARIES)
5903 @RequiresPermission(anyOf = {
5904 android.Manifest.permission.NETWORK_SETTINGS,
5905 android.Manifest.permission.NETWORK_STACK,
5906 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5907 })
5908 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
5909 try {
5910 mService.setFirewallChainEnabled(chain, enable);
5911 } catch (RemoteException e) {
5912 throw e.rethrowFromSystemServer();
5913 }
5914 }
markchien00a0bed2022-01-13 23:46:13 +08005915
5916 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00005917 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00005918 *
5919 * @param chain target chain.
5920 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
5921 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00005922 * @throws ServiceSpecificException in case of failure, with an error code indicating the
5923 * cause of the failure.
5924 * @hide
5925 */
5926 @RequiresPermission(anyOf = {
5927 android.Manifest.permission.NETWORK_SETTINGS,
5928 android.Manifest.permission.NETWORK_STACK,
5929 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5930 })
5931 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
5932 try {
5933 return mService.getFirewallChainEnabled(chain);
5934 } catch (RemoteException e) {
5935 throw e.rethrowFromSystemServer();
5936 }
5937 }
5938
5939 /**
markchien00a0bed2022-01-13 23:46:13 +08005940 * Replaces the contents of the specified UID-based firewall chain.
5941 *
5942 * @param chain target chain to replace.
5943 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00005944 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08005945 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
5946 * @hide
5947 */
5948 @SystemApi(client = MODULE_LIBRARIES)
5949 @RequiresPermission(anyOf = {
5950 android.Manifest.permission.NETWORK_SETTINGS,
5951 android.Manifest.permission.NETWORK_STACK,
5952 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5953 })
5954 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
5955 Objects.requireNonNull(uids);
5956 try {
5957 mService.replaceFirewallChain(chain, uids);
5958 } catch (RemoteException e) {
5959 throw e.rethrowFromSystemServer();
5960 }
5961 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005962}