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