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