blob: 0a05d430827c3883eb1a706f3dc54a8e2b412d76 [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
559 * appropriate network. {@see NetworkCapabilities} for supported transports.
560 */
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
569 * appropriate network. {@see NetworkCapabilities} for supported transports.
570 */
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
620 * appropriate network. {@see NetworkCapabilities} for supported transports.
621 */
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
630 * appropriate network. {@see NetworkCapabilities} for supported transports.
631 */
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
640 * appropriate network. {@see NetworkCapabilities} for supported transports.
641 */
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
657 * appropriate network. {@see NetworkCapabilities} for supported transports.
658 */
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 Utsumi966ff7f2022-05-11 05:56:26 +0000985 /**
986 * Firewall chain used for lockdown VPN.
987 * Denylist of apps that cannot receive incoming packets except on loopback because they are
988 * subject to an always-on VPN which is not currently connected.
989 *
990 * @see #BLOCKED_REASON_LOCKDOWN_VPN
991 * @hide
992 */
993 public static final int FIREWALL_CHAIN_LOCKDOWN_VPN = 6;
994
Motomu Utsumi9cd47262022-06-01 13:57:27 +0000995 /**
996 * Firewall chain used for OEM-specific application restrictions.
997 * Denylist of apps that will not have network access due to OEM-specific restrictions.
998 * @hide
999 */
1000 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1001
1002 /**
1003 * Firewall chain used for OEM-specific application restrictions.
1004 * Denylist of apps that will not have network access due to OEM-specific restrictions.
1005 * @hide
1006 */
1007 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1008
Motomu Utsumi608015f2022-06-06 07:44:05 +00001009 /**
1010 * Firewall chain used for OEM-specific application restrictions.
1011 * Denylist of apps that will not have network access due to OEM-specific restrictions.
1012 * @hide
1013 */
1014 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1015
markchiene1561fa2021-12-09 22:00:56 +08001016 /** @hide */
1017 @Retention(RetentionPolicy.SOURCE)
1018 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1019 FIREWALL_CHAIN_DOZABLE,
1020 FIREWALL_CHAIN_STANDBY,
1021 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001022 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumi966ff7f2022-05-11 05:56:26 +00001023 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Motomu Utsumi9cd47262022-06-01 13:57:27 +00001024 FIREWALL_CHAIN_LOCKDOWN_VPN,
1025 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi608015f2022-06-06 07:44:05 +00001026 FIREWALL_CHAIN_OEM_DENY_2,
1027 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001028 })
1029 public @interface FirewallChain {}
Robert Horvathd945bf02022-01-27 19:55:16 +01001030 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
markchiene1561fa2021-12-09 22:00:56 +08001031
1032 /**
markchien011a7f52022-03-29 01:07:22 +08001033 * A firewall rule which allows or drops packets depending on existing policy.
1034 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1035 * 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_DEFAULT = 0;
1040
1041 /**
markchien011a7f52022-03-29 01:07:22 +08001042 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1043 * allow 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_ALLOW = 1;
1048
1049 /**
markchien011a7f52022-03-29 01:07:22 +08001050 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1051 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001052 * @hide
1053 */
1054 @SystemApi(client = MODULE_LIBRARIES)
1055 public static final int FIREWALL_RULE_DENY = 2;
1056
1057 /** @hide */
1058 @Retention(RetentionPolicy.SOURCE)
1059 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1060 FIREWALL_RULE_DEFAULT,
1061 FIREWALL_RULE_ALLOW,
1062 FIREWALL_RULE_DENY
1063 })
1064 public @interface FirewallRule {}
1065
1066 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001067 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1068 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1069 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1070 * methods that take a Context argument.
1071 */
1072 private static ConnectivityManager sInstance;
1073
1074 private final Context mContext;
1075
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001076 @GuardedBy("mTetheringEventCallbacks")
1077 private TetheringManager mTetheringManager;
1078
1079 private TetheringManager getTetheringManager() {
1080 synchronized (mTetheringEventCallbacks) {
1081 if (mTetheringManager == null) {
1082 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1083 }
1084 return mTetheringManager;
1085 }
1086 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001087
1088 /**
1089 * Tests if a given integer represents a valid network type.
1090 * @param networkType the type to be tested
1091 * @return a boolean. {@code true} if the type is valid, else {@code false}
1092 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1093 * validate a network type.
1094 */
1095 @Deprecated
1096 public static boolean isNetworkTypeValid(int networkType) {
1097 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1098 }
1099
1100 /**
1101 * Returns a non-localized string representing a given network type.
1102 * ONLY used for debugging output.
1103 * @param type the type needing naming
1104 * @return a String for the given type, or a string version of the type ("87")
1105 * if no name is known.
1106 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1107 * {@hide}
1108 */
1109 @Deprecated
1110 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1111 public static String getNetworkTypeName(int type) {
1112 switch (type) {
1113 case TYPE_NONE:
1114 return "NONE";
1115 case TYPE_MOBILE:
1116 return "MOBILE";
1117 case TYPE_WIFI:
1118 return "WIFI";
1119 case TYPE_MOBILE_MMS:
1120 return "MOBILE_MMS";
1121 case TYPE_MOBILE_SUPL:
1122 return "MOBILE_SUPL";
1123 case TYPE_MOBILE_DUN:
1124 return "MOBILE_DUN";
1125 case TYPE_MOBILE_HIPRI:
1126 return "MOBILE_HIPRI";
1127 case TYPE_WIMAX:
1128 return "WIMAX";
1129 case TYPE_BLUETOOTH:
1130 return "BLUETOOTH";
1131 case TYPE_DUMMY:
1132 return "DUMMY";
1133 case TYPE_ETHERNET:
1134 return "ETHERNET";
1135 case TYPE_MOBILE_FOTA:
1136 return "MOBILE_FOTA";
1137 case TYPE_MOBILE_IMS:
1138 return "MOBILE_IMS";
1139 case TYPE_MOBILE_CBS:
1140 return "MOBILE_CBS";
1141 case TYPE_WIFI_P2P:
1142 return "WIFI_P2P";
1143 case TYPE_MOBILE_IA:
1144 return "MOBILE_IA";
1145 case TYPE_MOBILE_EMERGENCY:
1146 return "MOBILE_EMERGENCY";
1147 case TYPE_PROXY:
1148 return "PROXY";
1149 case TYPE_VPN:
1150 return "VPN";
1151 default:
1152 return Integer.toString(type);
1153 }
1154 }
1155
1156 /**
1157 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001158 */
lucaslin10774b72021-03-17 14:16:01 +08001159 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001160 public void systemReady() {
1161 try {
1162 mService.systemReady();
1163 } catch (RemoteException e) {
1164 throw e.rethrowFromSystemServer();
1165 }
1166 }
1167
1168 /**
1169 * Checks if a given type uses the cellular data connection.
1170 * This should be replaced in the future by a network property.
1171 * @param networkType the type to check
1172 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1173 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1174 * {@hide}
1175 */
1176 @Deprecated
1177 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1178 public static boolean isNetworkTypeMobile(int networkType) {
1179 switch (networkType) {
1180 case TYPE_MOBILE:
1181 case TYPE_MOBILE_MMS:
1182 case TYPE_MOBILE_SUPL:
1183 case TYPE_MOBILE_DUN:
1184 case TYPE_MOBILE_HIPRI:
1185 case TYPE_MOBILE_FOTA:
1186 case TYPE_MOBILE_IMS:
1187 case TYPE_MOBILE_CBS:
1188 case TYPE_MOBILE_IA:
1189 case TYPE_MOBILE_EMERGENCY:
1190 return true;
1191 default:
1192 return false;
1193 }
1194 }
1195
1196 /**
1197 * Checks if the given network type is backed by a Wi-Fi radio.
1198 *
1199 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1200 * @hide
1201 */
1202 @Deprecated
1203 public static boolean isNetworkTypeWifi(int networkType) {
1204 switch (networkType) {
1205 case TYPE_WIFI:
1206 case TYPE_WIFI_P2P:
1207 return true;
1208 default:
1209 return false;
1210 }
1211 }
1212
1213 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001214 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1215 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001216 * Specify that the traffic for this user should by follow the default rules.
1217 * @hide
1218 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001219 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001220 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1221
1222 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001223 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1224 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001225 * Specify that the traffic for this user should by default go on a network with
1226 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1227 * if no such network is available.
1228 * @hide
1229 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001230 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001231 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1232
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001233 /**
1234 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1235 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1236 * Specify that the traffic for this user should by default go on a network with
1237 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
1238 * should not go on the system default network
1239 * @hide
1240 */
1241 @SystemApi(client = MODULE_LIBRARIES)
1242 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1243
Chalard Jeanad565e22021-02-25 17:23:40 +09001244 /** @hide */
1245 @Retention(RetentionPolicy.SOURCE)
1246 @IntDef(value = {
1247 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001248 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1249 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001250 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001251 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001252 }
1253
1254 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001255 * Specifies the preferred network type. When the device has more
1256 * than one type available the preferred network type will be used.
1257 *
1258 * @param preference the network type to prefer over all others. It is
1259 * unspecified what happens to the old preferred network in the
1260 * overall ordering.
1261 * @deprecated Functionality has been removed as it no longer makes sense,
1262 * with many more than two networks - we'd need an array to express
1263 * preference. Instead we use dynamic network properties of
1264 * the networks to describe their precedence.
1265 */
1266 @Deprecated
1267 public void setNetworkPreference(int preference) {
1268 }
1269
1270 /**
1271 * Retrieves the current preferred network type.
1272 *
1273 * @return an integer representing the preferred network type
1274 *
1275 * @deprecated Functionality has been removed as it no longer makes sense,
1276 * with many more than two networks - we'd need an array to express
1277 * preference. Instead we use dynamic network properties of
1278 * the networks to describe their precedence.
1279 */
1280 @Deprecated
1281 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1282 public int getNetworkPreference() {
1283 return TYPE_NONE;
1284 }
1285
1286 /**
1287 * Returns details about the currently active default data network. When
1288 * connected, this network is the default route for outgoing connections.
1289 * You should always check {@link NetworkInfo#isConnected()} before initiating
1290 * network traffic. This may return {@code null} when there is no default
1291 * network.
1292 * Note that if the default network is a VPN, this method will return the
1293 * NetworkInfo for one of its underlying networks instead, or null if the
1294 * VPN agent did not specify any. Apps interested in learning about VPNs
1295 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1296 *
1297 * @return a {@link NetworkInfo} object for the current default network
1298 * or {@code null} if no default network is currently active
1299 * @deprecated See {@link NetworkInfo}.
1300 */
1301 @Deprecated
1302 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1303 @Nullable
1304 public NetworkInfo getActiveNetworkInfo() {
1305 try {
1306 return mService.getActiveNetworkInfo();
1307 } catch (RemoteException e) {
1308 throw e.rethrowFromSystemServer();
1309 }
1310 }
1311
1312 /**
1313 * Returns a {@link Network} object corresponding to the currently active
1314 * default data network. In the event that the current active default data
1315 * network disconnects, the returned {@code Network} object will no longer
1316 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001317 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001318 *
1319 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001320 * {@code null} if no default network is currently active or if
1321 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001322 */
1323 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1324 @Nullable
1325 public Network getActiveNetwork() {
1326 try {
1327 return mService.getActiveNetwork();
1328 } catch (RemoteException e) {
1329 throw e.rethrowFromSystemServer();
1330 }
1331 }
1332
1333 /**
1334 * Returns a {@link Network} object corresponding to the currently active
1335 * default data network for a specific UID. In the event that the default data
1336 * network disconnects, the returned {@code Network} object will no longer
1337 * be usable. This will return {@code null} when there is no default
1338 * network for the UID.
1339 *
1340 * @return a {@link Network} object for the current default network for the
1341 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001342 *
1343 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001344 */
1345 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1346 @Nullable
1347 public Network getActiveNetworkForUid(int uid) {
1348 return getActiveNetworkForUid(uid, false);
1349 }
1350
1351 /** {@hide} */
1352 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1353 try {
1354 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1355 } catch (RemoteException e) {
1356 throw e.rethrowFromSystemServer();
1357 }
1358 }
1359
1360 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001361 * Adds or removes a requirement for given UID ranges to use the VPN.
1362 *
1363 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1364 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1365 * otherwise have permission to bypass the VPN (e.g., because they have the
1366 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1367 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1368 * set to {@code false}, a previously-added restriction is removed.
1369 * <p>
1370 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1371 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1372 * remove a previously-added range, the exact range must be removed as is.
1373 * <p>
1374 * The changes are applied asynchronously and may not have been applied by the time the method
1375 * returns. Apps will be notified about any changes that apply to them via
1376 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1377 * effect.
1378 * <p>
1379 * This method should be called only by the VPN code.
1380 *
1381 * @param ranges the UID ranges to restrict
1382 * @param requireVpn whether the specified UID ranges must use a VPN
1383 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001384 * @hide
1385 */
1386 @RequiresPermission(anyOf = {
1387 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001388 android.Manifest.permission.NETWORK_STACK,
1389 android.Manifest.permission.NETWORK_SETTINGS})
1390 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001391 public void setRequireVpnForUids(boolean requireVpn,
1392 @NonNull Collection<Range<Integer>> ranges) {
1393 Objects.requireNonNull(ranges);
1394 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1395 // This method is not necessarily expected to be used outside the system server, so
1396 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1397 // stack process, or by tests.
1398 UidRange[] rangesArray = new UidRange[ranges.size()];
1399 int index = 0;
1400 for (Range<Integer> range : ranges) {
1401 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1402 }
1403 try {
1404 mService.setRequireVpnForUids(requireVpn, rangesArray);
1405 } catch (RemoteException e) {
1406 throw e.rethrowFromSystemServer();
1407 }
1408 }
1409
1410 /**
Tommy Webb07c46562023-02-20 14:10:55 -05001411 * Update ConnectivityService's map of UIDs to the transports they are allowed to use.
1412 * If a network has a transport type that is not an allowed type for the UID, the UID will
1413 * not be allowed to access that network.
1414 *
1415 * @param uids UIDs to update.
1416 * @param allowedTransportsPacked Corresponding bit-packed allowed transports to update.
1417 *
1418 * @hide
1419 */
1420 @RequiresPermission(anyOf = {
1421 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1422 android.Manifest.permission.NETWORK_STACK,
1423 android.Manifest.permission.NETWORK_SETTINGS})
1424 @SystemApi(client = MODULE_LIBRARIES)
1425 public void setUidsAllowedTransports(@NonNull final int[] uids,
1426 @NonNull final long[] allowedTransportsPacked) {
1427 Objects.requireNonNull(uids);
1428 Objects.requireNonNull(allowedTransportsPacked);
1429 if (uids.length != allowedTransportsPacked.length) {
1430 throw new IllegalArgumentException(
1431 "uids and allowedTransportsPacked must be equal length");
1432 }
1433 try {
1434 mService.setUidsAllowedTransports(uids, allowedTransportsPacked);
1435 } catch (RemoteException e) {
1436 throw e.rethrowFromSystemServer();
1437 }
1438 }
1439
1440 /**
Tommy Webb1fa42c02023-03-22 09:05:18 -04001441 * Returns whether the specified UID is blocked due to disallowed transports.
1442 *
1443 * @hide
1444 */
1445 @RequiresPermission(anyOf = {
1446 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1447 android.Manifest.permission.NETWORK_STACK,
1448 android.Manifest.permission.NETWORK_SETTINGS})
1449 @SystemApi(client = MODULE_LIBRARIES)
1450 public boolean isUidCurrentlyDisallowedByPolicy(int uid) {
1451 try {
1452 return mService.isUidCurrentlyDisallowedByPolicy(uid);
1453 } catch (RemoteException e) {
1454 throw e.rethrowFromSystemServer();
1455 }
1456 }
1457
1458 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001459 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1460 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1461 * but is still supported for backwards compatibility.
1462 * <p>
1463 * This type of VPN is assumed always to use the system default network, and must always declare
1464 * exactly one underlying network, which is the network that was the default when the VPN
1465 * connected.
1466 * <p>
1467 * Calling this method with {@code true} enables legacy behaviour, specifically:
1468 * <ul>
1469 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1470 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1471 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1472 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1473 * underlying the VPN.</li>
1474 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1475 * similarly replaced by the VPN network state.</li>
1476 * <li>Information on current network interfaces passed to NetworkStatsService will not
1477 * include any VPN interfaces.</li>
1478 * </ul>
1479 *
1480 * @param enabled whether legacy lockdown VPN is enabled or disabled
1481 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001482 * @hide
1483 */
1484 @RequiresPermission(anyOf = {
1485 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001486 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001487 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001488 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001489 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1490 try {
1491 mService.setLegacyLockdownVpnEnabled(enabled);
1492 } catch (RemoteException e) {
1493 throw e.rethrowFromSystemServer();
1494 }
1495 }
1496
1497 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001498 * Returns details about the currently active default data network
1499 * for a given uid. This is for internal use only to avoid spying
1500 * other apps.
1501 *
1502 * @return a {@link NetworkInfo} object for the current default network
1503 * for the given uid or {@code null} if no default network is
1504 * available for the specified uid.
1505 *
1506 * {@hide}
1507 */
1508 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1509 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1510 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1511 return getActiveNetworkInfoForUid(uid, false);
1512 }
1513
1514 /** {@hide} */
1515 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1516 try {
1517 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1518 } catch (RemoteException e) {
1519 throw e.rethrowFromSystemServer();
1520 }
1521 }
1522
1523 /**
1524 * Returns connection status information about a particular
1525 * network type.
1526 *
1527 * @param networkType integer specifying which networkType in
1528 * which you're interested.
1529 * @return a {@link NetworkInfo} object for the requested
1530 * network type or {@code null} if the type is not
1531 * supported by the device. If {@code networkType} is
1532 * TYPE_VPN and a VPN is active for the calling app,
1533 * then this method will try to return one of the
1534 * underlying networks for the VPN or null if the
1535 * VPN agent didn't specify any.
1536 *
1537 * @deprecated This method does not support multiple connected networks
1538 * of the same type. Use {@link #getAllNetworks} and
1539 * {@link #getNetworkInfo(android.net.Network)} instead.
1540 */
1541 @Deprecated
1542 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1543 @Nullable
1544 public NetworkInfo getNetworkInfo(int networkType) {
1545 try {
1546 return mService.getNetworkInfo(networkType);
1547 } catch (RemoteException e) {
1548 throw e.rethrowFromSystemServer();
1549 }
1550 }
1551
1552 /**
1553 * Returns connection status information about a particular
1554 * Network.
1555 *
1556 * @param network {@link Network} specifying which network
1557 * in which you're interested.
1558 * @return a {@link NetworkInfo} object for the requested
1559 * network or {@code null} if the {@code Network}
1560 * is not valid.
1561 * @deprecated See {@link NetworkInfo}.
1562 */
1563 @Deprecated
1564 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1565 @Nullable
1566 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1567 return getNetworkInfoForUid(network, Process.myUid(), false);
1568 }
1569
1570 /** {@hide} */
1571 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1572 try {
1573 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1574 } catch (RemoteException e) {
1575 throw e.rethrowFromSystemServer();
1576 }
1577 }
1578
1579 /**
1580 * Returns connection status information about all network
1581 * types supported by the device.
1582 *
1583 * @return an array of {@link NetworkInfo} objects. Check each
1584 * {@link NetworkInfo#getType} for which type each applies.
1585 *
1586 * @deprecated This method does not support multiple connected networks
1587 * of the same type. Use {@link #getAllNetworks} and
1588 * {@link #getNetworkInfo(android.net.Network)} instead.
1589 */
1590 @Deprecated
1591 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1592 @NonNull
1593 public NetworkInfo[] getAllNetworkInfo() {
1594 try {
1595 return mService.getAllNetworkInfo();
1596 } catch (RemoteException e) {
1597 throw e.rethrowFromSystemServer();
1598 }
1599 }
1600
1601 /**
junyulaib1211372021-03-03 12:09:05 +08001602 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1603 * connected.
1604 * @hide
1605 */
1606 @SystemApi(client = MODULE_LIBRARIES)
1607 @RequiresPermission(anyOf = {
1608 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1609 android.Manifest.permission.NETWORK_STACK,
1610 android.Manifest.permission.NETWORK_SETTINGS})
1611 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001612 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001613 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001614 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001615 } catch (RemoteException e) {
1616 throw e.rethrowFromSystemServer();
1617 }
1618 }
1619
1620 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001621 * Returns the {@link Network} object currently serving a given type, or
1622 * null if the given type is not connected.
1623 *
1624 * @hide
1625 * @deprecated This method does not support multiple connected networks
1626 * of the same type. Use {@link #getAllNetworks} and
1627 * {@link #getNetworkInfo(android.net.Network)} instead.
1628 */
1629 @Deprecated
1630 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1631 @UnsupportedAppUsage
1632 public Network getNetworkForType(int networkType) {
1633 try {
1634 return mService.getNetworkForType(networkType);
1635 } catch (RemoteException e) {
1636 throw e.rethrowFromSystemServer();
1637 }
1638 }
1639
1640 /**
1641 * Returns an array of all {@link Network} currently tracked by the
1642 * framework.
1643 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001644 * @deprecated This method does not provide any notification of network state changes, forcing
1645 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1646 * Apps should use methods such as
1647 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1648 * Apps that desire to obtain information about networks that do not apply to them
1649 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1650 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001651 * @return an array of {@link Network} objects.
1652 */
1653 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1654 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001655 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001656 public Network[] getAllNetworks() {
1657 try {
1658 return mService.getAllNetworks();
1659 } catch (RemoteException e) {
1660 throw e.rethrowFromSystemServer();
1661 }
1662 }
1663
1664 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001665 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001666 * the Networks that applications run by the given user will use by default.
1667 * @hide
1668 */
1669 @UnsupportedAppUsage
1670 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1671 try {
1672 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001673 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001674 } catch (RemoteException e) {
1675 throw e.rethrowFromSystemServer();
1676 }
1677 }
1678
1679 /**
1680 * Returns the IP information for the current default network.
1681 *
1682 * @return a {@link LinkProperties} object describing the IP info
1683 * for the current default network, or {@code null} if there
1684 * is no current default network.
1685 *
1686 * {@hide}
1687 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1688 * value of {@link #getActiveNetwork()} instead. In particular,
1689 * this method will return non-null LinkProperties even if the
1690 * app is blocked by policy from using this network.
1691 */
1692 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1693 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1694 public LinkProperties getActiveLinkProperties() {
1695 try {
1696 return mService.getActiveLinkProperties();
1697 } catch (RemoteException e) {
1698 throw e.rethrowFromSystemServer();
1699 }
1700 }
1701
1702 /**
1703 * Returns the IP information for a given network type.
1704 *
1705 * @param networkType the network type of interest.
1706 * @return a {@link LinkProperties} object describing the IP info
1707 * for the given networkType, or {@code null} if there is
1708 * no current default network.
1709 *
1710 * {@hide}
1711 * @deprecated This method does not support multiple connected networks
1712 * of the same type. Use {@link #getAllNetworks},
1713 * {@link #getNetworkInfo(android.net.Network)}, and
1714 * {@link #getLinkProperties(android.net.Network)} instead.
1715 */
1716 @Deprecated
1717 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1718 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1719 public LinkProperties getLinkProperties(int networkType) {
1720 try {
1721 return mService.getLinkPropertiesForType(networkType);
1722 } catch (RemoteException e) {
1723 throw e.rethrowFromSystemServer();
1724 }
1725 }
1726
1727 /**
1728 * Get the {@link LinkProperties} for the given {@link Network}. This
1729 * will return {@code null} if the network is unknown.
1730 *
1731 * @param network The {@link Network} object identifying the network in question.
1732 * @return The {@link LinkProperties} for the network, or {@code null}.
1733 */
1734 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1735 @Nullable
1736 public LinkProperties getLinkProperties(@Nullable Network network) {
1737 try {
1738 return mService.getLinkProperties(network);
1739 } catch (RemoteException e) {
1740 throw e.rethrowFromSystemServer();
1741 }
1742 }
1743
1744 /**
lucaslinc582d502022-01-27 09:07:00 +08001745 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001746 *
lucaslinc582d502022-01-27 09:07:00 +08001747 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1748 * given package, considering its permissions.
1749 *
1750 * @param lp A {@link LinkProperties} which will be redacted.
1751 * @param uid The target uid.
1752 * @param packageName The name of the package, for appops logging.
1753 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1754 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1755 * @hide
1756 */
1757 @RequiresPermission(anyOf = {
1758 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1759 android.Manifest.permission.NETWORK_STACK,
1760 android.Manifest.permission.NETWORK_SETTINGS})
1761 @SystemApi(client = MODULE_LIBRARIES)
1762 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001763 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001764 @NonNull String packageName) {
1765 try {
lucaslind2b06132022-03-02 10:56:57 +08001766 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001767 lp, uid, packageName, getAttributionTag());
1768 } catch (RemoteException e) {
1769 throw e.rethrowFromSystemServer();
1770 }
1771 }
1772
1773 /**
1774 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1775 *
1776 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1777 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1778 * sensitive information. To retrieve this location sensitive information (subject to
1779 * the caller's location permissions), use a {@link NetworkCallback} with the
1780 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1781 *
1782 * This method returns {@code null} if the network is unknown or if the |network| argument
1783 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001784 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001785 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001786 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001787 */
1788 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1789 @Nullable
1790 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1791 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001792 return mService.getNetworkCapabilities(
1793 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001794 } catch (RemoteException e) {
1795 throw e.rethrowFromSystemServer();
1796 }
1797 }
1798
1799 /**
lucaslinc582d502022-01-27 09:07:00 +08001800 * Redact {@link NetworkCapabilities} for a given package.
1801 *
1802 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001803 * to the given package, considering its permissions. If the passed capabilities contain
1804 * location-sensitive information, they will be redacted to the correct degree for the location
1805 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1806 * that level of location. If the UID holds no location permission, the returned object will
1807 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001808 *
1809 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1810 * @param uid The target uid.
1811 * @param packageName The name of the package, for appops logging.
1812 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1813 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1814 * @hide
1815 */
1816 @RequiresPermission(anyOf = {
1817 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1818 android.Manifest.permission.NETWORK_STACK,
1819 android.Manifest.permission.NETWORK_SETTINGS})
1820 @SystemApi(client = MODULE_LIBRARIES)
1821 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001822 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001823 @NonNull NetworkCapabilities nc,
1824 int uid, @NonNull String packageName) {
1825 try {
lucaslind2b06132022-03-02 10:56:57 +08001826 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001827 getAttributionTag());
1828 } catch (RemoteException e) {
1829 throw e.rethrowFromSystemServer();
1830 }
1831 }
1832
1833 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001834 * Gets a URL that can be used for resolving whether a captive portal is present.
1835 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1836 * portal is present.
1837 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1838 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1839 *
1840 * The system network validation may be using different strategies to detect captive portals,
1841 * so this method does not necessarily return a URL used by the system. It only returns a URL
1842 * that may be relevant for other components trying to detect captive portals.
1843 *
1844 * @hide
1845 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1846 * system.
1847 */
1848 @Deprecated
1849 @SystemApi
1850 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1851 public String getCaptivePortalServerUrl() {
1852 try {
1853 return mService.getCaptivePortalServerUrl();
1854 } catch (RemoteException e) {
1855 throw e.rethrowFromSystemServer();
1856 }
1857 }
1858
1859 /**
1860 * Tells the underlying networking system that the caller wants to
1861 * begin using the named feature. The interpretation of {@code feature}
1862 * is completely up to each networking implementation.
1863 *
1864 * <p>This method requires the caller to hold either the
1865 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1866 * or the ability to modify system settings as determined by
1867 * {@link android.provider.Settings.System#canWrite}.</p>
1868 *
1869 * @param networkType specifies which network the request pertains to
1870 * @param feature the name of the feature to be used
1871 * @return an integer value representing the outcome of the request.
1872 * The interpretation of this value is specific to each networking
1873 * implementation+feature combination, except that the value {@code -1}
1874 * always indicates failure.
1875 *
1876 * @deprecated Deprecated in favor of the cleaner
1877 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1878 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1879 * throw {@code UnsupportedOperationException} if called.
1880 * @removed
1881 */
1882 @Deprecated
1883 public int startUsingNetworkFeature(int networkType, String feature) {
1884 checkLegacyRoutingApiAccess();
1885 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1886 if (netCap == null) {
1887 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1888 feature);
1889 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1890 }
1891
1892 NetworkRequest request = null;
1893 synchronized (sLegacyRequests) {
1894 LegacyRequest l = sLegacyRequests.get(netCap);
1895 if (l != null) {
1896 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1897 renewRequestLocked(l);
1898 if (l.currentNetwork != null) {
1899 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1900 } else {
1901 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1902 }
1903 }
1904
1905 request = requestNetworkForFeatureLocked(netCap);
1906 }
1907 if (request != null) {
1908 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1909 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1910 } else {
1911 Log.d(TAG, " request Failed");
1912 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1913 }
1914 }
1915
1916 /**
1917 * Tells the underlying networking system that the caller is finished
1918 * using the named feature. The interpretation of {@code feature}
1919 * is completely up to each networking implementation.
1920 *
1921 * <p>This method requires the caller to hold either the
1922 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1923 * or the ability to modify system settings as determined by
1924 * {@link android.provider.Settings.System#canWrite}.</p>
1925 *
1926 * @param networkType specifies which network the request pertains to
1927 * @param feature the name of the feature that is no longer needed
1928 * @return an integer value representing the outcome of the request.
1929 * The interpretation of this value is specific to each networking
1930 * implementation+feature combination, except that the value {@code -1}
1931 * always indicates failure.
1932 *
1933 * @deprecated Deprecated in favor of the cleaner
1934 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1935 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1936 * throw {@code UnsupportedOperationException} if called.
1937 * @removed
1938 */
1939 @Deprecated
1940 public int stopUsingNetworkFeature(int networkType, String feature) {
1941 checkLegacyRoutingApiAccess();
1942 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1943 if (netCap == null) {
1944 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1945 feature);
1946 return -1;
1947 }
1948
1949 if (removeRequestForFeature(netCap)) {
1950 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1951 }
1952 return 1;
1953 }
1954
1955 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1956 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1957 if (networkType == TYPE_MOBILE) {
1958 switch (feature) {
1959 case "enableCBS":
1960 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1961 case "enableDUN":
1962 case "enableDUNAlways":
1963 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1964 case "enableFOTA":
1965 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1966 case "enableHIPRI":
1967 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1968 case "enableIMS":
1969 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1970 case "enableMMS":
1971 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1972 case "enableSUPL":
1973 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1974 default:
1975 return null;
1976 }
1977 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1978 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1979 }
1980 return null;
1981 }
1982
1983 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1984 if (netCap == null) return TYPE_NONE;
1985 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1986 return TYPE_MOBILE_CBS;
1987 }
1988 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1989 return TYPE_MOBILE_IMS;
1990 }
1991 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1992 return TYPE_MOBILE_FOTA;
1993 }
1994 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1995 return TYPE_MOBILE_DUN;
1996 }
1997 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1998 return TYPE_MOBILE_SUPL;
1999 }
2000 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2001 return TYPE_MOBILE_MMS;
2002 }
2003 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
2004 return TYPE_MOBILE_HIPRI;
2005 }
2006 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
2007 return TYPE_WIFI_P2P;
2008 }
2009 return TYPE_NONE;
2010 }
2011
2012 private static class LegacyRequest {
2013 NetworkCapabilities networkCapabilities;
2014 NetworkRequest networkRequest;
2015 int expireSequenceNumber;
2016 Network currentNetwork;
2017 int delay = -1;
2018
2019 private void clearDnsBinding() {
2020 if (currentNetwork != null) {
2021 currentNetwork = null;
2022 setProcessDefaultNetworkForHostResolution(null);
2023 }
2024 }
2025
2026 NetworkCallback networkCallback = new NetworkCallback() {
2027 @Override
2028 public void onAvailable(Network network) {
2029 currentNetwork = network;
2030 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
2031 setProcessDefaultNetworkForHostResolution(network);
2032 }
2033 @Override
2034 public void onLost(Network network) {
2035 if (network.equals(currentNetwork)) clearDnsBinding();
2036 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2037 }
2038 };
2039 }
2040
2041 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2042 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2043 new HashMap<>();
2044
2045 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2046 synchronized (sLegacyRequests) {
2047 LegacyRequest l = sLegacyRequests.get(netCap);
2048 if (l != null) return l.networkRequest;
2049 }
2050 return null;
2051 }
2052
2053 private void renewRequestLocked(LegacyRequest l) {
2054 l.expireSequenceNumber++;
2055 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2056 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2057 }
2058
2059 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2060 int ourSeqNum = -1;
2061 synchronized (sLegacyRequests) {
2062 LegacyRequest l = sLegacyRequests.get(netCap);
2063 if (l == null) return;
2064 ourSeqNum = l.expireSequenceNumber;
2065 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2066 }
2067 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2068 }
2069
2070 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2071 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2072 int delay = -1;
2073 int type = legacyTypeForNetworkCapabilities(netCap);
2074 try {
2075 delay = mService.getRestoreDefaultNetworkDelay(type);
2076 } catch (RemoteException e) {
2077 throw e.rethrowFromSystemServer();
2078 }
2079 LegacyRequest l = new LegacyRequest();
2080 l.networkCapabilities = netCap;
2081 l.delay = delay;
2082 l.expireSequenceNumber = 0;
2083 l.networkRequest = sendRequestForNetwork(
2084 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2085 if (l.networkRequest == null) return null;
2086 sLegacyRequests.put(netCap, l);
2087 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2088 return l.networkRequest;
2089 }
2090
2091 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2092 if (delay >= 0) {
2093 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2094 CallbackHandler handler = getDefaultHandler();
2095 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2096 handler.sendMessageDelayed(msg, delay);
2097 }
2098 }
2099
2100 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2101 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2102 final LegacyRequest l;
2103 synchronized (sLegacyRequests) {
2104 l = sLegacyRequests.remove(netCap);
2105 }
2106 if (l == null) return false;
2107 unregisterNetworkCallback(l.networkCallback);
2108 l.clearDnsBinding();
2109 return true;
2110 }
2111
2112 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2113 static {
2114 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2115 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2116 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2117 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2118 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2119 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2120 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2121 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2122 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2123 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2124 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2125 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2126 }
2127
2128 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2129 static {
2130 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2131 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2132 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2133 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2134 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2135 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2136 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2137 }
2138
2139 /**
2140 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2141 * instance suitable for registering a request or callback. Throws an
2142 * IllegalArgumentException if no mapping from the legacy type to
2143 * NetworkCapabilities is known.
2144 *
2145 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2146 * to find the network instead.
2147 * @hide
2148 */
2149 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2150 final NetworkCapabilities nc = new NetworkCapabilities();
2151
2152 // Map from type to transports.
2153 final int NOT_FOUND = -1;
2154 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002155 if (transport == NOT_FOUND) {
2156 throw new IllegalArgumentException("unknown legacy type: " + type);
2157 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002158 nc.addTransportType(transport);
2159
2160 // Map from type to capabilities.
2161 nc.addCapability(sLegacyTypeToCapability.get(
2162 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2163 nc.maybeMarkCapabilitiesRestricted();
2164 return nc;
2165 }
2166
2167 /** @hide */
2168 public static class PacketKeepaliveCallback {
2169 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2170 public PacketKeepaliveCallback() {
2171 }
2172 /** The requested keepalive was successfully started. */
2173 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2174 public void onStarted() {}
2175 /** The keepalive was successfully stopped. */
2176 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2177 public void onStopped() {}
2178 /** An error occurred. */
2179 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2180 public void onError(int error) {}
2181 }
2182
2183 /**
2184 * Allows applications to request that the system periodically send specific packets on their
2185 * behalf, using hardware offload to save battery power.
2186 *
2187 * To request that the system send keepalives, call one of the methods that return a
2188 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2189 * passing in a non-null callback. If the callback is successfully started, the callback's
2190 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2191 * specifying one of the {@code ERROR_*} constants in this class.
2192 *
2193 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2194 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2195 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2196 *
2197 * @deprecated Use {@link SocketKeepalive} instead.
2198 *
2199 * @hide
2200 */
2201 public class PacketKeepalive {
2202
2203 private static final String TAG = "PacketKeepalive";
2204
2205 /** @hide */
2206 public static final int SUCCESS = 0;
2207
2208 /** @hide */
2209 public static final int NO_KEEPALIVE = -1;
2210
2211 /** @hide */
2212 public static final int BINDER_DIED = -10;
2213
2214 /** The specified {@code Network} is not connected. */
2215 public static final int ERROR_INVALID_NETWORK = -20;
2216 /** The specified IP addresses are invalid. For example, the specified source IP address is
2217 * not configured on the specified {@code Network}. */
2218 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2219 /** The requested port is invalid. */
2220 public static final int ERROR_INVALID_PORT = -22;
2221 /** The packet length is invalid (e.g., too long). */
2222 public static final int ERROR_INVALID_LENGTH = -23;
2223 /** The packet transmission interval is invalid (e.g., too short). */
2224 public static final int ERROR_INVALID_INTERVAL = -24;
2225
2226 /** The hardware does not support this request. */
2227 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2228 /** The hardware returned an error. */
2229 public static final int ERROR_HARDWARE_ERROR = -31;
2230
2231 /** The NAT-T destination port for IPsec */
2232 public static final int NATT_PORT = 4500;
2233
2234 /** The minimum interval in seconds between keepalive packet transmissions */
2235 public static final int MIN_INTERVAL = 10;
2236
2237 private final Network mNetwork;
2238 private final ISocketKeepaliveCallback mCallback;
2239 private final ExecutorService mExecutor;
2240
2241 private volatile Integer mSlot;
2242
2243 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2244 public void stop() {
2245 try {
2246 mExecutor.execute(() -> {
2247 try {
2248 if (mSlot != null) {
2249 mService.stopKeepalive(mNetwork, mSlot);
2250 }
2251 } catch (RemoteException e) {
2252 Log.e(TAG, "Error stopping packet keepalive: ", e);
2253 throw e.rethrowFromSystemServer();
2254 }
2255 });
2256 } catch (RejectedExecutionException e) {
2257 // The internal executor has already stopped due to previous event.
2258 }
2259 }
2260
2261 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002262 Objects.requireNonNull(network, "network cannot be null");
2263 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002264 mNetwork = network;
2265 mExecutor = Executors.newSingleThreadExecutor();
2266 mCallback = new ISocketKeepaliveCallback.Stub() {
2267 @Override
2268 public void onStarted(int slot) {
2269 final long token = Binder.clearCallingIdentity();
2270 try {
2271 mExecutor.execute(() -> {
2272 mSlot = slot;
2273 callback.onStarted();
2274 });
2275 } finally {
2276 Binder.restoreCallingIdentity(token);
2277 }
2278 }
2279
2280 @Override
2281 public void onStopped() {
2282 final long token = Binder.clearCallingIdentity();
2283 try {
2284 mExecutor.execute(() -> {
2285 mSlot = null;
2286 callback.onStopped();
2287 });
2288 } finally {
2289 Binder.restoreCallingIdentity(token);
2290 }
2291 mExecutor.shutdown();
2292 }
2293
2294 @Override
2295 public void onError(int error) {
2296 final long token = Binder.clearCallingIdentity();
2297 try {
2298 mExecutor.execute(() -> {
2299 mSlot = null;
2300 callback.onError(error);
2301 });
2302 } finally {
2303 Binder.restoreCallingIdentity(token);
2304 }
2305 mExecutor.shutdown();
2306 }
2307
2308 @Override
2309 public void onDataReceived() {
2310 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2311 // this callback when data is received.
2312 }
2313 };
2314 }
2315 }
2316
2317 /**
2318 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2319 *
2320 * @deprecated Use {@link #createSocketKeepalive} instead.
2321 *
2322 * @hide
2323 */
2324 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2325 public PacketKeepalive startNattKeepalive(
2326 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2327 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2328 final PacketKeepalive k = new PacketKeepalive(network, callback);
2329 try {
2330 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2331 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2332 } catch (RemoteException e) {
2333 Log.e(TAG, "Error starting packet keepalive: ", e);
2334 throw e.rethrowFromSystemServer();
2335 }
2336 return k;
2337 }
2338
2339 // Construct an invalid fd.
2340 private ParcelFileDescriptor createInvalidFd() {
2341 final int invalidFd = -1;
2342 return ParcelFileDescriptor.adoptFd(invalidFd);
2343 }
2344
2345 /**
2346 * Request that keepalives be started on a IPsec NAT-T socket.
2347 *
2348 * @param network The {@link Network} the socket is on.
2349 * @param socket The socket that needs to be kept alive.
2350 * @param source The source address of the {@link UdpEncapsulationSocket}.
2351 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2352 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2353 * must run callback sequentially, otherwise the order of callbacks cannot be
2354 * guaranteed.
2355 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2356 * changes. Must be extended by applications that use this API.
2357 *
2358 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2359 * given socket.
2360 **/
2361 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2362 @NonNull UdpEncapsulationSocket socket,
2363 @NonNull InetAddress source,
2364 @NonNull InetAddress destination,
2365 @NonNull @CallbackExecutor Executor executor,
2366 @NonNull Callback callback) {
2367 ParcelFileDescriptor dup;
2368 try {
2369 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2370 // which cannot be obtained by the app process.
2371 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2372 } catch (IOException ignored) {
2373 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2374 // ERROR_INVALID_SOCKET.
2375 dup = createInvalidFd();
2376 }
2377 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2378 destination, executor, callback);
2379 }
2380
2381 /**
2382 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2383 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2384 *
2385 * @param network The {@link Network} the socket is on.
2386 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2387 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2388 * from that port.
2389 * @param source The source address of the {@link UdpEncapsulationSocket}.
2390 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2391 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2392 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2393 * must run callback sequentially, otherwise the order of callbacks cannot be
2394 * guaranteed.
2395 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2396 * changes. Must be extended by applications that use this API.
2397 *
2398 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2399 * given socket.
2400 * @hide
2401 */
2402 @SystemApi
2403 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2404 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2405 @NonNull ParcelFileDescriptor pfd,
2406 @NonNull InetAddress source,
2407 @NonNull InetAddress destination,
2408 @NonNull @CallbackExecutor Executor executor,
2409 @NonNull Callback callback) {
2410 ParcelFileDescriptor dup;
2411 try {
2412 // TODO: Consider remove unnecessary dup.
2413 dup = pfd.dup();
2414 } catch (IOException ignored) {
2415 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2416 // ERROR_INVALID_SOCKET.
2417 dup = createInvalidFd();
2418 }
2419 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002420 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002421 }
2422
2423 /**
2424 * Request that keepalives be started on a TCP socket.
2425 * The socket must be established.
2426 *
2427 * @param network The {@link Network} the socket is on.
2428 * @param socket The socket that needs to be kept alive.
2429 * @param executor The executor on which callback will be invoked. This implementation assumes
2430 * the provided {@link Executor} runs the callbacks in sequence with no
2431 * concurrency. Failing this, no guarantee of correctness can be made. It is
2432 * the responsibility of the caller to ensure the executor provides this
2433 * guarantee. A simple way of creating such an executor is with the standard
2434 * tool {@code Executors.newSingleThreadExecutor}.
2435 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2436 * changes. Must be extended by applications that use this API.
2437 *
2438 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2439 * given socket.
2440 * @hide
2441 */
2442 @SystemApi
2443 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2444 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2445 @NonNull Socket socket,
2446 @NonNull Executor executor,
2447 @NonNull Callback callback) {
2448 ParcelFileDescriptor dup;
2449 try {
2450 dup = ParcelFileDescriptor.fromSocket(socket);
2451 } catch (UncheckedIOException ignored) {
2452 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2453 // ERROR_INVALID_SOCKET.
2454 dup = createInvalidFd();
2455 }
2456 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2457 }
2458
2459 /**
2460 * Ensure that a network route exists to deliver traffic to the specified
2461 * host via the specified network interface. An attempt to add a route that
2462 * already exists is ignored, but treated as successful.
2463 *
2464 * <p>This method requires the caller to hold either the
2465 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2466 * or the ability to modify system settings as determined by
2467 * {@link android.provider.Settings.System#canWrite}.</p>
2468 *
2469 * @param networkType the type of the network over which traffic to the specified
2470 * host is to be routed
2471 * @param hostAddress the IP address of the host to which the route is desired
2472 * @return {@code true} on success, {@code false} on failure
2473 *
2474 * @deprecated Deprecated in favor of the
2475 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2476 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2477 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2478 * throw {@code UnsupportedOperationException} if called.
2479 * @removed
2480 */
2481 @Deprecated
2482 public boolean requestRouteToHost(int networkType, int hostAddress) {
2483 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2484 }
2485
2486 /**
2487 * Ensure that a network route exists to deliver traffic to the specified
2488 * host via the specified network interface. An attempt to add a route that
2489 * already exists is ignored, but treated as successful.
2490 *
2491 * <p>This method requires the caller to hold either the
2492 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2493 * or the ability to modify system settings as determined by
2494 * {@link android.provider.Settings.System#canWrite}.</p>
2495 *
2496 * @param networkType the type of the network over which traffic to the specified
2497 * host is to be routed
2498 * @param hostAddress the IP address of the host to which the route is desired
2499 * @return {@code true} on success, {@code false} on failure
2500 * @hide
2501 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2502 * {@link #bindProcessToNetwork} API.
2503 */
2504 @Deprecated
2505 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002506 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002507 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2508 checkLegacyRoutingApiAccess();
2509 try {
2510 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2511 mContext.getOpPackageName(), getAttributionTag());
2512 } catch (RemoteException e) {
2513 throw e.rethrowFromSystemServer();
2514 }
2515 }
2516
2517 /**
2518 * @return the context's attribution tag
2519 */
2520 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2521 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002522 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002523 }
2524
2525 /**
2526 * Returns the value of the setting for background data usage. If false,
2527 * applications should not use the network if the application is not in the
2528 * foreground. Developers should respect this setting, and check the value
2529 * of this before performing any background data operations.
2530 * <p>
2531 * All applications that have background services that use the network
2532 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2533 * <p>
2534 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2535 * background data depends on several combined factors, and this method will
2536 * always return {@code true}. Instead, when background data is unavailable,
2537 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2538 *
2539 * @return Whether background data usage is allowed.
2540 */
2541 @Deprecated
2542 public boolean getBackgroundDataSetting() {
2543 // assume that background data is allowed; final authority is
2544 // NetworkInfo which may be blocked.
2545 return true;
2546 }
2547
2548 /**
2549 * Sets the value of the setting for background data usage.
2550 *
2551 * @param allowBackgroundData Whether an application should use data while
2552 * it is in the background.
2553 *
2554 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2555 * @see #getBackgroundDataSetting()
2556 * @hide
2557 */
2558 @Deprecated
2559 @UnsupportedAppUsage
2560 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2561 // ignored
2562 }
2563
2564 /**
2565 * @hide
2566 * @deprecated Talk to TelephonyManager directly
2567 */
2568 @Deprecated
2569 @UnsupportedAppUsage
2570 public boolean getMobileDataEnabled() {
2571 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2572 if (tm != null) {
2573 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2574 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2575 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2576 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2577 + " retVal=" + retVal);
2578 return retVal;
2579 }
2580 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2581 return false;
2582 }
2583
2584 /**
2585 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2586 * to find out when the system default network has gone in to a high power state.
2587 */
2588 public interface OnNetworkActiveListener {
2589 /**
2590 * Called on the main thread of the process to report that the current data network
2591 * has become active, and it is now a good time to perform any pending network
2592 * operations. Note that this listener only tells you when the network becomes
2593 * active; if at any other time you want to know whether it is active (and thus okay
2594 * to initiate network traffic), you can retrieve its instantaneous state with
2595 * {@link ConnectivityManager#isDefaultNetworkActive}.
2596 */
2597 void onNetworkActive();
2598 }
2599
Chiachang Wang2de41682021-09-23 10:46:03 +08002600 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002601 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2602 mNetworkActivityListeners = new ArrayMap<>();
2603
2604 /**
2605 * Start listening to reports when the system's default data network is active, meaning it is
2606 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2607 * to determine the current state of the system's default network after registering the
2608 * listener.
2609 * <p>
2610 * If the process default network has been set with
2611 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2612 * reflect the process's default, but the system default.
2613 *
2614 * @param l The listener to be told when the network is active.
2615 */
2616 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002617 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002618 @Override
2619 public void onNetworkActive() throws RemoteException {
2620 l.onNetworkActive();
2621 }
2622 };
2623
Chiachang Wang2de41682021-09-23 10:46:03 +08002624 synchronized (mNetworkActivityListeners) {
2625 try {
2626 mService.registerNetworkActivityListener(rl);
2627 mNetworkActivityListeners.put(l, rl);
2628 } catch (RemoteException e) {
2629 throw e.rethrowFromSystemServer();
2630 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002631 }
2632 }
2633
2634 /**
2635 * Remove network active listener previously registered with
2636 * {@link #addDefaultNetworkActiveListener}.
2637 *
2638 * @param l Previously registered listener.
2639 */
2640 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002641 synchronized (mNetworkActivityListeners) {
2642 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2643 if (rl == null) {
2644 throw new IllegalArgumentException("Listener was not registered.");
2645 }
2646 try {
2647 mService.unregisterNetworkActivityListener(rl);
2648 mNetworkActivityListeners.remove(l);
2649 } catch (RemoteException e) {
2650 throw e.rethrowFromSystemServer();
2651 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002652 }
2653 }
2654
2655 /**
2656 * Return whether the data network is currently active. An active network means that
2657 * it is currently in a high power state for performing data transmission. On some
2658 * types of networks, it may be expensive to move and stay in such a state, so it is
2659 * more power efficient to batch network traffic together when the radio is already in
2660 * this state. This method tells you whether right now is currently a good time to
2661 * initiate network traffic, as the network is already active.
2662 */
2663 public boolean isDefaultNetworkActive() {
2664 try {
lucaslin709eb842021-01-21 02:04:15 +08002665 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002666 } catch (RemoteException e) {
2667 throw e.rethrowFromSystemServer();
2668 }
2669 }
2670
2671 /**
2672 * {@hide}
2673 */
2674 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002675 mContext = Objects.requireNonNull(context, "missing context");
2676 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002677 sInstance = this;
2678 }
2679
2680 /** {@hide} */
2681 @UnsupportedAppUsage
2682 public static ConnectivityManager from(Context context) {
2683 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2684 }
2685
2686 /** @hide */
2687 public NetworkRequest getDefaultRequest() {
2688 try {
2689 // This is not racy as the default request is final in ConnectivityService.
2690 return mService.getDefaultRequest();
2691 } catch (RemoteException e) {
2692 throw e.rethrowFromSystemServer();
2693 }
2694 }
2695
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002696 /**
2697 * Check if the package is a allowed to write settings. This also accounts that such an access
2698 * happened.
2699 *
2700 * @return {@code true} iff the package is allowed to write settings.
2701 */
2702 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2703 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2704 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2705 boolean throwException) {
2706 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002707 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002708 }
2709
2710 /**
2711 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2712 * situations where a Context pointer is unavailable.
2713 * @hide
2714 */
2715 @Deprecated
2716 static ConnectivityManager getInstanceOrNull() {
2717 return sInstance;
2718 }
2719
2720 /**
2721 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2722 * situations where a Context pointer is unavailable.
2723 * @hide
2724 */
2725 @Deprecated
2726 @UnsupportedAppUsage
2727 private static ConnectivityManager getInstance() {
2728 if (getInstanceOrNull() == null) {
2729 throw new IllegalStateException("No ConnectivityManager yet constructed");
2730 }
2731 return getInstanceOrNull();
2732 }
2733
2734 /**
2735 * Get the set of tetherable, available interfaces. This list is limited by
2736 * device configuration and current interface existence.
2737 *
2738 * @return an array of 0 or more Strings of tetherable interface names.
2739 *
2740 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2741 * {@hide}
2742 */
2743 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2744 @UnsupportedAppUsage
2745 @Deprecated
2746 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002747 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002748 }
2749
2750 /**
2751 * Get the set of tethered interfaces.
2752 *
2753 * @return an array of 0 or more String of currently tethered interface names.
2754 *
2755 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2756 * {@hide}
2757 */
2758 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2759 @UnsupportedAppUsage
2760 @Deprecated
2761 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002762 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002763 }
2764
2765 /**
2766 * Get the set of interface names which attempted to tether but
2767 * failed. Re-attempting to tether may cause them to reset to the Tethered
2768 * state. Alternatively, causing the interface to be destroyed and recreated
2769 * may cause them to reset to the available state.
2770 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2771 * information on the cause of the errors.
2772 *
2773 * @return an array of 0 or more String indicating the interface names
2774 * which failed to tether.
2775 *
2776 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2777 * {@hide}
2778 */
2779 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2780 @UnsupportedAppUsage
2781 @Deprecated
2782 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002783 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002784 }
2785
2786 /**
2787 * Get the set of tethered dhcp ranges.
2788 *
2789 * @deprecated This method is not supported.
2790 * TODO: remove this function when all of clients are removed.
2791 * {@hide}
2792 */
2793 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2794 @Deprecated
2795 public String[] getTetheredDhcpRanges() {
2796 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2797 }
2798
2799 /**
2800 * Attempt to tether the named interface. This will setup a dhcp server
2801 * on the interface, forward and NAT IP packets and forward DNS requests
2802 * to the best active upstream network interface. Note that if no upstream
2803 * IP network interface is available, dhcp will still run and traffic will be
2804 * allowed between the tethered devices and this device, though upstream net
2805 * access will of course fail until an upstream network interface becomes
2806 * active.
2807 *
2808 * <p>This method requires the caller to hold either the
2809 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2810 * or the ability to modify system settings as determined by
2811 * {@link android.provider.Settings.System#canWrite}.</p>
2812 *
2813 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2814 * and WifiStateMachine which need direct access. All other clients should use
2815 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2816 * logic.</p>
2817 *
2818 * @param iface the interface name to tether.
2819 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2820 * @deprecated Use {@link TetheringManager#startTethering} instead
2821 *
2822 * {@hide}
2823 */
2824 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2825 @Deprecated
2826 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002827 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002828 }
2829
2830 /**
2831 * Stop tethering the named interface.
2832 *
2833 * <p>This method requires the caller to hold either the
2834 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2835 * or the ability to modify system settings as determined by
2836 * {@link android.provider.Settings.System#canWrite}.</p>
2837 *
2838 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2839 * and WifiStateMachine which need direct access. All other clients should use
2840 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2841 * logic.</p>
2842 *
2843 * @param iface the interface name to untether.
2844 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2845 *
2846 * {@hide}
2847 */
2848 @UnsupportedAppUsage
2849 @Deprecated
2850 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002851 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002852 }
2853
2854 /**
2855 * Check if the device allows for tethering. It may be disabled via
2856 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2857 * due to device configuration.
2858 *
2859 * <p>If this app does not have permission to use this API, it will always
2860 * return false rather than throw an exception.</p>
2861 *
2862 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2863 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2864 *
2865 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2866 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2867 *
2868 * @return a boolean - {@code true} indicating Tethering is supported.
2869 *
2870 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2871 * {@hide}
2872 */
2873 @SystemApi
2874 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2875 android.Manifest.permission.WRITE_SETTINGS})
2876 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002877 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002878 }
2879
2880 /**
2881 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2882 *
2883 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2884 * @hide
2885 */
2886 @SystemApi
2887 @Deprecated
2888 public static abstract class OnStartTetheringCallback {
2889 /**
2890 * Called when tethering has been successfully started.
2891 */
2892 public void onTetheringStarted() {}
2893
2894 /**
2895 * Called when starting tethering failed.
2896 */
2897 public void onTetheringFailed() {}
2898 }
2899
2900 /**
2901 * Convenient overload for
2902 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2903 * handler to run on the current thread's {@link Looper}.
2904 *
2905 * @deprecated Use {@link TetheringManager#startTethering} instead.
2906 * @hide
2907 */
2908 @SystemApi
2909 @Deprecated
2910 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2911 public void startTethering(int type, boolean showProvisioningUi,
2912 final OnStartTetheringCallback callback) {
2913 startTethering(type, showProvisioningUi, callback, null);
2914 }
2915
2916 /**
2917 * Runs tether provisioning for the given type if needed and then starts tethering if
2918 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2919 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2920 * schedules tether provisioning re-checks if appropriate.
2921 *
2922 * @param type The type of tethering to start. Must be one of
2923 * {@link ConnectivityManager.TETHERING_WIFI},
2924 * {@link ConnectivityManager.TETHERING_USB}, or
2925 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2926 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2927 * is one. This should be true the first time this function is called and also any time
2928 * the user can see this UI. It gives users information from their carrier about the
2929 * check failing and how they can sign up for tethering if possible.
2930 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2931 * of the result of trying to tether.
2932 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2933 *
2934 * @deprecated Use {@link TetheringManager#startTethering} instead.
2935 * @hide
2936 */
2937 @SystemApi
2938 @Deprecated
2939 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2940 public void startTethering(int type, boolean showProvisioningUi,
2941 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002942 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002943
2944 final Executor executor = new Executor() {
2945 @Override
2946 public void execute(Runnable command) {
2947 if (handler == null) {
2948 command.run();
2949 } else {
2950 handler.post(command);
2951 }
2952 }
2953 };
2954
2955 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2956 @Override
2957 public void onTetheringStarted() {
2958 callback.onTetheringStarted();
2959 }
2960
2961 @Override
2962 public void onTetheringFailed(final int error) {
2963 callback.onTetheringFailed();
2964 }
2965 };
2966
2967 final TetheringRequest request = new TetheringRequest.Builder(type)
2968 .setShouldShowEntitlementUi(showProvisioningUi).build();
2969
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002970 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002971 }
2972
2973 /**
2974 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2975 * applicable.
2976 *
2977 * @param type The type of tethering to stop. Must be one of
2978 * {@link ConnectivityManager.TETHERING_WIFI},
2979 * {@link ConnectivityManager.TETHERING_USB}, or
2980 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2981 *
2982 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2983 * @hide
2984 */
2985 @SystemApi
2986 @Deprecated
2987 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2988 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002989 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002990 }
2991
2992 /**
2993 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2994 * upstream status.
2995 *
2996 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2997 * @hide
2998 */
2999 @SystemApi
3000 @Deprecated
3001 public abstract static class OnTetheringEventCallback {
3002
3003 /**
3004 * Called when tethering upstream changed. This can be called multiple times and can be
3005 * called any time.
3006 *
3007 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
3008 * have any upstream.
3009 */
3010 public void onUpstreamChanged(@Nullable Network network) {}
3011 }
3012
3013 @GuardedBy("mTetheringEventCallbacks")
3014 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
3015 mTetheringEventCallbacks = new ArrayMap<>();
3016
3017 /**
3018 * Start listening to tethering change events. Any new added callback will receive the last
3019 * tethering status right away. If callback is registered when tethering has no upstream or
3020 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3021 * with a null argument. The same callback object cannot be registered twice.
3022 *
3023 * @param executor the executor on which callback will be invoked.
3024 * @param callback the callback to be called when tethering has change events.
3025 *
3026 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3027 * @hide
3028 */
3029 @SystemApi
3030 @Deprecated
3031 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3032 public void registerTetheringEventCallback(
3033 @NonNull @CallbackExecutor Executor executor,
3034 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003035 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003036
3037 final TetheringEventCallback tetherCallback =
3038 new TetheringEventCallback() {
3039 @Override
3040 public void onUpstreamChanged(@Nullable Network network) {
3041 callback.onUpstreamChanged(network);
3042 }
3043 };
3044
3045 synchronized (mTetheringEventCallbacks) {
3046 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003047 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003048 }
3049 }
3050
3051 /**
3052 * Remove tethering event callback previously registered with
3053 * {@link #registerTetheringEventCallback}.
3054 *
3055 * @param callback previously registered callback.
3056 *
3057 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3058 * @hide
3059 */
3060 @SystemApi
3061 @Deprecated
3062 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3063 public void unregisterTetheringEventCallback(
3064 @NonNull final OnTetheringEventCallback callback) {
3065 Objects.requireNonNull(callback, "The callback must be non-null");
3066 synchronized (mTetheringEventCallbacks) {
3067 final TetheringEventCallback tetherCallback =
3068 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003069 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003070 }
3071 }
3072
3073
3074 /**
3075 * Get the list of regular expressions that define any tetherable
3076 * USB network interfaces. If USB tethering is not supported by the
3077 * device, this list should be empty.
3078 *
3079 * @return an array of 0 or more regular expression Strings defining
3080 * what interfaces are considered tetherable usb interfaces.
3081 *
3082 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3083 * {@hide}
3084 */
3085 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3086 @UnsupportedAppUsage
3087 @Deprecated
3088 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003089 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003090 }
3091
3092 /**
3093 * Get the list of regular expressions that define any tetherable
3094 * Wifi network interfaces. If Wifi tethering is not supported by the
3095 * device, this list should be empty.
3096 *
3097 * @return an array of 0 or more regular expression Strings defining
3098 * what interfaces are considered tetherable wifi interfaces.
3099 *
3100 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3101 * {@hide}
3102 */
3103 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3104 @UnsupportedAppUsage
3105 @Deprecated
3106 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003107 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003108 }
3109
3110 /**
3111 * Get the list of regular expressions that define any tetherable
3112 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3113 * device, this list should be empty.
3114 *
3115 * @return an array of 0 or more regular expression Strings defining
3116 * what interfaces are considered tetherable bluetooth interfaces.
3117 *
3118 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3119 *TetheringManager.TetheringInterfaceRegexps)} instead.
3120 * {@hide}
3121 */
3122 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3123 @UnsupportedAppUsage
3124 @Deprecated
3125 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003126 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003127 }
3128
3129 /**
3130 * Attempt to both alter the mode of USB and Tethering of USB. A
3131 * utility method to deal with some of the complexity of USB - will
3132 * attempt to switch to Rndis and subsequently tether the resulting
3133 * interface on {@code true} or turn off tethering and switch off
3134 * Rndis on {@code false}.
3135 *
3136 * <p>This method requires the caller to hold either the
3137 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3138 * or the ability to modify system settings as determined by
3139 * {@link android.provider.Settings.System#canWrite}.</p>
3140 *
3141 * @param enable a boolean - {@code true} to enable tethering
3142 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3143 * @deprecated Use {@link TetheringManager#startTethering} instead
3144 *
3145 * {@hide}
3146 */
3147 @UnsupportedAppUsage
3148 @Deprecated
3149 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003150 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003151 }
3152
3153 /**
3154 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3155 * {@hide}
3156 */
3157 @SystemApi
3158 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003159 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003160 /**
3161 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3162 * {@hide}
3163 */
3164 @Deprecated
3165 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3166 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3167 /**
3168 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3169 * {@hide}
3170 */
3171 @Deprecated
3172 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3173 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3174 /**
3175 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3176 * {@hide}
3177 */
3178 @Deprecated
3179 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3180 /**
3181 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3182 * {@hide}
3183 */
3184 @Deprecated
3185 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3186 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3187 /**
3188 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3189 * {@hide}
3190 */
3191 @Deprecated
3192 public static final int TETHER_ERROR_MASTER_ERROR =
3193 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3194 /**
3195 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3196 * {@hide}
3197 */
3198 @Deprecated
3199 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3200 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3201 /**
3202 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3203 * {@hide}
3204 */
3205 @Deprecated
3206 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3207 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3208 /**
3209 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3210 * {@hide}
3211 */
3212 @Deprecated
3213 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3214 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3215 /**
3216 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3217 * {@hide}
3218 */
3219 @Deprecated
3220 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3221 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3222 /**
3223 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3224 * {@hide}
3225 */
3226 @Deprecated
3227 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3228 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3229 /**
3230 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3231 * {@hide}
3232 */
3233 @SystemApi
3234 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003235 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003236 /**
3237 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3238 * {@hide}
3239 */
3240 @Deprecated
3241 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3242 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3243 /**
3244 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3245 * {@hide}
3246 */
3247 @SystemApi
3248 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003249 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003250
3251 /**
3252 * Get a more detailed error code after a Tethering or Untethering
3253 * request asynchronously failed.
3254 *
3255 * @param iface The name of the interface of interest
3256 * @return error The error code of the last error tethering or untethering the named
3257 * interface
3258 *
3259 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3260 * {@hide}
3261 */
3262 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3263 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3264 @Deprecated
3265 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003266 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003267 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3268 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3269 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3270 // instead.
3271 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3272 }
3273 return error;
3274 }
3275
3276 /** @hide */
3277 @Retention(RetentionPolicy.SOURCE)
3278 @IntDef(value = {
3279 TETHER_ERROR_NO_ERROR,
3280 TETHER_ERROR_PROVISION_FAILED,
3281 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3282 })
3283 public @interface EntitlementResultCode {
3284 }
3285
3286 /**
3287 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3288 * entitlement succeeded.
3289 *
3290 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3291 * @hide
3292 */
3293 @SystemApi
3294 @Deprecated
3295 public interface OnTetheringEntitlementResultListener {
3296 /**
3297 * Called to notify entitlement result.
3298 *
3299 * @param resultCode an int value of entitlement result. It may be one of
3300 * {@link #TETHER_ERROR_NO_ERROR},
3301 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3302 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3303 */
3304 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3305 }
3306
3307 /**
3308 * Get the last value of the entitlement check on this downstream. If the cached value is
3309 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3310 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3311 * guaranteed that the UI-based entitlement check will complete in any specific time period
3312 * and may in fact never complete. Any successful entitlement check the platform performs for
3313 * any reason will update the cached value.
3314 *
3315 * @param type the downstream type of tethering. Must be one of
3316 * {@link #TETHERING_WIFI},
3317 * {@link #TETHERING_USB}, or
3318 * {@link #TETHERING_BLUETOOTH}.
3319 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3320 * @param executor the executor on which callback will be invoked.
3321 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3322 * notify the caller of the result of entitlement check. The listener may be called zero
3323 * or one time.
3324 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3325 * {@hide}
3326 */
3327 @SystemApi
3328 @Deprecated
3329 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3330 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3331 @NonNull @CallbackExecutor Executor executor,
3332 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003333 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003334 ResultReceiver wrappedListener = new ResultReceiver(null) {
3335 @Override
3336 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003337 final long token = Binder.clearCallingIdentity();
3338 try {
3339 executor.execute(() -> {
3340 listener.onTetheringEntitlementResult(resultCode);
3341 });
3342 } finally {
3343 Binder.restoreCallingIdentity(token);
3344 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003345 }
3346 };
3347
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003348 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003349 showEntitlementUi);
3350 }
3351
3352 /**
3353 * Report network connectivity status. This is currently used only
3354 * to alter status bar UI.
3355 * <p>This method requires the caller to hold the permission
3356 * {@link android.Manifest.permission#STATUS_BAR}.
3357 *
3358 * @param networkType The type of network you want to report on
3359 * @param percentage The quality of the connection 0 is bad, 100 is good
3360 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3361 * {@hide}
3362 */
3363 public void reportInetCondition(int networkType, int percentage) {
3364 printStackTrace();
3365 try {
3366 mService.reportInetCondition(networkType, percentage);
3367 } catch (RemoteException e) {
3368 throw e.rethrowFromSystemServer();
3369 }
3370 }
3371
3372 /**
3373 * Report a problem network to the framework. This provides a hint to the system
3374 * that there might be connectivity problems on this network and may cause
3375 * the framework to re-evaluate network connectivity and/or switch to another
3376 * network.
3377 *
3378 * @param network The {@link Network} the application was attempting to use
3379 * or {@code null} to indicate the current default network.
3380 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3381 * working and non-working connectivity.
3382 */
3383 @Deprecated
3384 public void reportBadNetwork(@Nullable Network network) {
3385 printStackTrace();
3386 try {
3387 // One of these will be ignored because it matches system's current state.
3388 // The other will trigger the necessary reevaluation.
3389 mService.reportNetworkConnectivity(network, true);
3390 mService.reportNetworkConnectivity(network, false);
3391 } catch (RemoteException e) {
3392 throw e.rethrowFromSystemServer();
3393 }
3394 }
3395
3396 /**
3397 * Report to the framework whether a network has working connectivity.
3398 * This provides a hint to the system that a particular network is providing
3399 * working connectivity or not. In response the framework may re-evaluate
3400 * the network's connectivity and might take further action thereafter.
3401 *
3402 * @param network The {@link Network} the application was attempting to use
3403 * or {@code null} to indicate the current default network.
3404 * @param hasConnectivity {@code true} if the application was able to successfully access the
3405 * Internet using {@code network} or {@code false} if not.
3406 */
3407 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3408 printStackTrace();
3409 try {
3410 mService.reportNetworkConnectivity(network, hasConnectivity);
3411 } catch (RemoteException e) {
3412 throw e.rethrowFromSystemServer();
3413 }
3414 }
3415
3416 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003417 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003418 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003419 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3420 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3421 * accessing any network, regardless of what the settings for that network are.
3422 *
3423 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3424 * proxy is likely to break networking on multiple networks. This method is only meant
3425 * for device policy clients looking to do general internal filtering or similar use cases.
3426 *
3427 * {@see #getGlobalProxy}
3428 * {@see LinkProperties#getHttpProxy}
3429 *
3430 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3431 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003432 * @hide
3433 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003434 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003435 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003436 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003437 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003438 try {
3439 mService.setGlobalProxy(p);
3440 } catch (RemoteException e) {
3441 throw e.rethrowFromSystemServer();
3442 }
3443 }
3444
3445 /**
3446 * Retrieve any network-independent global HTTP proxy.
3447 *
3448 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3449 * if no global HTTP proxy is set.
3450 * @hide
3451 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003452 @SystemApi(client = MODULE_LIBRARIES)
3453 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003454 public ProxyInfo getGlobalProxy() {
3455 try {
3456 return mService.getGlobalProxy();
3457 } catch (RemoteException e) {
3458 throw e.rethrowFromSystemServer();
3459 }
3460 }
3461
3462 /**
3463 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3464 * network-specific HTTP proxy. If {@code network} is null, the
3465 * network-specific proxy returned is the proxy of the default active
3466 * network.
3467 *
3468 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3469 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3470 * or when {@code network} is {@code null},
3471 * the {@code ProxyInfo} for the default active network. Returns
3472 * {@code null} when no proxy applies or the caller doesn't have
3473 * permission to use {@code network}.
3474 * @hide
3475 */
3476 public ProxyInfo getProxyForNetwork(Network network) {
3477 try {
3478 return mService.getProxyForNetwork(network);
3479 } catch (RemoteException e) {
3480 throw e.rethrowFromSystemServer();
3481 }
3482 }
3483
3484 /**
3485 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3486 * otherwise if this process is bound to a {@link Network} using
3487 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3488 * the default network's proxy is returned.
3489 *
3490 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3491 * HTTP proxy is active.
3492 */
3493 @Nullable
3494 public ProxyInfo getDefaultProxy() {
3495 return getProxyForNetwork(getBoundNetworkForProcess());
3496 }
3497
3498 /**
3499 * Returns true if the hardware supports the given network type
3500 * else it returns false. This doesn't indicate we have coverage
3501 * or are authorized onto a network, just whether or not the
3502 * hardware supports it. For example a GSM phone without a SIM
3503 * should still return {@code true} for mobile data, but a wifi only
3504 * tablet would return {@code false}.
3505 *
3506 * @param networkType The network type we'd like to check
3507 * @return {@code true} if supported, else {@code false}
3508 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3509 * @hide
3510 */
3511 @Deprecated
3512 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3513 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3514 public boolean isNetworkSupported(int networkType) {
3515 try {
3516 return mService.isNetworkSupported(networkType);
3517 } catch (RemoteException e) {
3518 throw e.rethrowFromSystemServer();
3519 }
3520 }
3521
3522 /**
3523 * Returns if the currently active data network is metered. A network is
3524 * classified as metered when the user is sensitive to heavy data usage on
3525 * that connection due to monetary costs, data limitations or
3526 * battery/performance issues. You should check this before doing large
3527 * data transfers, and warn the user or delay the operation until another
3528 * network is available.
3529 *
3530 * @return {@code true} if large transfers should be avoided, otherwise
3531 * {@code false}.
3532 */
3533 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3534 public boolean isActiveNetworkMetered() {
3535 try {
3536 return mService.isActiveNetworkMetered();
3537 } catch (RemoteException e) {
3538 throw e.rethrowFromSystemServer();
3539 }
3540 }
3541
3542 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003543 * Set sign in error notification to visible or invisible
3544 *
3545 * @hide
3546 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3547 */
3548 @Deprecated
3549 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3550 String action) {
3551 try {
3552 mService.setProvisioningNotificationVisible(visible, networkType, action);
3553 } catch (RemoteException e) {
3554 throw e.rethrowFromSystemServer();
3555 }
3556 }
3557
3558 /**
3559 * Set the value for enabling/disabling airplane mode
3560 *
3561 * @param enable whether to enable airplane mode or not
3562 *
3563 * @hide
3564 */
3565 @RequiresPermission(anyOf = {
3566 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3567 android.Manifest.permission.NETWORK_SETTINGS,
3568 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3569 android.Manifest.permission.NETWORK_STACK})
3570 @SystemApi
3571 public void setAirplaneMode(boolean enable) {
3572 try {
3573 mService.setAirplaneMode(enable);
3574 } catch (RemoteException e) {
3575 throw e.rethrowFromSystemServer();
3576 }
3577 }
3578
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003579 /**
3580 * Registers the specified {@link NetworkProvider}.
3581 * Each listener must only be registered once. The listener can be unregistered with
3582 * {@link #unregisterNetworkProvider}.
3583 *
3584 * @param provider the provider to register
3585 * @return the ID of the provider. This ID must be used by the provider when registering
3586 * {@link android.net.NetworkAgent}s.
3587 * @hide
3588 */
3589 @SystemApi
3590 @RequiresPermission(anyOf = {
3591 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3592 android.Manifest.permission.NETWORK_FACTORY})
3593 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3594 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3595 throw new IllegalStateException("NetworkProviders can only be registered once");
3596 }
3597
3598 try {
3599 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3600 provider.getName());
3601 provider.setProviderId(providerId);
3602 } catch (RemoteException e) {
3603 throw e.rethrowFromSystemServer();
3604 }
3605 return provider.getProviderId();
3606 }
3607
3608 /**
3609 * Unregisters the specified NetworkProvider.
3610 *
3611 * @param provider the provider to unregister
3612 * @hide
3613 */
3614 @SystemApi
3615 @RequiresPermission(anyOf = {
3616 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3617 android.Manifest.permission.NETWORK_FACTORY})
3618 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3619 try {
3620 mService.unregisterNetworkProvider(provider.getMessenger());
3621 } catch (RemoteException e) {
3622 throw e.rethrowFromSystemServer();
3623 }
3624 provider.setProviderId(NetworkProvider.ID_NONE);
3625 }
3626
Chalard Jeand1b498b2021-01-05 08:40:09 +09003627 /**
3628 * Register or update a network offer with ConnectivityService.
3629 *
3630 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003631 * them to networking requests made by apps or the system. A callback identifies an offer
3632 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3633 * score and the capabilities of the network it might be able to bring up ; these act as
3634 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003635 * provider.
3636 *
3637 * The provider is under no obligation to be able to bring up the network it offers at any
3638 * given time. Instead, this mechanism is meant to limit requests received by providers
3639 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3640 * the quality of the network satisfying a given request to their own offer.
3641 *
3642 * An offer can be updated by calling this again with the same callback object. This is
3643 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3644 * provider with the changes caused by the changes in the offer.
3645 *
3646 * @param provider The provider making this offer.
3647 * @param score The prospective score of the network.
3648 * @param caps The prospective capabilities of the network.
3649 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003650 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003651 */
3652 @RequiresPermission(anyOf = {
3653 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3654 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003655 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003656 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3657 @NonNull final INetworkOfferCallback callback) {
3658 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003659 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003660 Objects.requireNonNull(score, "null score"),
3661 Objects.requireNonNull(caps, "null caps"),
3662 Objects.requireNonNull(callback, "null callback"));
3663 } catch (RemoteException e) {
3664 throw e.rethrowFromSystemServer();
3665 }
3666 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003667
Chalard Jeand1b498b2021-01-05 08:40:09 +09003668 /**
3669 * Withdraw a network offer made with {@link #offerNetwork}.
3670 *
3671 * @param callback The callback passed at registration time. This must be the same object
3672 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003673 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003674 */
3675 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3676 try {
3677 mService.unofferNetwork(Objects.requireNonNull(callback));
3678 } catch (RemoteException e) {
3679 throw e.rethrowFromSystemServer();
3680 }
3681 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003682 /** @hide exposed via the NetworkProvider class. */
3683 @RequiresPermission(anyOf = {
3684 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3685 android.Manifest.permission.NETWORK_FACTORY})
3686 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3687 try {
3688 mService.declareNetworkRequestUnfulfillable(request);
3689 } catch (RemoteException e) {
3690 throw e.rethrowFromSystemServer();
3691 }
3692 }
3693
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003694 /**
3695 * @hide
3696 * Register a NetworkAgent with ConnectivityService.
3697 * @return Network corresponding to NetworkAgent.
3698 */
3699 @RequiresPermission(anyOf = {
3700 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3701 android.Manifest.permission.NETWORK_FACTORY})
3702 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003703 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3704 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003705 try {
3706 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3707 } catch (RemoteException e) {
3708 throw e.rethrowFromSystemServer();
3709 }
3710 }
3711
3712 /**
3713 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3714 * changes. Should be extended by applications wanting notifications.
3715 *
3716 * A {@code NetworkCallback} is registered by calling
3717 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3718 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3719 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3720 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3721 * A {@code NetworkCallback} should be registered at most once at any time.
3722 * A {@code NetworkCallback} that has been unregistered can be registered again.
3723 */
3724 public static class NetworkCallback {
3725 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003726 * No flags associated with this callback.
3727 * @hide
3728 */
3729 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003730
Roshan Piuse08bc182020-12-22 15:10:42 -08003731 /**
lucaslinc582d502022-01-27 09:07:00 +08003732 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3733 *
3734 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3735 * Prior to Android 12, this information is always returned to apps holding the appropriate
3736 * permission, possibly noting that the app has used location.
3737 * <p>In Android 12 and above, by default the sent objects do not contain any location
3738 * information, even if the app holds the necessary permissions, and the system does not
3739 * take note of location usage by the app. Apps can request that location information is
3740 * included, in which case the system will check location permission and the location
3741 * toggle state, and take note of location usage by the app if any such information is
3742 * returned.
3743 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003744 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3745 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3746 * <p>
3747 * These include:
3748 * <li> Some transport info instances (retrieved via
3749 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3750 * contain location sensitive information.
3751 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003752 * sensitive for wifi suggestor apps (i.e using
3753 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003754 * </p>
3755 * <p>
3756 * Note:
3757 * <li> Retrieving this location sensitive information (subject to app's location
3758 * permissions) will be noted by system. </li>
3759 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003760 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003761 */
Roshan Pius189d0092021-03-11 21:16:44 -08003762 // Note: Some existing fields which are location sensitive may still be included without
3763 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003764 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3765
3766 /** @hide */
3767 @Retention(RetentionPolicy.SOURCE)
3768 @IntDef(flag = true, prefix = "FLAG_", value = {
3769 FLAG_NONE,
3770 FLAG_INCLUDE_LOCATION_INFO
3771 })
3772 public @interface Flag { }
3773
3774 /**
3775 * All the valid flags for error checking.
3776 */
3777 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3778
3779 public NetworkCallback() {
3780 this(FLAG_NONE);
3781 }
3782
3783 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003784 if ((flags & VALID_FLAGS) != flags) {
3785 throw new IllegalArgumentException("Invalid flags");
3786 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003787 mFlags = flags;
3788 }
3789
3790 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003791 * Called when the framework connects to a new network to evaluate whether it satisfies this
3792 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3793 * callback. There is no guarantee that this new network will satisfy any requests, or that
3794 * the network will stay connected for longer than the time necessary to evaluate it.
3795 * <p>
3796 * Most applications <b>should not</b> act on this callback, and should instead use
3797 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3798 * the framework in properly evaluating the network &mdash; for example, an application that
3799 * can automatically log in to a captive portal without user intervention.
3800 *
3801 * @param network The {@link Network} of the network that is being evaluated.
3802 *
3803 * @hide
3804 */
3805 public void onPreCheck(@NonNull Network network) {}
3806
3807 /**
3808 * Called when the framework connects and has declared a new network ready for use.
3809 * This callback may be called more than once if the {@link Network} that is
3810 * satisfying the request changes.
3811 *
3812 * @param network The {@link Network} of the satisfying network.
3813 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3814 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3815 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3816 * @hide
3817 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003818 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003819 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003820 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003821 // Internally only this method is called when a new network is available, and
3822 // it calls the callback in the same way and order that older versions used
3823 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003824 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3825 onBlockedStatusChanged(network, blocked);
3826 }
3827
3828 /**
3829 * Legacy variant of onAvailable that takes a boolean blocked reason.
3830 *
3831 * This method has never been public API, but it's not final, so there may be apps that
3832 * implemented it and rely on it being called. Do our best not to break them.
3833 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3834 * this method is called. There does not seem to be a way to avoid this.
3835 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3836 *
3837 * @hide
3838 */
3839 public void onAvailable(@NonNull Network network,
3840 @NonNull NetworkCapabilities networkCapabilities,
3841 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003842 onAvailable(network);
3843 if (!networkCapabilities.hasCapability(
3844 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3845 onNetworkSuspended(network);
3846 }
3847 onCapabilitiesChanged(network, networkCapabilities);
3848 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003849 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003850 }
3851
3852 /**
3853 * Called when the framework connects and has declared a new network ready for use.
3854 *
3855 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3856 * be available at the same time, and onAvailable will be called for each of these as they
3857 * appear.
3858 *
3859 * <p>For callbacks registered with {@link #requestNetwork} and
3860 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3861 * is the new best network for this request and is now tracked by this callback ; this
3862 * callback will no longer receive method calls about other networks that may have been
3863 * passed to this method previously. The previously-best network may have disconnected, or
3864 * it may still be around and the newly-best network may simply be better.
3865 *
3866 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3867 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3868 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3869 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3870 *
3871 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3872 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3873 * this callback as this is prone to race conditions (there is no guarantee the objects
3874 * returned by these methods will be current). Instead, wait for a call to
3875 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3876 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3877 * to be well-ordered with respect to other callbacks.
3878 *
3879 * @param network The {@link Network} of the satisfying network.
3880 */
3881 public void onAvailable(@NonNull Network network) {}
3882
3883 /**
3884 * Called when the network is about to be lost, typically because there are no outstanding
3885 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3886 * with the new replacement network for graceful handover. This method is not guaranteed
3887 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3888 * network is suddenly disconnected.
3889 *
3890 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3891 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3892 * this callback as this is prone to race conditions ; calling these methods while in a
3893 * callback may return an outdated or even a null object.
3894 *
3895 * @param network The {@link Network} that is about to be lost.
3896 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3897 * connected for graceful handover; note that the network may still
3898 * suffer a hard loss at any time.
3899 */
3900 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3901
3902 /**
3903 * Called when a network disconnects or otherwise no longer satisfies this request or
3904 * callback.
3905 *
3906 * <p>If the callback was registered with requestNetwork() or
3907 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3908 * returned by onAvailable() when that network is lost and no other network satisfies
3909 * the criteria of the request.
3910 *
3911 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3912 * each network which no longer satisfies the criteria of the callback.
3913 *
3914 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3915 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3916 * this callback as this is prone to race conditions ; calling these methods while in a
3917 * callback may return an outdated or even a null object.
3918 *
3919 * @param network The {@link Network} lost.
3920 */
3921 public void onLost(@NonNull Network network) {}
3922
3923 /**
3924 * Called if no network is found within the timeout time specified in
3925 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3926 * requested network request cannot be fulfilled (whether or not a timeout was
3927 * specified). When this callback is invoked the associated
3928 * {@link NetworkRequest} will have already been removed and released, as if
3929 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3930 */
3931 public void onUnavailable() {}
3932
3933 /**
3934 * Called when the network corresponding to this request changes capabilities but still
3935 * satisfies the requested criteria.
3936 *
3937 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3938 * to be called immediately after {@link #onAvailable}.
3939 *
3940 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3941 * ConnectivityManager methods in this callback as this is prone to race conditions :
3942 * calling these methods while in a callback may return an outdated or even a null object.
3943 *
3944 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003945 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003946 * network.
3947 */
3948 public void onCapabilitiesChanged(@NonNull Network network,
3949 @NonNull NetworkCapabilities networkCapabilities) {}
3950
3951 /**
3952 * Called when the network corresponding to this request changes {@link LinkProperties}.
3953 *
3954 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3955 * to be called immediately after {@link #onAvailable}.
3956 *
3957 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3958 * ConnectivityManager methods in this callback as this is prone to race conditions :
3959 * calling these methods while in a callback may return an outdated or even a null object.
3960 *
3961 * @param network The {@link Network} whose link properties have changed.
3962 * @param linkProperties The new {@link LinkProperties} for this network.
3963 */
3964 public void onLinkPropertiesChanged(@NonNull Network network,
3965 @NonNull LinkProperties linkProperties) {}
3966
3967 /**
3968 * Called when the network the framework connected to for this request suspends data
3969 * transmission temporarily.
3970 *
3971 * <p>This generally means that while the TCP connections are still live temporarily
3972 * network data fails to transfer. To give a specific example, this is used on cellular
3973 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3974 * means read operations on sockets on this network will block once the buffers are
3975 * drained, and write operations will block once the buffers are full.
3976 *
3977 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3978 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3979 * this callback as this is prone to race conditions (there is no guarantee the objects
3980 * returned by these methods will be current).
3981 *
3982 * @hide
3983 */
3984 public void onNetworkSuspended(@NonNull Network network) {}
3985
3986 /**
3987 * Called when the network the framework connected to for this request
3988 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3989 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3990
3991 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3992 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3993 * this callback as this is prone to race conditions : calling these methods while in a
3994 * callback may return an outdated or even a null object.
3995 *
3996 * @hide
3997 */
3998 public void onNetworkResumed(@NonNull Network network) {}
3999
4000 /**
4001 * Called when access to the specified network is blocked or unblocked.
4002 *
4003 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4004 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4005 * this callback as this is prone to race conditions : calling these methods while in a
4006 * callback may return an outdated or even a null object.
4007 *
4008 * @param network The {@link Network} whose blocked status has changed.
4009 * @param blocked The blocked status of this {@link Network}.
4010 */
4011 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4012
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004013 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004014 * Called when access to the specified network is blocked or unblocked, or the reason for
4015 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004016 *
4017 * If a NetworkCallback object implements this method,
4018 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4019 *
4020 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4021 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4022 * this callback as this is prone to race conditions : calling these methods while in a
4023 * callback may return an outdated or even a null object.
4024 *
4025 * @param network The {@link Network} whose blocked status has changed.
4026 * @param blocked The blocked status of this {@link Network}.
4027 * @hide
4028 */
4029 @SystemApi(client = MODULE_LIBRARIES)
4030 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4031 onBlockedStatusChanged(network, blocked != 0);
4032 }
4033
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004034 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004035 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004036 }
4037
4038 /**
4039 * Constant error codes used by ConnectivityService to communicate about failures and errors
4040 * across a Binder boundary.
4041 * @hide
4042 */
4043 public interface Errors {
4044 int TOO_MANY_REQUESTS = 1;
4045 }
4046
4047 /** @hide */
4048 public static class TooManyRequestsException extends RuntimeException {}
4049
4050 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4051 switch (e.errorCode) {
4052 case Errors.TOO_MANY_REQUESTS:
4053 return new TooManyRequestsException();
4054 default:
4055 Log.w(TAG, "Unknown service error code " + e.errorCode);
4056 return new RuntimeException(e);
4057 }
4058 }
4059
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004060 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004061 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004062 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004063 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004064 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004065 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004066 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004067 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004068 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004069 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004070 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004071 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004072 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004073 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004074 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004075 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004076 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004077 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004078 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004079 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004080 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004081 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004082
4083 /** @hide */
4084 public static String getCallbackName(int whichCallback) {
4085 switch (whichCallback) {
4086 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4087 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4088 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4089 case CALLBACK_LOST: return "CALLBACK_LOST";
4090 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4091 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4092 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4093 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4094 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4095 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4096 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4097 default:
4098 return Integer.toString(whichCallback);
4099 }
4100 }
4101
4102 private class CallbackHandler extends Handler {
4103 private static final String TAG = "ConnectivityManager.CallbackHandler";
4104 private static final boolean DBG = false;
4105
4106 CallbackHandler(Looper looper) {
4107 super(looper);
4108 }
4109
4110 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004111 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004112 }
4113
4114 @Override
4115 public void handleMessage(Message message) {
4116 if (message.what == EXPIRE_LEGACY_REQUEST) {
4117 expireRequest((NetworkCapabilities) message.obj, message.arg1);
4118 return;
4119 }
4120
4121 final NetworkRequest request = getObject(message, NetworkRequest.class);
4122 final Network network = getObject(message, Network.class);
4123 final NetworkCallback callback;
4124 synchronized (sCallbacks) {
4125 callback = sCallbacks.get(request);
4126 if (callback == null) {
4127 Log.w(TAG,
4128 "callback not found for " + getCallbackName(message.what) + " message");
4129 return;
4130 }
4131 if (message.what == CALLBACK_UNAVAIL) {
4132 sCallbacks.remove(request);
4133 callback.networkRequest = ALREADY_UNREGISTERED;
4134 }
4135 }
4136 if (DBG) {
4137 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4138 }
4139
4140 switch (message.what) {
4141 case CALLBACK_PRECHECK: {
4142 callback.onPreCheck(network);
4143 break;
4144 }
4145 case CALLBACK_AVAILABLE: {
4146 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4147 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004148 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004149 break;
4150 }
4151 case CALLBACK_LOSING: {
4152 callback.onLosing(network, message.arg1);
4153 break;
4154 }
4155 case CALLBACK_LOST: {
4156 callback.onLost(network);
4157 break;
4158 }
4159 case CALLBACK_UNAVAIL: {
4160 callback.onUnavailable();
4161 break;
4162 }
4163 case CALLBACK_CAP_CHANGED: {
4164 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4165 callback.onCapabilitiesChanged(network, cap);
4166 break;
4167 }
4168 case CALLBACK_IP_CHANGED: {
4169 LinkProperties lp = getObject(message, LinkProperties.class);
4170 callback.onLinkPropertiesChanged(network, lp);
4171 break;
4172 }
4173 case CALLBACK_SUSPENDED: {
4174 callback.onNetworkSuspended(network);
4175 break;
4176 }
4177 case CALLBACK_RESUMED: {
4178 callback.onNetworkResumed(network);
4179 break;
4180 }
4181 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004182 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004183 }
4184 }
4185 }
4186
4187 private <T> T getObject(Message msg, Class<T> c) {
4188 return (T) msg.getData().getParcelable(c.getSimpleName());
4189 }
4190 }
4191
4192 private CallbackHandler getDefaultHandler() {
4193 synchronized (sCallbacks) {
4194 if (sCallbackHandler == null) {
4195 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4196 }
4197 return sCallbackHandler;
4198 }
4199 }
4200
4201 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4202 private static CallbackHandler sCallbackHandler;
4203
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004204 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4205 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4206 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004207 printStackTrace();
4208 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004209 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4210 throw new IllegalArgumentException("null NetworkCapabilities");
4211 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004212 final NetworkRequest request;
4213 final String callingPackageName = mContext.getOpPackageName();
4214 try {
4215 synchronized(sCallbacks) {
4216 if (callback.networkRequest != null
4217 && callback.networkRequest != ALREADY_UNREGISTERED) {
4218 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4219 // and requests (http://b/20701525).
4220 Log.e(TAG, "NetworkCallback was already registered");
4221 }
4222 Messenger messenger = new Messenger(handler);
4223 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004224 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004225 if (reqType == LISTEN) {
4226 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004227 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004228 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004229 } else {
4230 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004231 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4232 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004233 }
4234 if (request != null) {
4235 sCallbacks.put(request, callback);
4236 }
4237 callback.networkRequest = request;
4238 }
4239 } catch (RemoteException e) {
4240 throw e.rethrowFromSystemServer();
4241 } catch (ServiceSpecificException e) {
4242 throw convertServiceException(e);
4243 }
4244 return request;
4245 }
4246
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004247 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4248 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4249 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4250 legacyType, handler);
4251 }
4252
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004253 /**
4254 * Helper function to request a network with a particular legacy type.
4255 *
4256 * This API is only for use in internal system code that requests networks with legacy type and
4257 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4258 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4259 *
4260 * @param request {@link NetworkRequest} describing this request.
4261 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4262 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4263 * be a positive value (i.e. >0).
4264 * @param legacyType to specify the network type(#TYPE_*).
4265 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4266 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4267 * the callback must not be shared - it uniquely specifies this request.
4268 *
4269 * @hide
4270 */
4271 @SystemApi
4272 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4273 public void requestNetwork(@NonNull NetworkRequest request,
4274 int timeoutMs, int legacyType, @NonNull Handler handler,
4275 @NonNull NetworkCallback networkCallback) {
4276 if (legacyType == TYPE_NONE) {
4277 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4278 }
4279 CallbackHandler cbHandler = new CallbackHandler(handler);
4280 NetworkCapabilities nc = request.networkCapabilities;
4281 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4282 }
4283
4284 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004285 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004286 *
4287 * <p>This method will attempt to find the best network that matches the passed
4288 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4289 * criteria. The platform will evaluate which network is the best at its own discretion.
4290 * Throughput, latency, cost per byte, policy, user preference and other considerations
4291 * may be factored in the decision of what is considered the best network.
4292 *
4293 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4294 * matching this request, while always attempting to match the request to a better network if
4295 * possible. If a better match is found, the platform will switch this request to the now-best
4296 * network and inform the app of the newly best network by invoking
4297 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4298 * will not try to maintain any other network than the best one currently matching the request:
4299 * a network not matching any network request may be disconnected at any time.
4300 *
4301 * <p>For example, an application could use this method to obtain a connected cellular network
4302 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4303 * radio to consume additional power. Or, an application could inform the system that it wants
4304 * a network supporting sending MMSes and have the system let it know about the currently best
4305 * MMS-supporting network through the provided {@link NetworkCallback}.
4306 *
4307 * <p>The status of the request can be followed by listening to the various callbacks described
4308 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4309 * used to direct traffic to the network (although accessing some networks may be subject to
4310 * holding specific permissions). Callers will learn about the specific characteristics of the
4311 * network through
4312 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4313 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4314 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4315 * matching the request at any given time; therefore when a better network matching the request
4316 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4317 * with the new network after which no further updates are given about the previously-best
4318 * network, unless it becomes the best again at some later time. All callbacks are invoked
4319 * in order on the same thread, which by default is a thread created by the framework running
4320 * in the app.
4321 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4322 * callbacks are invoked.
4323 *
4324 * <p>This{@link NetworkRequest} will live until released via
4325 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4326 * which point the system may let go of the network at any time.
4327 *
4328 * <p>A version of this method which takes a timeout is
4329 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4330 * wait for a limited amount of time for the network to become unavailable.
4331 *
4332 * <p>It is presently unsupported to request a network with mutable
4333 * {@link NetworkCapabilities} such as
4334 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4335 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4336 * as these {@code NetworkCapabilities} represent states that a particular
4337 * network may never attain, and whether a network will attain these states
4338 * is unknown prior to bringing up the network so the framework does not
4339 * know how to go about satisfying a request with these capabilities.
4340 *
4341 * <p>This method requires the caller to hold either the
4342 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4343 * or the ability to modify system settings as determined by
4344 * {@link android.provider.Settings.System#canWrite}.</p>
4345 *
4346 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4347 * number of outstanding requests to 100 per app (identified by their UID), shared with
4348 * all variants of this method, of {@link #registerNetworkCallback} as well as
4349 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4350 * Requesting a network with this method will count toward this limit. If this limit is
4351 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4352 * make sure to unregister the callbacks with
4353 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4354 *
4355 * @param request {@link NetworkRequest} describing this request.
4356 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4357 * the callback must not be shared - it uniquely specifies this request.
4358 * The callback is invoked on the default internal Handler.
4359 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4360 * @throws SecurityException if missing the appropriate permissions.
4361 * @throws RuntimeException if the app already has too many callbacks registered.
4362 */
4363 public void requestNetwork(@NonNull NetworkRequest request,
4364 @NonNull NetworkCallback networkCallback) {
4365 requestNetwork(request, networkCallback, getDefaultHandler());
4366 }
4367
4368 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004369 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004370 *
4371 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4372 * but runs all the callbacks on the passed Handler.
4373 *
4374 * <p>This method has the same permission requirements as
4375 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4376 * and throws the same exceptions in the same conditions.
4377 *
4378 * @param request {@link NetworkRequest} describing this request.
4379 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4380 * the callback must not be shared - it uniquely specifies this request.
4381 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4382 */
4383 public void requestNetwork(@NonNull NetworkRequest request,
4384 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4385 CallbackHandler cbHandler = new CallbackHandler(handler);
4386 NetworkCapabilities nc = request.networkCapabilities;
4387 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4388 }
4389
4390 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004391 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004392 * by a timeout.
4393 *
4394 * This function behaves identically to the non-timed-out version
4395 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4396 * is not found within the given time (in milliseconds) the
4397 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4398 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4399 * not have to be released if timed-out (it is automatically released). Unregistering a
4400 * request that timed out is not an error.
4401 *
4402 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4403 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4404 * for that purpose. Calling this method will attempt to bring up the requested network.
4405 *
4406 * <p>This method has the same permission requirements as
4407 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4408 * and throws the same exceptions in the same conditions.
4409 *
4410 * @param request {@link NetworkRequest} describing this request.
4411 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4412 * the callback must not be shared - it uniquely specifies this request.
4413 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4414 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4415 * be a positive value (i.e. >0).
4416 */
4417 public void requestNetwork(@NonNull NetworkRequest request,
4418 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4419 checkTimeout(timeoutMs);
4420 NetworkCapabilities nc = request.networkCapabilities;
4421 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4422 getDefaultHandler());
4423 }
4424
4425 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004426 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004427 * by a timeout.
4428 *
4429 * This method behaves identically to
4430 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4431 * on the passed Handler.
4432 *
4433 * <p>This method has the same permission requirements as
4434 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4435 * and throws the same exceptions in the same conditions.
4436 *
4437 * @param request {@link NetworkRequest} describing this request.
4438 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4439 * the callback must not be shared - it uniquely specifies this request.
4440 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4441 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4442 * before {@link NetworkCallback#onUnavailable} is called.
4443 */
4444 public void requestNetwork(@NonNull NetworkRequest request,
4445 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4446 checkTimeout(timeoutMs);
4447 CallbackHandler cbHandler = new CallbackHandler(handler);
4448 NetworkCapabilities nc = request.networkCapabilities;
4449 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4450 }
4451
4452 /**
4453 * The lookup key for a {@link Network} object included with the intent after
4454 * successfully finding a network for the applications request. Retrieve it with
4455 * {@link android.content.Intent#getParcelableExtra(String)}.
4456 * <p>
4457 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4458 * then you must get a ConnectivityManager instance before doing so.
4459 */
4460 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4461
4462 /**
4463 * The lookup key for a {@link NetworkRequest} object included with the intent after
4464 * successfully finding a network for the applications request. Retrieve it with
4465 * {@link android.content.Intent#getParcelableExtra(String)}.
4466 */
4467 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4468
4469
4470 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004471 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004472 *
4473 * This function behaves identically to the version that takes a NetworkCallback, but instead
4474 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4475 * the request may outlive the calling application and get called back when a suitable
4476 * network is found.
4477 * <p>
4478 * The operation is an Intent broadcast that goes to a broadcast receiver that
4479 * you registered with {@link Context#registerReceiver} or through the
4480 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4481 * <p>
4482 * The operation Intent is delivered with two extras, a {@link Network} typed
4483 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4484 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4485 * the original requests parameters. It is important to create a new,
4486 * {@link NetworkCallback} based request before completing the processing of the
4487 * Intent to reserve the network or it will be released shortly after the Intent
4488 * is processed.
4489 * <p>
4490 * If there is already a request for this Intent registered (with the equality of
4491 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4492 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4493 * <p>
4494 * The request may be released normally by calling
4495 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4496 * <p>It is presently unsupported to request a network with either
4497 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4498 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4499 * as these {@code NetworkCapabilities} represent states that a particular
4500 * network may never attain, and whether a network will attain these states
4501 * is unknown prior to bringing up the network so the framework does not
4502 * know how to go about satisfying a request with these capabilities.
4503 *
4504 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4505 * number of outstanding requests to 100 per app (identified by their UID), shared with
4506 * all variants of this method, of {@link #registerNetworkCallback} as well as
4507 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4508 * Requesting a network with this method will count toward this limit. If this limit is
4509 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4510 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4511 * or {@link #releaseNetworkRequest(PendingIntent)}.
4512 *
4513 * <p>This method requires the caller to hold either the
4514 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4515 * or the ability to modify system settings as determined by
4516 * {@link android.provider.Settings.System#canWrite}.</p>
4517 *
4518 * @param request {@link NetworkRequest} describing this request.
4519 * @param operation Action to perform when the network is available (corresponds
4520 * to the {@link NetworkCallback#onAvailable} call. Typically
4521 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4522 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4523 * @throws SecurityException if missing the appropriate permissions.
4524 * @throws RuntimeException if the app already has too many callbacks registered.
4525 */
4526 public void requestNetwork(@NonNull NetworkRequest request,
4527 @NonNull PendingIntent operation) {
4528 printStackTrace();
4529 checkPendingIntentNotNull(operation);
4530 try {
4531 mService.pendingRequestForNetwork(
4532 request.networkCapabilities, operation, mContext.getOpPackageName(),
4533 getAttributionTag());
4534 } catch (RemoteException e) {
4535 throw e.rethrowFromSystemServer();
4536 } catch (ServiceSpecificException e) {
4537 throw convertServiceException(e);
4538 }
4539 }
4540
4541 /**
4542 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4543 * <p>
4544 * This method has the same behavior as
4545 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4546 * releasing network resources and disconnecting.
4547 *
4548 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4549 * PendingIntent passed to
4550 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4551 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4552 */
4553 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4554 printStackTrace();
4555 checkPendingIntentNotNull(operation);
4556 try {
4557 mService.releasePendingNetworkRequest(operation);
4558 } catch (RemoteException e) {
4559 throw e.rethrowFromSystemServer();
4560 }
4561 }
4562
4563 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004564 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004565 }
4566
4567 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004568 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004569 }
4570
4571 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004572 if (timeoutMs <= 0) {
4573 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4574 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004575 }
4576
4577 /**
4578 * Registers to receive notifications about all networks which satisfy the given
4579 * {@link NetworkRequest}. The callbacks will continue to be called until
4580 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4581 * called.
4582 *
4583 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4584 * number of outstanding requests to 100 per app (identified by their UID), shared with
4585 * all variants of this method, of {@link #requestNetwork} as well as
4586 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4587 * Requesting a network with this method will count toward this limit. If this limit is
4588 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4589 * make sure to unregister the callbacks with
4590 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4591 *
4592 * @param request {@link NetworkRequest} describing this request.
4593 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4594 * networks change state.
4595 * The callback is invoked on the default internal Handler.
4596 * @throws RuntimeException if the app already has too many callbacks registered.
4597 */
4598 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4599 public void registerNetworkCallback(@NonNull NetworkRequest request,
4600 @NonNull NetworkCallback networkCallback) {
4601 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4602 }
4603
4604 /**
4605 * Registers to receive notifications about all networks which satisfy the given
4606 * {@link NetworkRequest}. The callbacks will continue to be called until
4607 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4608 * called.
4609 *
4610 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4611 * number of outstanding requests to 100 per app (identified by their UID), shared with
4612 * all variants of this method, of {@link #requestNetwork} as well as
4613 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4614 * Requesting a network with this method will count toward this limit. If this limit is
4615 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4616 * make sure to unregister the callbacks with
4617 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4618 *
4619 *
4620 * @param request {@link NetworkRequest} describing this request.
4621 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4622 * networks change state.
4623 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
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 NetworkCallback networkCallback, @NonNull Handler handler) {
4629 CallbackHandler cbHandler = new CallbackHandler(handler);
4630 NetworkCapabilities nc = request.networkCapabilities;
4631 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4632 }
4633
4634 /**
4635 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4636 * {@link NetworkRequest}.
4637 *
4638 * This function behaves identically to the version that takes a NetworkCallback, but instead
4639 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4640 * the request may outlive the calling application and get called back when a suitable
4641 * network is found.
4642 * <p>
4643 * The operation is an Intent broadcast that goes to a broadcast receiver that
4644 * you registered with {@link Context#registerReceiver} or through the
4645 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4646 * <p>
4647 * The operation Intent is delivered with two extras, a {@link Network} typed
4648 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4649 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4650 * the original requests parameters.
4651 * <p>
4652 * If there is already a request for this Intent registered (with the equality of
4653 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4654 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4655 * <p>
4656 * The request may be released normally by calling
4657 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4658 *
4659 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4660 * number of outstanding requests to 100 per app (identified by their UID), shared with
4661 * all variants of this method, of {@link #requestNetwork} as well as
4662 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4663 * Requesting a network with this method will count toward this limit. If this limit is
4664 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4665 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4666 * or {@link #releaseNetworkRequest(PendingIntent)}.
4667 *
4668 * @param request {@link NetworkRequest} describing this request.
4669 * @param operation Action to perform when the network is available (corresponds
4670 * to the {@link NetworkCallback#onAvailable} call. Typically
4671 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4672 * @throws RuntimeException if the app already has too many callbacks registered.
4673 */
4674 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4675 public void registerNetworkCallback(@NonNull NetworkRequest request,
4676 @NonNull PendingIntent operation) {
4677 printStackTrace();
4678 checkPendingIntentNotNull(operation);
4679 try {
4680 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004681 request.networkCapabilities, operation, mContext.getOpPackageName(),
4682 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004683 } catch (RemoteException e) {
4684 throw e.rethrowFromSystemServer();
4685 } catch (ServiceSpecificException e) {
4686 throw convertServiceException(e);
4687 }
4688 }
4689
4690 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004691 * Registers to receive notifications about changes in the application's default network. This
4692 * may be a physical network or a virtual network, such as a VPN that applies to the
4693 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004694 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4695 *
4696 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4697 * number of outstanding requests to 100 per app (identified by their UID), shared with
4698 * all variants of this method, of {@link #requestNetwork} as well as
4699 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4700 * Requesting a network with this method will count toward this limit. If this limit is
4701 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4702 * make sure to unregister the callbacks with
4703 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4704 *
4705 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004706 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004707 * The callback is invoked on the default internal Handler.
4708 * @throws RuntimeException if the app already has too many callbacks registered.
4709 */
4710 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4711 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4712 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4713 }
4714
4715 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004716 * Registers to receive notifications about changes in the application's default network. This
4717 * may be a physical network or a virtual network, such as a VPN that applies to the
4718 * application. The callbacks will continue to be called until either the application exits or
4719 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4720 *
4721 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4722 * number of outstanding requests to 100 per app (identified by their UID), shared with
4723 * all variants of this method, of {@link #requestNetwork} as well as
4724 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4725 * Requesting a network with this method will count toward this limit. If this limit is
4726 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4727 * make sure to unregister the callbacks with
4728 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4729 *
4730 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4731 * application's default network changes.
4732 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4733 * @throws RuntimeException if the app already has too many callbacks registered.
4734 */
4735 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4736 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4737 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004738 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004739 }
4740
4741 /**
4742 * Registers to receive notifications about changes in the default network for the specified
4743 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4744 * UID. The callbacks will continue to be called until either the application exits or
4745 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4746 *
4747 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4748 * number of outstanding requests to 100 per app (identified by their UID), shared with
4749 * all variants of this method, of {@link #requestNetwork} as well as
4750 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4751 * Requesting a network with this method will count toward this limit. If this limit is
4752 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4753 * make sure to unregister the callbacks with
4754 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4755 *
4756 * @param uid the UID for which to track default network changes.
4757 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4758 * UID's default network changes.
4759 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4760 * @throws RuntimeException if the app already has too many callbacks registered.
4761 * @hide
4762 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004763 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004764 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4765 @RequiresPermission(anyOf = {
4766 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4767 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004768 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004769 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004770 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004771 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004772 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4773 }
4774
4775 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004776 * Registers to receive notifications about changes in the system default network. The callbacks
4777 * will continue to be called until either the application exits or
4778 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4779 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004780 * This method should not be used to determine networking state seen by applications, because in
4781 * many cases, most or even all application traffic may not use the default network directly,
4782 * and traffic from different applications may go on different networks by default. As an
4783 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4784 * and not onto the system default network. Applications or system components desiring to do
4785 * determine network state as seen by applications should use other methods such as
4786 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4787 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004788 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4789 * number of outstanding requests to 100 per app (identified by their UID), shared with
4790 * all variants of this method, of {@link #requestNetwork} as well as
4791 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4792 * Requesting a network with this method will count toward this limit. If this limit is
4793 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4794 * make sure to unregister the callbacks with
4795 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4796 *
4797 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4798 * system default network changes.
4799 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4800 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004801 *
4802 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004803 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004804 @SystemApi(client = MODULE_LIBRARIES)
4805 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4806 @RequiresPermission(anyOf = {
4807 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4808 android.Manifest.permission.NETWORK_SETTINGS})
4809 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004810 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004811 CallbackHandler cbHandler = new CallbackHandler(handler);
4812 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004813 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004814 }
4815
4816 /**
junyulaibd123062021-03-15 11:48:48 +08004817 * Registers to receive notifications about the best matching network which satisfy the given
4818 * {@link NetworkRequest}. The callbacks will continue to be called until
4819 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4820 * called.
4821 *
4822 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4823 * number of outstanding requests to 100 per app (identified by their UID), shared with
4824 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4825 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4826 * Requesting a network with this method will count toward this limit. If this limit is
4827 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4828 * make sure to unregister the callbacks with
4829 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4830 *
4831 *
4832 * @param request {@link NetworkRequest} describing this request.
4833 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4834 * networks change state.
4835 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4836 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004837 */
junyulai5a5c99b2021-03-05 15:51:17 +08004838 @SuppressLint("ExecutorRegistration")
4839 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4840 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4841 final NetworkCapabilities nc = request.networkCapabilities;
4842 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004843 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004844 }
4845
4846 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004847 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4848 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4849 * network connection for updated bandwidth information. The caller will be notified via
4850 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4851 * method assumes that the caller has previously called
4852 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4853 * changes.
4854 *
4855 * @param network {@link Network} specifying which network you're interested.
4856 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4857 */
4858 public boolean requestBandwidthUpdate(@NonNull Network network) {
4859 try {
4860 return mService.requestBandwidthUpdate(network);
4861 } catch (RemoteException e) {
4862 throw e.rethrowFromSystemServer();
4863 }
4864 }
4865
4866 /**
4867 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4868 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4869 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4870 * If the given {@code NetworkCallback} had previously been used with
4871 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4872 * will be disconnected.
4873 *
4874 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4875 * triggering it as soon as this call returns.
4876 *
4877 * @param networkCallback The {@link NetworkCallback} used when making the request.
4878 */
4879 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4880 printStackTrace();
4881 checkCallbackNotNull(networkCallback);
4882 final List<NetworkRequest> reqs = new ArrayList<>();
4883 // Find all requests associated to this callback and stop callback triggers immediately.
4884 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4885 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004886 if (networkCallback.networkRequest == null) {
4887 throw new IllegalArgumentException("NetworkCallback was not registered");
4888 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004889 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4890 Log.d(TAG, "NetworkCallback was already unregistered");
4891 return;
4892 }
4893 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4894 if (e.getValue() == networkCallback) {
4895 reqs.add(e.getKey());
4896 }
4897 }
4898 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4899 for (NetworkRequest r : reqs) {
4900 try {
4901 mService.releaseNetworkRequest(r);
4902 } catch (RemoteException e) {
4903 throw e.rethrowFromSystemServer();
4904 }
4905 // Only remove mapping if rpc was successful.
4906 sCallbacks.remove(r);
4907 }
4908 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4909 }
4910 }
4911
4912 /**
4913 * Unregisters a callback previously registered via
4914 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4915 *
4916 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4917 * PendingIntent passed to
4918 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4919 * Cannot be null.
4920 */
4921 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4922 releaseNetworkRequest(operation);
4923 }
4924
4925 /**
4926 * Informs the system whether it should switch to {@code network} regardless of whether it is
4927 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4928 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4929 * the system default network regardless of any other network that's currently connected. If
4930 * {@code always} is true, then the choice is remembered, so that the next time the user
4931 * connects to this network, the system will switch to it.
4932 *
4933 * @param network The network to accept.
4934 * @param accept Whether to accept the network even if unvalidated.
4935 * @param always Whether to remember this choice in the future.
4936 *
4937 * @hide
4938 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004939 @SystemApi(client = MODULE_LIBRARIES)
4940 @RequiresPermission(anyOf = {
4941 android.Manifest.permission.NETWORK_SETTINGS,
4942 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4943 android.Manifest.permission.NETWORK_STACK,
4944 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4945 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004946 try {
4947 mService.setAcceptUnvalidated(network, accept, always);
4948 } catch (RemoteException e) {
4949 throw e.rethrowFromSystemServer();
4950 }
4951 }
4952
4953 /**
4954 * Informs the system whether it should consider the network as validated even if it only has
4955 * partial connectivity. If {@code accept} is true, then the network will be considered as
4956 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4957 * is remembered, so that the next time the user connects to this network, the system will
4958 * switch to it.
4959 *
4960 * @param network The network to accept.
4961 * @param accept Whether to consider the network as validated even if it has partial
4962 * connectivity.
4963 * @param always Whether to remember this choice in the future.
4964 *
4965 * @hide
4966 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004967 @SystemApi(client = MODULE_LIBRARIES)
4968 @RequiresPermission(anyOf = {
4969 android.Manifest.permission.NETWORK_SETTINGS,
4970 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4971 android.Manifest.permission.NETWORK_STACK,
4972 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4973 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4974 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004975 try {
4976 mService.setAcceptPartialConnectivity(network, accept, always);
4977 } catch (RemoteException e) {
4978 throw e.rethrowFromSystemServer();
4979 }
4980 }
4981
4982 /**
4983 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4984 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4985 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4986 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4987 *
4988 * @param network The network to accept.
4989 *
4990 * @hide
4991 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004992 @SystemApi(client = MODULE_LIBRARIES)
4993 @RequiresPermission(anyOf = {
4994 android.Manifest.permission.NETWORK_SETTINGS,
4995 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4996 android.Manifest.permission.NETWORK_STACK,
4997 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4998 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004999 try {
5000 mService.setAvoidUnvalidated(network);
5001 } catch (RemoteException e) {
5002 throw e.rethrowFromSystemServer();
5003 }
5004 }
5005
5006 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005007 * Temporarily allow bad wifi to override {@code config_networkAvoidBadWifi} configuration.
5008 *
5009 * @param timeMs The expired current time. The value should be set within a limited time from
5010 * now.
5011 *
5012 * @hide
5013 */
5014 public void setTestAllowBadWifiUntil(long timeMs) {
5015 try {
5016 mService.setTestAllowBadWifiUntil(timeMs);
5017 } catch (RemoteException e) {
5018 throw e.rethrowFromSystemServer();
5019 }
5020 }
5021
5022 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005023 * Requests that the system open the captive portal app on the specified network.
5024 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005025 * <p>This is to be used on networks where a captive portal was detected, as per
5026 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5027 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005028 * @param network The network to log into.
5029 *
5030 * @hide
5031 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005032 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5033 @RequiresPermission(anyOf = {
5034 android.Manifest.permission.NETWORK_SETTINGS,
5035 android.Manifest.permission.NETWORK_STACK,
5036 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5037 })
5038 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005039 try {
5040 mService.startCaptivePortalApp(network);
5041 } catch (RemoteException e) {
5042 throw e.rethrowFromSystemServer();
5043 }
5044 }
5045
5046 /**
5047 * Requests that the system open the captive portal app with the specified extras.
5048 *
5049 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5050 * corresponding permission.
5051 * @param network Network on which the captive portal was detected.
5052 * @param appExtras Extras to include in the app start intent.
5053 * @hide
5054 */
5055 @SystemApi
5056 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5057 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5058 try {
5059 mService.startCaptivePortalAppInternal(network, appExtras);
5060 } catch (RemoteException e) {
5061 throw e.rethrowFromSystemServer();
5062 }
5063 }
5064
5065 /**
5066 * Determine whether the device is configured to avoid bad wifi.
5067 * @hide
5068 */
5069 @SystemApi
5070 @RequiresPermission(anyOf = {
5071 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5072 android.Manifest.permission.NETWORK_STACK})
5073 public boolean shouldAvoidBadWifi() {
5074 try {
5075 return mService.shouldAvoidBadWifi();
5076 } catch (RemoteException e) {
5077 throw e.rethrowFromSystemServer();
5078 }
5079 }
5080
5081 /**
5082 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5083 * time-sensitive user-facing operations when the system default network is temporarily
5084 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5085 * this method), and the operation should be infrequent to ensure that data usage is limited.
5086 *
5087 * An example of such an operation might be a time-sensitive foreground activity, such as a
5088 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5089 */
5090 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5091
5092 /**
5093 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5094 * a backup channel for traffic that is primarily going over another network.
5095 *
5096 * An example might be maintaining backup connections to peers or servers for the purpose of
5097 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5098 * on backup paths should be negligible compared to the traffic on the main path.
5099 */
5100 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5101
5102 /**
5103 * It is acceptable to use metered data to improve network latency and performance.
5104 */
5105 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5106
5107 /**
5108 * Return value to use for unmetered networks. On such networks we currently set all the flags
5109 * to true.
5110 * @hide
5111 */
5112 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5113 MULTIPATH_PREFERENCE_HANDOVER |
5114 MULTIPATH_PREFERENCE_RELIABILITY |
5115 MULTIPATH_PREFERENCE_PERFORMANCE;
5116
Aaron Huangcff22942021-05-27 16:31:26 +08005117 /** @hide */
5118 @Retention(RetentionPolicy.SOURCE)
5119 @IntDef(flag = true, value = {
5120 MULTIPATH_PREFERENCE_HANDOVER,
5121 MULTIPATH_PREFERENCE_RELIABILITY,
5122 MULTIPATH_PREFERENCE_PERFORMANCE,
5123 })
5124 public @interface MultipathPreference {
5125 }
5126
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005127 /**
5128 * Provides a hint to the calling application on whether it is desirable to use the
5129 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5130 * for multipath data transfer on this network when it is not the system default network.
5131 * Applications desiring to use multipath network protocols should call this method before
5132 * each such operation.
5133 *
5134 * @param network The network on which the application desires to use multipath data.
5135 * If {@code null}, this method will return the a preference that will generally
5136 * apply to metered networks.
5137 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
5138 */
5139 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5140 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5141 try {
5142 return mService.getMultipathPreference(network);
5143 } catch (RemoteException e) {
5144 throw e.rethrowFromSystemServer();
5145 }
5146 }
5147
5148 /**
5149 * Resets all connectivity manager settings back to factory defaults.
5150 * @hide
5151 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005152 @SystemApi(client = MODULE_LIBRARIES)
5153 @RequiresPermission(anyOf = {
5154 android.Manifest.permission.NETWORK_SETTINGS,
5155 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005156 public void factoryReset() {
5157 try {
5158 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005159 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005160 } catch (RemoteException e) {
5161 throw e.rethrowFromSystemServer();
5162 }
5163 }
5164
5165 /**
5166 * Binds the current process to {@code network}. All Sockets created in the future
5167 * (and not explicitly bound via a bound SocketFactory from
5168 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5169 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5170 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5171 * work and all host name resolutions will fail. This is by design so an application doesn't
5172 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5173 * To clear binding pass {@code null} for {@code network}. Using individually bound
5174 * Sockets created by Network.getSocketFactory().createSocket() and
5175 * performing network-specific host name resolutions via
5176 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5177 * {@code bindProcessToNetwork}.
5178 *
5179 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5180 * the current binding.
5181 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5182 */
5183 public boolean bindProcessToNetwork(@Nullable Network network) {
5184 // Forcing callers to call through non-static function ensures ConnectivityManager
5185 // instantiated.
5186 return setProcessDefaultNetwork(network);
5187 }
5188
5189 /**
5190 * Binds the current process to {@code network}. All Sockets created in the future
5191 * (and not explicitly bound via a bound SocketFactory from
5192 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5193 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5194 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5195 * work and all host name resolutions will fail. This is by design so an application doesn't
5196 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5197 * To clear binding pass {@code null} for {@code network}. Using individually bound
5198 * Sockets created by Network.getSocketFactory().createSocket() and
5199 * performing network-specific host name resolutions via
5200 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5201 * {@code setProcessDefaultNetwork}.
5202 *
5203 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5204 * the current binding.
5205 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5206 * @deprecated This function can throw {@link IllegalStateException}. Use
5207 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5208 * is a direct replacement.
5209 */
5210 @Deprecated
5211 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5212 int netId = (network == null) ? NETID_UNSET : network.netId;
5213 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5214
5215 if (netId != NETID_UNSET) {
5216 netId = network.getNetIdForResolv();
5217 }
5218
5219 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5220 return false;
5221 }
5222
5223 if (!isSameNetId) {
5224 // Set HTTP proxy system properties to match network.
5225 // TODO: Deprecate this static method and replace it with a non-static version.
5226 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005227 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005228 } catch (SecurityException e) {
5229 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5230 Log.e(TAG, "Can't set proxy properties", e);
5231 }
5232 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005233 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005234 // Must flush socket pool as idle sockets will be bound to previous network and may
5235 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005236 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005237 }
5238
5239 return true;
5240 }
5241
5242 /**
5243 * Returns the {@link Network} currently bound to this process via
5244 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5245 *
5246 * @return {@code Network} to which this process is bound, or {@code null}.
5247 */
5248 @Nullable
5249 public Network getBoundNetworkForProcess() {
5250 // Forcing callers to call thru non-static function ensures ConnectivityManager
5251 // instantiated.
5252 return getProcessDefaultNetwork();
5253 }
5254
5255 /**
5256 * Returns the {@link Network} currently bound to this process via
5257 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5258 *
5259 * @return {@code Network} to which this process is bound, or {@code null}.
5260 * @deprecated Using this function can lead to other functions throwing
5261 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5262 * {@code getBoundNetworkForProcess} is a direct replacement.
5263 */
5264 @Deprecated
5265 @Nullable
5266 public static Network getProcessDefaultNetwork() {
5267 int netId = NetworkUtils.getBoundNetworkForProcess();
5268 if (netId == NETID_UNSET) return null;
5269 return new Network(netId);
5270 }
5271
5272 private void unsupportedStartingFrom(int version) {
5273 if (Process.myUid() == Process.SYSTEM_UID) {
5274 // The getApplicationInfo() call we make below is not supported in system context. Let
5275 // the call through here, and rely on the fact that ConnectivityService will refuse to
5276 // allow the system to use these APIs anyway.
5277 return;
5278 }
5279
5280 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5281 throw new UnsupportedOperationException(
5282 "This method is not supported in target SDK version " + version + " and above");
5283 }
5284 }
5285
5286 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5287 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5288 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5289 // remove these exemptions. Note that this check is not secure, and apps can still access these
5290 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5291 // so is unsupported and may break in the future. http://b/22728205
5292 private void checkLegacyRoutingApiAccess() {
5293 unsupportedStartingFrom(VERSION_CODES.M);
5294 }
5295
5296 /**
5297 * Binds host resolutions performed by this process to {@code network}.
5298 * {@link #bindProcessToNetwork} takes precedence over this setting.
5299 *
5300 * @param network The {@link Network} to bind host resolutions from the current process to, or
5301 * {@code null} to clear the current binding.
5302 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5303 * @hide
5304 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5305 */
5306 @Deprecated
5307 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5308 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5309 return NetworkUtils.bindProcessToNetworkForHostResolution(
5310 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5311 }
5312
5313 /**
5314 * Device is not restricting metered network activity while application is running on
5315 * background.
5316 */
5317 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5318
5319 /**
5320 * Device is restricting metered network activity while application is running on background,
5321 * but application is allowed to bypass it.
5322 * <p>
5323 * In this state, application should take action to mitigate metered network access.
5324 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5325 */
5326 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5327
5328 /**
5329 * Device is restricting metered network activity while application is running on background.
5330 * <p>
5331 * In this state, application should not try to use the network while running on background,
5332 * because it would be denied.
5333 */
5334 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5335
5336 /**
5337 * A change in the background metered network activity restriction has occurred.
5338 * <p>
5339 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5340 * applies to them.
5341 * <p>
5342 * This is only sent to registered receivers, not manifest receivers.
5343 */
5344 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5345 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5346 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5347
Aaron Huangcff22942021-05-27 16:31:26 +08005348 /** @hide */
5349 @Retention(RetentionPolicy.SOURCE)
5350 @IntDef(flag = false, value = {
5351 RESTRICT_BACKGROUND_STATUS_DISABLED,
5352 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5353 RESTRICT_BACKGROUND_STATUS_ENABLED,
5354 })
5355 public @interface RestrictBackgroundStatus {
5356 }
5357
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005358 /**
5359 * Determines if the calling application is subject to metered network restrictions while
5360 * running on background.
5361 *
5362 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5363 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5364 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5365 */
5366 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5367 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005368 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005369 } catch (RemoteException e) {
5370 throw e.rethrowFromSystemServer();
5371 }
5372 }
5373
5374 /**
5375 * The network watchlist is a list of domains and IP addresses that are associated with
5376 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5377 * currently used by the system for validation purposes.
5378 *
5379 * @return Hash of network watchlist config file. Null if config does not exist.
5380 */
5381 @Nullable
5382 public byte[] getNetworkWatchlistConfigHash() {
5383 try {
5384 return mService.getNetworkWatchlistConfigHash();
5385 } catch (RemoteException e) {
5386 Log.e(TAG, "Unable to get watchlist config hash");
5387 throw e.rethrowFromSystemServer();
5388 }
5389 }
5390
5391 /**
5392 * Returns the {@code uid} of the owner of a network connection.
5393 *
5394 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5395 * IPPROTO_UDP} currently supported.
5396 * @param local The local {@link InetSocketAddress} of a connection.
5397 * @param remote The remote {@link InetSocketAddress} of a connection.
5398 * @return {@code uid} if the connection is found and the app has permission to observe it
5399 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5400 * android.os.Process#INVALID_UID} if the connection is not found.
5401 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5402 * user.
5403 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5404 */
5405 public int getConnectionOwnerUid(
5406 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5407 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5408 try {
5409 return mService.getConnectionOwnerUid(connectionInfo);
5410 } catch (RemoteException e) {
5411 throw e.rethrowFromSystemServer();
5412 }
5413 }
5414
5415 private void printStackTrace() {
5416 if (DEBUG) {
5417 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5418 final StringBuffer sb = new StringBuffer();
5419 for (int i = 3; i < callStack.length; i++) {
5420 final String stackTrace = callStack[i].toString();
5421 if (stackTrace == null || stackTrace.contains("android.os")) {
5422 break;
5423 }
5424 sb.append(" [").append(stackTrace).append("]");
5425 }
5426 Log.d(TAG, "StackLog:" + sb.toString());
5427 }
5428 }
5429
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005430 /** @hide */
5431 public TestNetworkManager startOrGetTestNetworkManager() {
5432 final IBinder tnBinder;
5433 try {
5434 tnBinder = mService.startOrGetTestNetworkService();
5435 } catch (RemoteException e) {
5436 throw e.rethrowFromSystemServer();
5437 }
5438
5439 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5440 }
5441
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005442 /** @hide */
5443 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5444 return new ConnectivityDiagnosticsManager(mContext, mService);
5445 }
5446
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005447 /**
5448 * Simulates a Data Stall for the specified Network.
5449 *
5450 * <p>This method should only be used for tests.
5451 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005452 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5453 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005454 *
5455 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005456 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5457 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5458 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005459 * @param network The Network for which a Data Stall is being simluated.
5460 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5461 * @throws SecurityException if the caller is not the owner of the given network.
5462 * @hide
5463 */
5464 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5465 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5466 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005467 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005468 @NonNull Network network, @NonNull PersistableBundle extras) {
5469 try {
5470 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5471 } catch (RemoteException e) {
5472 e.rethrowFromSystemServer();
5473 }
5474 }
5475
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005476 @NonNull
5477 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5478
5479 /**
5480 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5481 * receive available QoS events related to the {@link Network} and local ip + port
5482 * specified within socketInfo.
5483 * <p/>
5484 * The same {@link QosCallback} must be unregistered before being registered a second time,
5485 * otherwise {@link QosCallbackRegistrationException} is thrown.
5486 * <p/>
5487 * This API does not, in itself, require any permission if called with a network that is not
5488 * restricted. However, the underlying implementation currently only supports the IMS network,
5489 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5490 * useful, because they'd never be called back on networks that they would have access to.
5491 *
5492 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5493 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5494 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5495 * @throws RuntimeException if the app already has too many callbacks registered.
5496 *
5497 * Exceptions after the time of registration is passed through
5498 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5499 *
5500 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005501 * @param executor The executor on which the callback will be invoked. The provided
5502 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005503 * callbacks cannot be guaranteed.onQosCallbackRegistered
5504 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005505 *
5506 * @hide
5507 */
5508 @SystemApi
5509 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005510 @CallbackExecutor @NonNull final Executor executor,
5511 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005512 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005513 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005514 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005515
5516 try {
5517 synchronized (mQosCallbackConnections) {
5518 if (getQosCallbackConnection(callback) == null) {
5519 final QosCallbackConnection connection =
5520 new QosCallbackConnection(this, callback, executor);
5521 mQosCallbackConnections.add(connection);
5522 mService.registerQosSocketCallback(socketInfo, connection);
5523 } else {
5524 Log.e(TAG, "registerQosCallback: Callback already registered");
5525 throw new QosCallbackRegistrationException();
5526 }
5527 }
5528 } catch (final RemoteException e) {
5529 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5530
5531 // The same unregister method method is called for consistency even though nothing
5532 // will be sent to the ConnectivityService since the callback was never successfully
5533 // registered.
5534 unregisterQosCallback(callback);
5535 e.rethrowFromSystemServer();
5536 } catch (final ServiceSpecificException e) {
5537 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5538 unregisterQosCallback(callback);
5539 throw convertServiceException(e);
5540 }
5541 }
5542
5543 /**
5544 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5545 * events once unregistered and can be registered a second time.
5546 * <p/>
5547 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5548 *
5549 * @param callback the callback being unregistered
5550 *
5551 * @hide
5552 */
5553 @SystemApi
5554 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5555 Objects.requireNonNull(callback, "The callback must be non-null");
5556 try {
5557 synchronized (mQosCallbackConnections) {
5558 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5559 if (connection != null) {
5560 connection.stopReceivingMessages();
5561 mService.unregisterQosCallback(connection);
5562 mQosCallbackConnections.remove(connection);
5563 } else {
5564 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5565 }
5566 }
5567 } catch (final RemoteException e) {
5568 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5569 e.rethrowFromSystemServer();
5570 }
5571 }
5572
5573 /**
5574 * Gets the connection related to the callback.
5575 *
5576 * @param callback the callback to look up
5577 * @return the related connection
5578 */
5579 @Nullable
5580 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5581 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5582 // Checking by reference here is intentional
5583 if (connection.getCallback() == callback) {
5584 return connection;
5585 }
5586 }
5587 return null;
5588 }
5589
5590 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005591 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005592 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5593 * be used to request that the system provide a network without causing the network to be
5594 * in the foreground.
5595 *
5596 * <p>This method will attempt to find the best network that matches the passed
5597 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5598 * criteria. The platform will evaluate which network is the best at its own discretion.
5599 * Throughput, latency, cost per byte, policy, user preference and other considerations
5600 * may be factored in the decision of what is considered the best network.
5601 *
5602 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5603 * matching this request, while always attempting to match the request to a better network if
5604 * possible. If a better match is found, the platform will switch this request to the now-best
5605 * network and inform the app of the newly best network by invoking
5606 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5607 * will not try to maintain any other network than the best one currently matching the request:
5608 * a network not matching any network request may be disconnected at any time.
5609 *
5610 * <p>For example, an application could use this method to obtain a connected cellular network
5611 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5612 * radio to consume additional power. Or, an application could inform the system that it wants
5613 * a network supporting sending MMSes and have the system let it know about the currently best
5614 * MMS-supporting network through the provided {@link NetworkCallback}.
5615 *
5616 * <p>The status of the request can be followed by listening to the various callbacks described
5617 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5618 * used to direct traffic to the network (although accessing some networks may be subject to
5619 * holding specific permissions). Callers will learn about the specific characteristics of the
5620 * network through
5621 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5622 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5623 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5624 * matching the request at any given time; therefore when a better network matching the request
5625 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5626 * with the new network after which no further updates are given about the previously-best
5627 * network, unless it becomes the best again at some later time. All callbacks are invoked
5628 * in order on the same thread, which by default is a thread created by the framework running
5629 * in the app.
5630 *
5631 * <p>This{@link NetworkRequest} will live until released via
5632 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5633 * which point the system may let go of the network at any time.
5634 *
5635 * <p>It is presently unsupported to request a network with mutable
5636 * {@link NetworkCapabilities} such as
5637 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5638 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5639 * as these {@code NetworkCapabilities} represent states that a particular
5640 * network may never attain, and whether a network will attain these states
5641 * is unknown prior to bringing up the network so the framework does not
5642 * know how to go about satisfying a request with these capabilities.
5643 *
5644 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5645 * number of outstanding requests to 100 per app (identified by their UID), shared with
5646 * all variants of this method, of {@link #registerNetworkCallback} as well as
5647 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5648 * Requesting a network with this method will count toward this limit. If this limit is
5649 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5650 * make sure to unregister the callbacks with
5651 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5652 *
5653 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005654 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5655 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005656 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5657 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005658 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5659 * @throws SecurityException if missing the appropriate permissions.
5660 * @throws RuntimeException if the app already has too many callbacks registered.
5661 *
5662 * @hide
5663 */
5664 @SystemApi(client = MODULE_LIBRARIES)
5665 @SuppressLint("ExecutorRegistration")
5666 @RequiresPermission(anyOf = {
5667 android.Manifest.permission.NETWORK_SETTINGS,
5668 android.Manifest.permission.NETWORK_STACK,
5669 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5670 })
5671 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005672 @NonNull NetworkCallback networkCallback,
5673 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005674 final NetworkCapabilities nc = request.networkCapabilities;
5675 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005676 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005677 }
James Mattis12aeab82021-01-10 14:24:24 -08005678
5679 /**
James Mattis12aeab82021-01-10 14:24:24 -08005680 * Used by automotive devices to set the network preferences used to direct traffic at an
5681 * application level as per the given OemNetworkPreferences. An example use-case would be an
5682 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5683 * vehicle via a particular network.
5684 *
5685 * Calling this will overwrite the existing preference.
5686 *
5687 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5688 * @param executor the executor on which listener will be invoked.
5689 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5690 * communicate completion of setOemNetworkPreference(). This will only be
5691 * called once upon successful completion of setOemNetworkPreference().
5692 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5693 * @throws SecurityException if missing the appropriate permissions.
5694 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005695 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005696 */
James Mattis6e2d7022021-01-26 16:23:52 -08005697 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005698 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005699 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005700 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005701 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005702 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5703 if (null != listener) {
5704 Objects.requireNonNull(executor, "Executor must be non-null");
5705 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005706 final IOnCompleteListener listenerInternal = listener == null ? null :
5707 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005708 @Override
5709 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005710 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005711 }
5712 };
5713
5714 try {
5715 mService.setOemNetworkPreference(preference, listenerInternal);
5716 } catch (RemoteException e) {
5717 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5718 throw e.rethrowFromSystemServer();
5719 }
5720 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005721
Chalard Jeanad565e22021-02-25 17:23:40 +09005722 /**
5723 * Request that a user profile is put by default on a network matching a given preference.
5724 *
5725 * See the documentation for the individual preferences for a description of the supported
5726 * behaviors.
5727 *
5728 * @param profile the profile concerned.
5729 * @param preference the preference for this profile.
5730 * @param executor an executor to execute the listener on. Optional if listener is null.
5731 * @param listener an optional listener to listen for completion of the operation.
5732 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5733 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005734 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5735 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005736 * @hide
5737 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005738 // This function is for establishing per-profile default networking and can only be called by
5739 // the device policy manager, running as the system server. It would make no sense to call it
5740 // on a context for a user because it does not establish a setting on behalf of a user, rather
5741 // it establishes a setting for a user on behalf of the DPM.
5742 @SuppressLint({"UserHandle"})
5743 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005744 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005745 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005746 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005747 @ProfileNetworkPreferencePolicy final int preference,
5748 @Nullable @CallbackExecutor final Executor executor,
5749 @Nullable final Runnable listener) {
5750
5751 ProfileNetworkPreference.Builder preferenceBuilder =
5752 new ProfileNetworkPreference.Builder();
5753 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005754 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5755 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5756 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005757 setProfileNetworkPreferences(profile,
5758 List.of(preferenceBuilder.build()), executor, listener);
5759 }
5760
5761 /**
5762 * Set a list of default network selection policies for a user profile.
5763 *
5764 * Calling this API with a user handle defines the entire policy for that user handle.
5765 * It will overwrite any setting previously set for the same user profile,
5766 * and not affect previously set settings for other handles.
5767 *
5768 * Call this API with an empty list to remove settings for this user profile.
5769 *
5770 * See {@link ProfileNetworkPreference} for more details on each preference
5771 * parameter.
5772 *
5773 * @param profile the user profile for which the preference is being set.
5774 * @param profileNetworkPreferences the list of profile network preferences for the
5775 * provided profile.
5776 * @param executor an executor to execute the listener on. Optional if listener is null.
5777 * @param listener an optional listener to listen for completion of the operation.
5778 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5779 * @throws SecurityException if missing the appropriate permissions.
5780 * @hide
5781 */
5782 @SystemApi(client = MODULE_LIBRARIES)
5783 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5784 public void setProfileNetworkPreferences(
5785 @NonNull final UserHandle profile,
5786 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005787 @Nullable @CallbackExecutor final Executor executor,
5788 @Nullable final Runnable listener) {
5789 if (null != listener) {
5790 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5791 }
5792 final IOnCompleteListener proxy;
5793 if (null == listener) {
5794 proxy = null;
5795 } else {
5796 proxy = new IOnCompleteListener.Stub() {
5797 @Override
5798 public void onComplete() {
5799 executor.execute(listener::run);
5800 }
5801 };
5802 }
5803 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005804 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005805 } catch (RemoteException e) {
5806 throw e.rethrowFromSystemServer();
5807 }
5808 }
5809
lucaslin5cdbcfb2021-03-12 00:46:33 +08005810 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005811 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005812 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005813 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005814
5815 /**
5816 * Get the network ID range reserved for IPSec tunnel interfaces.
5817 *
5818 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5819 * @hide
5820 */
5821 @SystemApi(client = MODULE_LIBRARIES)
5822 @NonNull
5823 public static Range<Integer> getIpSecNetIdRange() {
5824 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5825 }
markchien738ad912021-12-09 18:15:45 +08005826
5827 /**
markchiene46042b2022-03-02 18:07:35 +08005828 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5829 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005830 *
5831 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005832 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005833 * @hide
5834 */
5835 @SystemApi(client = MODULE_LIBRARIES)
5836 @RequiresPermission(anyOf = {
5837 android.Manifest.permission.NETWORK_SETTINGS,
5838 android.Manifest.permission.NETWORK_STACK,
5839 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5840 })
markchiene46042b2022-03-02 18:07:35 +08005841 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005842 try {
markchiene46042b2022-03-02 18:07:35 +08005843 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08005844 } catch (RemoteException e) {
5845 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005846 }
5847 }
5848
5849 /**
markchiene46042b2022-03-02 18:07:35 +08005850 * Removes the specified UID from the list of UIDs that are allowed to use background data on
5851 * metered networks when background data is restricted. The deny list takes precedence over
5852 * the allow list.
5853 *
5854 * @param uid uid of target app
5855 * @throws IllegalStateException if updating allow list failed.
5856 * @hide
5857 */
5858 @SystemApi(client = MODULE_LIBRARIES)
5859 @RequiresPermission(anyOf = {
5860 android.Manifest.permission.NETWORK_SETTINGS,
5861 android.Manifest.permission.NETWORK_STACK,
5862 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5863 })
5864 public void removeUidFromMeteredNetworkAllowList(final int uid) {
5865 try {
5866 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
5867 } catch (RemoteException e) {
5868 throw e.rethrowFromSystemServer();
5869 }
5870 }
5871
5872 /**
5873 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
5874 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08005875 *
5876 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005877 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08005878 * @hide
5879 */
5880 @SystemApi(client = MODULE_LIBRARIES)
5881 @RequiresPermission(anyOf = {
5882 android.Manifest.permission.NETWORK_SETTINGS,
5883 android.Manifest.permission.NETWORK_STACK,
5884 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5885 })
markchiene46042b2022-03-02 18:07:35 +08005886 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005887 try {
markchiene46042b2022-03-02 18:07:35 +08005888 mService.updateMeteredNetworkDenyList(uid, true /* add */);
5889 } catch (RemoteException e) {
5890 throw e.rethrowFromSystemServer();
5891 }
5892 }
5893
5894 /**
5895 * Removes the specified UID from the list of UIds that can use use background data on metered
5896 * networks if background data is not restricted. The deny list takes precedence over the
5897 * allow list.
5898 *
5899 * @param uid uid of target app
5900 * @throws IllegalStateException if updating deny list failed.
5901 * @hide
5902 */
5903 @SystemApi(client = MODULE_LIBRARIES)
5904 @RequiresPermission(anyOf = {
5905 android.Manifest.permission.NETWORK_SETTINGS,
5906 android.Manifest.permission.NETWORK_STACK,
5907 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5908 })
5909 public void removeUidFromMeteredNetworkDenyList(final int uid) {
5910 try {
5911 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08005912 } catch (RemoteException e) {
5913 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08005914 }
5915 }
5916
5917 /**
5918 * Sets a firewall rule for the specified UID on the specified chain.
5919 *
5920 * @param chain target chain.
5921 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08005922 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08005923 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08005924 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08005925 * @hide
5926 */
5927 @SystemApi(client = MODULE_LIBRARIES)
5928 @RequiresPermission(anyOf = {
5929 android.Manifest.permission.NETWORK_SETTINGS,
5930 android.Manifest.permission.NETWORK_STACK,
5931 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5932 })
markchien3c04e662022-03-22 16:29:56 +08005933 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
5934 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08005935 try {
markchien3c04e662022-03-22 16:29:56 +08005936 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08005937 } catch (RemoteException e) {
5938 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005939 }
5940 }
markchien98a6f952022-01-13 23:43:53 +08005941
5942 /**
5943 * Enables or disables the specified firewall chain.
5944 *
5945 * @param chain target chain.
5946 * @param enable whether the chain should be enabled.
markchien68cfadc2022-01-14 13:39:54 +08005947 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08005948 * @hide
5949 */
5950 @SystemApi(client = MODULE_LIBRARIES)
5951 @RequiresPermission(anyOf = {
5952 android.Manifest.permission.NETWORK_SETTINGS,
5953 android.Manifest.permission.NETWORK_STACK,
5954 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5955 })
5956 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
5957 try {
5958 mService.setFirewallChainEnabled(chain, enable);
5959 } catch (RemoteException e) {
5960 throw e.rethrowFromSystemServer();
5961 }
5962 }
markchien00a0bed2022-01-13 23:46:13 +08005963
5964 /**
5965 * Replaces the contents of the specified UID-based firewall chain.
5966 *
5967 * @param chain target chain to replace.
5968 * @param uids The list of UIDs to be placed into chain.
markchien68cfadc2022-01-14 13:39:54 +08005969 * @throws IllegalStateException if replacing the firewall chain failed.
markchien00a0bed2022-01-13 23:46:13 +08005970 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
5971 * @hide
5972 */
5973 @SystemApi(client = MODULE_LIBRARIES)
5974 @RequiresPermission(anyOf = {
5975 android.Manifest.permission.NETWORK_SETTINGS,
5976 android.Manifest.permission.NETWORK_STACK,
5977 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5978 })
5979 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
5980 Objects.requireNonNull(uids);
5981 try {
5982 mService.replaceFirewallChain(chain, uids);
5983 } catch (RemoteException e) {
5984 throw e.rethrowFromSystemServer();
5985 }
5986 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005987}