blob: a798f6e2067e3a04af9e489d6ff13317195e591c [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 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900998 * A kludge to facilitate static access where a Context pointer isn't available, like in the
999 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1000 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1001 * methods that take a Context argument.
1002 */
1003 private static ConnectivityManager sInstance;
1004
1005 private final Context mContext;
1006
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001007 @GuardedBy("mTetheringEventCallbacks")
1008 private TetheringManager mTetheringManager;
1009
1010 private TetheringManager getTetheringManager() {
1011 synchronized (mTetheringEventCallbacks) {
1012 if (mTetheringManager == null) {
1013 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1014 }
1015 return mTetheringManager;
1016 }
1017 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001018
1019 /**
1020 * Tests if a given integer represents a valid network type.
1021 * @param networkType the type to be tested
1022 * @return a boolean. {@code true} if the type is valid, else {@code false}
1023 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1024 * validate a network type.
1025 */
1026 @Deprecated
1027 public static boolean isNetworkTypeValid(int networkType) {
1028 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1029 }
1030
1031 /**
1032 * Returns a non-localized string representing a given network type.
1033 * ONLY used for debugging output.
1034 * @param type the type needing naming
1035 * @return a String for the given type, or a string version of the type ("87")
1036 * if no name is known.
1037 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1038 * {@hide}
1039 */
1040 @Deprecated
1041 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1042 public static String getNetworkTypeName(int type) {
1043 switch (type) {
1044 case TYPE_NONE:
1045 return "NONE";
1046 case TYPE_MOBILE:
1047 return "MOBILE";
1048 case TYPE_WIFI:
1049 return "WIFI";
1050 case TYPE_MOBILE_MMS:
1051 return "MOBILE_MMS";
1052 case TYPE_MOBILE_SUPL:
1053 return "MOBILE_SUPL";
1054 case TYPE_MOBILE_DUN:
1055 return "MOBILE_DUN";
1056 case TYPE_MOBILE_HIPRI:
1057 return "MOBILE_HIPRI";
1058 case TYPE_WIMAX:
1059 return "WIMAX";
1060 case TYPE_BLUETOOTH:
1061 return "BLUETOOTH";
1062 case TYPE_DUMMY:
1063 return "DUMMY";
1064 case TYPE_ETHERNET:
1065 return "ETHERNET";
1066 case TYPE_MOBILE_FOTA:
1067 return "MOBILE_FOTA";
1068 case TYPE_MOBILE_IMS:
1069 return "MOBILE_IMS";
1070 case TYPE_MOBILE_CBS:
1071 return "MOBILE_CBS";
1072 case TYPE_WIFI_P2P:
1073 return "WIFI_P2P";
1074 case TYPE_MOBILE_IA:
1075 return "MOBILE_IA";
1076 case TYPE_MOBILE_EMERGENCY:
1077 return "MOBILE_EMERGENCY";
1078 case TYPE_PROXY:
1079 return "PROXY";
1080 case TYPE_VPN:
1081 return "VPN";
1082 default:
1083 return Integer.toString(type);
1084 }
1085 }
1086
1087 /**
1088 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001089 */
lucaslin10774b72021-03-17 14:16:01 +08001090 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001091 public void systemReady() {
1092 try {
1093 mService.systemReady();
1094 } catch (RemoteException e) {
1095 throw e.rethrowFromSystemServer();
1096 }
1097 }
1098
1099 /**
1100 * Checks if a given type uses the cellular data connection.
1101 * This should be replaced in the future by a network property.
1102 * @param networkType the type to check
1103 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1104 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1105 * {@hide}
1106 */
1107 @Deprecated
1108 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1109 public static boolean isNetworkTypeMobile(int networkType) {
1110 switch (networkType) {
1111 case TYPE_MOBILE:
1112 case TYPE_MOBILE_MMS:
1113 case TYPE_MOBILE_SUPL:
1114 case TYPE_MOBILE_DUN:
1115 case TYPE_MOBILE_HIPRI:
1116 case TYPE_MOBILE_FOTA:
1117 case TYPE_MOBILE_IMS:
1118 case TYPE_MOBILE_CBS:
1119 case TYPE_MOBILE_IA:
1120 case TYPE_MOBILE_EMERGENCY:
1121 return true;
1122 default:
1123 return false;
1124 }
1125 }
1126
1127 /**
1128 * Checks if the given network type is backed by a Wi-Fi radio.
1129 *
1130 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1131 * @hide
1132 */
1133 @Deprecated
1134 public static boolean isNetworkTypeWifi(int networkType) {
1135 switch (networkType) {
1136 case TYPE_WIFI:
1137 case TYPE_WIFI_P2P:
1138 return true;
1139 default:
1140 return false;
1141 }
1142 }
1143
1144 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001145 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1146 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001147 * Specify that the traffic for this user should by follow the default rules.
1148 * @hide
1149 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001150 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001151 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1152
1153 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001154 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1155 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001156 * Specify that the traffic for this user should by default go on a network with
1157 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1158 * if no such network is available.
1159 * @hide
1160 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001161 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001162 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1163
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001164 /**
1165 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1166 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1167 * Specify that the traffic for this user should by default go on a network with
1168 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
1169 * should not go on the system default network
1170 * @hide
1171 */
1172 @SystemApi(client = MODULE_LIBRARIES)
1173 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1174
Chalard Jeanad565e22021-02-25 17:23:40 +09001175 /** @hide */
1176 @Retention(RetentionPolicy.SOURCE)
1177 @IntDef(value = {
1178 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001179 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1180 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001181 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001182 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001183 }
1184
1185 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001186 * Specifies the preferred network type. When the device has more
1187 * than one type available the preferred network type will be used.
1188 *
1189 * @param preference the network type to prefer over all others. It is
1190 * unspecified what happens to the old preferred network in the
1191 * overall ordering.
1192 * @deprecated Functionality has been removed as it no longer makes sense,
1193 * with many more than two networks - we'd need an array to express
1194 * preference. Instead we use dynamic network properties of
1195 * the networks to describe their precedence.
1196 */
1197 @Deprecated
1198 public void setNetworkPreference(int preference) {
1199 }
1200
1201 /**
1202 * Retrieves the current preferred network type.
1203 *
1204 * @return an integer representing the preferred network type
1205 *
1206 * @deprecated Functionality has been removed as it no longer makes sense,
1207 * with many more than two networks - we'd need an array to express
1208 * preference. Instead we use dynamic network properties of
1209 * the networks to describe their precedence.
1210 */
1211 @Deprecated
1212 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1213 public int getNetworkPreference() {
1214 return TYPE_NONE;
1215 }
1216
1217 /**
1218 * Returns details about the currently active default data network. When
1219 * connected, this network is the default route for outgoing connections.
1220 * You should always check {@link NetworkInfo#isConnected()} before initiating
1221 * network traffic. This may return {@code null} when there is no default
1222 * network.
1223 * Note that if the default network is a VPN, this method will return the
1224 * NetworkInfo for one of its underlying networks instead, or null if the
1225 * VPN agent did not specify any. Apps interested in learning about VPNs
1226 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1227 *
1228 * @return a {@link NetworkInfo} object for the current default network
1229 * or {@code null} if no default network is currently active
1230 * @deprecated See {@link NetworkInfo}.
1231 */
1232 @Deprecated
1233 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1234 @Nullable
1235 public NetworkInfo getActiveNetworkInfo() {
1236 try {
1237 return mService.getActiveNetworkInfo();
1238 } catch (RemoteException e) {
1239 throw e.rethrowFromSystemServer();
1240 }
1241 }
1242
1243 /**
1244 * Returns a {@link Network} object corresponding to the currently active
1245 * default data network. In the event that the current active default data
1246 * network disconnects, the returned {@code Network} object will no longer
1247 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001248 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001249 *
1250 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001251 * {@code null} if no default network is currently active or if
1252 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001253 */
1254 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1255 @Nullable
1256 public Network getActiveNetwork() {
1257 try {
1258 return mService.getActiveNetwork();
1259 } catch (RemoteException e) {
1260 throw e.rethrowFromSystemServer();
1261 }
1262 }
1263
1264 /**
1265 * Returns a {@link Network} object corresponding to the currently active
1266 * default data network for a specific UID. In the event that the default data
1267 * network disconnects, the returned {@code Network} object will no longer
1268 * be usable. This will return {@code null} when there is no default
1269 * network for the UID.
1270 *
1271 * @return a {@link Network} object for the current default network for the
1272 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001273 *
1274 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001275 */
1276 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1277 @Nullable
1278 public Network getActiveNetworkForUid(int uid) {
1279 return getActiveNetworkForUid(uid, false);
1280 }
1281
1282 /** {@hide} */
1283 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1284 try {
1285 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1286 } catch (RemoteException e) {
1287 throw e.rethrowFromSystemServer();
1288 }
1289 }
1290
1291 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001292 * Adds or removes a requirement for given UID ranges to use the VPN.
1293 *
1294 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1295 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1296 * otherwise have permission to bypass the VPN (e.g., because they have the
1297 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1298 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1299 * set to {@code false}, a previously-added restriction is removed.
1300 * <p>
1301 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1302 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1303 * remove a previously-added range, the exact range must be removed as is.
1304 * <p>
1305 * The changes are applied asynchronously and may not have been applied by the time the method
1306 * returns. Apps will be notified about any changes that apply to them via
1307 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1308 * effect.
1309 * <p>
1310 * This method should be called only by the VPN code.
1311 *
1312 * @param ranges the UID ranges to restrict
1313 * @param requireVpn whether the specified UID ranges must use a VPN
1314 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001315 * @hide
1316 */
1317 @RequiresPermission(anyOf = {
1318 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001319 android.Manifest.permission.NETWORK_STACK,
1320 android.Manifest.permission.NETWORK_SETTINGS})
1321 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001322 public void setRequireVpnForUids(boolean requireVpn,
1323 @NonNull Collection<Range<Integer>> ranges) {
1324 Objects.requireNonNull(ranges);
1325 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1326 // This method is not necessarily expected to be used outside the system server, so
1327 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1328 // stack process, or by tests.
1329 UidRange[] rangesArray = new UidRange[ranges.size()];
1330 int index = 0;
1331 for (Range<Integer> range : ranges) {
1332 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1333 }
1334 try {
1335 mService.setRequireVpnForUids(requireVpn, rangesArray);
1336 } catch (RemoteException e) {
1337 throw e.rethrowFromSystemServer();
1338 }
1339 }
1340
1341 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001342 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1343 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1344 * but is still supported for backwards compatibility.
1345 * <p>
1346 * This type of VPN is assumed always to use the system default network, and must always declare
1347 * exactly one underlying network, which is the network that was the default when the VPN
1348 * connected.
1349 * <p>
1350 * Calling this method with {@code true} enables legacy behaviour, specifically:
1351 * <ul>
1352 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1353 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1354 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1355 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1356 * underlying the VPN.</li>
1357 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1358 * similarly replaced by the VPN network state.</li>
1359 * <li>Information on current network interfaces passed to NetworkStatsService will not
1360 * include any VPN interfaces.</li>
1361 * </ul>
1362 *
1363 * @param enabled whether legacy lockdown VPN is enabled or disabled
1364 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001365 * @hide
1366 */
1367 @RequiresPermission(anyOf = {
1368 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001369 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001370 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001371 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001372 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1373 try {
1374 mService.setLegacyLockdownVpnEnabled(enabled);
1375 } catch (RemoteException e) {
1376 throw e.rethrowFromSystemServer();
1377 }
1378 }
1379
1380 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001381 * Returns details about the currently active default data network
1382 * for a given uid. This is for internal use only to avoid spying
1383 * other apps.
1384 *
1385 * @return a {@link NetworkInfo} object for the current default network
1386 * for the given uid or {@code null} if no default network is
1387 * available for the specified uid.
1388 *
1389 * {@hide}
1390 */
1391 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1392 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1393 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1394 return getActiveNetworkInfoForUid(uid, false);
1395 }
1396
1397 /** {@hide} */
1398 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1399 try {
1400 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1401 } catch (RemoteException e) {
1402 throw e.rethrowFromSystemServer();
1403 }
1404 }
1405
1406 /**
1407 * Returns connection status information about a particular
1408 * network type.
1409 *
1410 * @param networkType integer specifying which networkType in
1411 * which you're interested.
1412 * @return a {@link NetworkInfo} object for the requested
1413 * network type or {@code null} if the type is not
1414 * supported by the device. If {@code networkType} is
1415 * TYPE_VPN and a VPN is active for the calling app,
1416 * then this method will try to return one of the
1417 * underlying networks for the VPN or null if the
1418 * VPN agent didn't specify any.
1419 *
1420 * @deprecated This method does not support multiple connected networks
1421 * of the same type. Use {@link #getAllNetworks} and
1422 * {@link #getNetworkInfo(android.net.Network)} instead.
1423 */
1424 @Deprecated
1425 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1426 @Nullable
1427 public NetworkInfo getNetworkInfo(int networkType) {
1428 try {
1429 return mService.getNetworkInfo(networkType);
1430 } catch (RemoteException e) {
1431 throw e.rethrowFromSystemServer();
1432 }
1433 }
1434
1435 /**
1436 * Returns connection status information about a particular
1437 * Network.
1438 *
1439 * @param network {@link Network} specifying which network
1440 * in which you're interested.
1441 * @return a {@link NetworkInfo} object for the requested
1442 * network or {@code null} if the {@code Network}
1443 * is not valid.
1444 * @deprecated See {@link NetworkInfo}.
1445 */
1446 @Deprecated
1447 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1448 @Nullable
1449 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1450 return getNetworkInfoForUid(network, Process.myUid(), false);
1451 }
1452
1453 /** {@hide} */
1454 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1455 try {
1456 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1457 } catch (RemoteException e) {
1458 throw e.rethrowFromSystemServer();
1459 }
1460 }
1461
1462 /**
1463 * Returns connection status information about all network
1464 * types supported by the device.
1465 *
1466 * @return an array of {@link NetworkInfo} objects. Check each
1467 * {@link NetworkInfo#getType} for which type each applies.
1468 *
1469 * @deprecated This method does not support multiple connected networks
1470 * of the same type. Use {@link #getAllNetworks} and
1471 * {@link #getNetworkInfo(android.net.Network)} instead.
1472 */
1473 @Deprecated
1474 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1475 @NonNull
1476 public NetworkInfo[] getAllNetworkInfo() {
1477 try {
1478 return mService.getAllNetworkInfo();
1479 } catch (RemoteException e) {
1480 throw e.rethrowFromSystemServer();
1481 }
1482 }
1483
1484 /**
junyulaib1211372021-03-03 12:09:05 +08001485 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1486 * connected.
1487 * @hide
1488 */
1489 @SystemApi(client = MODULE_LIBRARIES)
1490 @RequiresPermission(anyOf = {
1491 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1492 android.Manifest.permission.NETWORK_STACK,
1493 android.Manifest.permission.NETWORK_SETTINGS})
1494 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001495 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001496 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001497 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001498 } catch (RemoteException e) {
1499 throw e.rethrowFromSystemServer();
1500 }
1501 }
1502
1503 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001504 * Returns the {@link Network} object currently serving a given type, or
1505 * null if the given type is not connected.
1506 *
1507 * @hide
1508 * @deprecated This method does not support multiple connected networks
1509 * of the same type. Use {@link #getAllNetworks} and
1510 * {@link #getNetworkInfo(android.net.Network)} instead.
1511 */
1512 @Deprecated
1513 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1514 @UnsupportedAppUsage
1515 public Network getNetworkForType(int networkType) {
1516 try {
1517 return mService.getNetworkForType(networkType);
1518 } catch (RemoteException e) {
1519 throw e.rethrowFromSystemServer();
1520 }
1521 }
1522
1523 /**
1524 * Returns an array of all {@link Network} currently tracked by the
1525 * framework.
1526 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001527 * @deprecated This method does not provide any notification of network state changes, forcing
1528 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1529 * Apps should use methods such as
1530 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1531 * Apps that desire to obtain information about networks that do not apply to them
1532 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1533 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001534 * @return an array of {@link Network} objects.
1535 */
1536 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1537 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001538 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001539 public Network[] getAllNetworks() {
1540 try {
1541 return mService.getAllNetworks();
1542 } catch (RemoteException e) {
1543 throw e.rethrowFromSystemServer();
1544 }
1545 }
1546
1547 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001548 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001549 * the Networks that applications run by the given user will use by default.
1550 * @hide
1551 */
1552 @UnsupportedAppUsage
1553 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1554 try {
1555 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001556 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001557 } catch (RemoteException e) {
1558 throw e.rethrowFromSystemServer();
1559 }
1560 }
1561
1562 /**
1563 * Returns the IP information for the current default network.
1564 *
1565 * @return a {@link LinkProperties} object describing the IP info
1566 * for the current default network, or {@code null} if there
1567 * is no current default network.
1568 *
1569 * {@hide}
1570 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1571 * value of {@link #getActiveNetwork()} instead. In particular,
1572 * this method will return non-null LinkProperties even if the
1573 * app is blocked by policy from using this network.
1574 */
1575 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1576 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1577 public LinkProperties getActiveLinkProperties() {
1578 try {
1579 return mService.getActiveLinkProperties();
1580 } catch (RemoteException e) {
1581 throw e.rethrowFromSystemServer();
1582 }
1583 }
1584
1585 /**
1586 * Returns the IP information for a given network type.
1587 *
1588 * @param networkType the network type of interest.
1589 * @return a {@link LinkProperties} object describing the IP info
1590 * for the given networkType, or {@code null} if there is
1591 * no current default network.
1592 *
1593 * {@hide}
1594 * @deprecated This method does not support multiple connected networks
1595 * of the same type. Use {@link #getAllNetworks},
1596 * {@link #getNetworkInfo(android.net.Network)}, and
1597 * {@link #getLinkProperties(android.net.Network)} instead.
1598 */
1599 @Deprecated
1600 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1601 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1602 public LinkProperties getLinkProperties(int networkType) {
1603 try {
1604 return mService.getLinkPropertiesForType(networkType);
1605 } catch (RemoteException e) {
1606 throw e.rethrowFromSystemServer();
1607 }
1608 }
1609
1610 /**
1611 * Get the {@link LinkProperties} for the given {@link Network}. This
1612 * will return {@code null} if the network is unknown.
1613 *
1614 * @param network The {@link Network} object identifying the network in question.
1615 * @return The {@link LinkProperties} for the network, or {@code null}.
1616 */
1617 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1618 @Nullable
1619 public LinkProperties getLinkProperties(@Nullable Network network) {
1620 try {
1621 return mService.getLinkProperties(network);
1622 } catch (RemoteException e) {
1623 throw e.rethrowFromSystemServer();
1624 }
1625 }
1626
1627 /**
lucaslinc582d502022-01-27 09:07:00 +08001628 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001629 *
lucaslinc582d502022-01-27 09:07:00 +08001630 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1631 * given package, considering its permissions.
1632 *
1633 * @param lp A {@link LinkProperties} which will be redacted.
1634 * @param uid The target uid.
1635 * @param packageName The name of the package, for appops logging.
1636 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1637 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1638 * @hide
1639 */
1640 @RequiresPermission(anyOf = {
1641 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1642 android.Manifest.permission.NETWORK_STACK,
1643 android.Manifest.permission.NETWORK_SETTINGS})
1644 @SystemApi(client = MODULE_LIBRARIES)
1645 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001646 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001647 @NonNull String packageName) {
1648 try {
lucaslind2b06132022-03-02 10:56:57 +08001649 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001650 lp, uid, packageName, getAttributionTag());
1651 } catch (RemoteException e) {
1652 throw e.rethrowFromSystemServer();
1653 }
1654 }
1655
1656 /**
1657 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1658 *
1659 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1660 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1661 * sensitive information. To retrieve this location sensitive information (subject to
1662 * the caller's location permissions), use a {@link NetworkCallback} with the
1663 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1664 *
1665 * This method returns {@code null} if the network is unknown or if the |network| argument
1666 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001667 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001668 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001669 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001670 */
1671 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1672 @Nullable
1673 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1674 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001675 return mService.getNetworkCapabilities(
1676 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001677 } catch (RemoteException e) {
1678 throw e.rethrowFromSystemServer();
1679 }
1680 }
1681
1682 /**
lucaslinc582d502022-01-27 09:07:00 +08001683 * Redact {@link NetworkCapabilities} for a given package.
1684 *
1685 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001686 * to the given package, considering its permissions. If the passed capabilities contain
1687 * location-sensitive information, they will be redacted to the correct degree for the location
1688 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1689 * that level of location. If the UID holds no location permission, the returned object will
1690 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001691 *
1692 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1693 * @param uid The target uid.
1694 * @param packageName The name of the package, for appops logging.
1695 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1696 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1697 * @hide
1698 */
1699 @RequiresPermission(anyOf = {
1700 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1701 android.Manifest.permission.NETWORK_STACK,
1702 android.Manifest.permission.NETWORK_SETTINGS})
1703 @SystemApi(client = MODULE_LIBRARIES)
1704 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001705 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001706 @NonNull NetworkCapabilities nc,
1707 int uid, @NonNull String packageName) {
1708 try {
lucaslind2b06132022-03-02 10:56:57 +08001709 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001710 getAttributionTag());
1711 } catch (RemoteException e) {
1712 throw e.rethrowFromSystemServer();
1713 }
1714 }
1715
1716 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001717 * Gets a URL that can be used for resolving whether a captive portal is present.
1718 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1719 * portal is present.
1720 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1721 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1722 *
1723 * The system network validation may be using different strategies to detect captive portals,
1724 * so this method does not necessarily return a URL used by the system. It only returns a URL
1725 * that may be relevant for other components trying to detect captive portals.
1726 *
1727 * @hide
1728 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1729 * system.
1730 */
1731 @Deprecated
1732 @SystemApi
1733 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1734 public String getCaptivePortalServerUrl() {
1735 try {
1736 return mService.getCaptivePortalServerUrl();
1737 } catch (RemoteException e) {
1738 throw e.rethrowFromSystemServer();
1739 }
1740 }
1741
1742 /**
1743 * Tells the underlying networking system that the caller wants to
1744 * begin using the named feature. The interpretation of {@code feature}
1745 * is completely up to each networking implementation.
1746 *
1747 * <p>This method requires the caller to hold either the
1748 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1749 * or the ability to modify system settings as determined by
1750 * {@link android.provider.Settings.System#canWrite}.</p>
1751 *
1752 * @param networkType specifies which network the request pertains to
1753 * @param feature the name of the feature to be used
1754 * @return an integer value representing the outcome of the request.
1755 * The interpretation of this value is specific to each networking
1756 * implementation+feature combination, except that the value {@code -1}
1757 * always indicates failure.
1758 *
1759 * @deprecated Deprecated in favor of the cleaner
1760 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1761 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1762 * throw {@code UnsupportedOperationException} if called.
1763 * @removed
1764 */
1765 @Deprecated
1766 public int startUsingNetworkFeature(int networkType, String feature) {
1767 checkLegacyRoutingApiAccess();
1768 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1769 if (netCap == null) {
1770 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1771 feature);
1772 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1773 }
1774
1775 NetworkRequest request = null;
1776 synchronized (sLegacyRequests) {
1777 LegacyRequest l = sLegacyRequests.get(netCap);
1778 if (l != null) {
1779 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1780 renewRequestLocked(l);
1781 if (l.currentNetwork != null) {
1782 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1783 } else {
1784 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1785 }
1786 }
1787
1788 request = requestNetworkForFeatureLocked(netCap);
1789 }
1790 if (request != null) {
1791 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1792 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1793 } else {
1794 Log.d(TAG, " request Failed");
1795 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1796 }
1797 }
1798
1799 /**
1800 * Tells the underlying networking system that the caller is finished
1801 * using the named feature. The interpretation of {@code feature}
1802 * is completely up to each networking implementation.
1803 *
1804 * <p>This method requires the caller to hold either the
1805 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1806 * or the ability to modify system settings as determined by
1807 * {@link android.provider.Settings.System#canWrite}.</p>
1808 *
1809 * @param networkType specifies which network the request pertains to
1810 * @param feature the name of the feature that is no longer needed
1811 * @return an integer value representing the outcome of the request.
1812 * The interpretation of this value is specific to each networking
1813 * implementation+feature combination, except that the value {@code -1}
1814 * always indicates failure.
1815 *
1816 * @deprecated Deprecated in favor of the cleaner
1817 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1818 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1819 * throw {@code UnsupportedOperationException} if called.
1820 * @removed
1821 */
1822 @Deprecated
1823 public int stopUsingNetworkFeature(int networkType, String feature) {
1824 checkLegacyRoutingApiAccess();
1825 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1826 if (netCap == null) {
1827 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1828 feature);
1829 return -1;
1830 }
1831
1832 if (removeRequestForFeature(netCap)) {
1833 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1834 }
1835 return 1;
1836 }
1837
1838 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1839 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1840 if (networkType == TYPE_MOBILE) {
1841 switch (feature) {
1842 case "enableCBS":
1843 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1844 case "enableDUN":
1845 case "enableDUNAlways":
1846 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1847 case "enableFOTA":
1848 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1849 case "enableHIPRI":
1850 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1851 case "enableIMS":
1852 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1853 case "enableMMS":
1854 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1855 case "enableSUPL":
1856 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1857 default:
1858 return null;
1859 }
1860 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1861 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1862 }
1863 return null;
1864 }
1865
1866 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1867 if (netCap == null) return TYPE_NONE;
1868 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1869 return TYPE_MOBILE_CBS;
1870 }
1871 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1872 return TYPE_MOBILE_IMS;
1873 }
1874 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1875 return TYPE_MOBILE_FOTA;
1876 }
1877 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1878 return TYPE_MOBILE_DUN;
1879 }
1880 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1881 return TYPE_MOBILE_SUPL;
1882 }
1883 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1884 return TYPE_MOBILE_MMS;
1885 }
1886 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1887 return TYPE_MOBILE_HIPRI;
1888 }
1889 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1890 return TYPE_WIFI_P2P;
1891 }
1892 return TYPE_NONE;
1893 }
1894
1895 private static class LegacyRequest {
1896 NetworkCapabilities networkCapabilities;
1897 NetworkRequest networkRequest;
1898 int expireSequenceNumber;
1899 Network currentNetwork;
1900 int delay = -1;
1901
1902 private void clearDnsBinding() {
1903 if (currentNetwork != null) {
1904 currentNetwork = null;
1905 setProcessDefaultNetworkForHostResolution(null);
1906 }
1907 }
1908
1909 NetworkCallback networkCallback = new NetworkCallback() {
1910 @Override
1911 public void onAvailable(Network network) {
1912 currentNetwork = network;
1913 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1914 setProcessDefaultNetworkForHostResolution(network);
1915 }
1916 @Override
1917 public void onLost(Network network) {
1918 if (network.equals(currentNetwork)) clearDnsBinding();
1919 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1920 }
1921 };
1922 }
1923
1924 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1925 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1926 new HashMap<>();
1927
1928 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1929 synchronized (sLegacyRequests) {
1930 LegacyRequest l = sLegacyRequests.get(netCap);
1931 if (l != null) return l.networkRequest;
1932 }
1933 return null;
1934 }
1935
1936 private void renewRequestLocked(LegacyRequest l) {
1937 l.expireSequenceNumber++;
1938 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1939 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1940 }
1941
1942 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1943 int ourSeqNum = -1;
1944 synchronized (sLegacyRequests) {
1945 LegacyRequest l = sLegacyRequests.get(netCap);
1946 if (l == null) return;
1947 ourSeqNum = l.expireSequenceNumber;
1948 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
1949 }
1950 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1951 }
1952
1953 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1954 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1955 int delay = -1;
1956 int type = legacyTypeForNetworkCapabilities(netCap);
1957 try {
1958 delay = mService.getRestoreDefaultNetworkDelay(type);
1959 } catch (RemoteException e) {
1960 throw e.rethrowFromSystemServer();
1961 }
1962 LegacyRequest l = new LegacyRequest();
1963 l.networkCapabilities = netCap;
1964 l.delay = delay;
1965 l.expireSequenceNumber = 0;
1966 l.networkRequest = sendRequestForNetwork(
1967 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
1968 if (l.networkRequest == null) return null;
1969 sLegacyRequests.put(netCap, l);
1970 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1971 return l.networkRequest;
1972 }
1973
1974 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1975 if (delay >= 0) {
1976 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
1977 CallbackHandler handler = getDefaultHandler();
1978 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1979 handler.sendMessageDelayed(msg, delay);
1980 }
1981 }
1982
1983 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1984 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1985 final LegacyRequest l;
1986 synchronized (sLegacyRequests) {
1987 l = sLegacyRequests.remove(netCap);
1988 }
1989 if (l == null) return false;
1990 unregisterNetworkCallback(l.networkCallback);
1991 l.clearDnsBinding();
1992 return true;
1993 }
1994
1995 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1996 static {
1997 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1998 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1999 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2000 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2001 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2002 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2003 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2004 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2005 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2006 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2007 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2008 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2009 }
2010
2011 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2012 static {
2013 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2014 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2015 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2016 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2017 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2018 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2019 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2020 }
2021
2022 /**
2023 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2024 * instance suitable for registering a request or callback. Throws an
2025 * IllegalArgumentException if no mapping from the legacy type to
2026 * NetworkCapabilities is known.
2027 *
2028 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2029 * to find the network instead.
2030 * @hide
2031 */
2032 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2033 final NetworkCapabilities nc = new NetworkCapabilities();
2034
2035 // Map from type to transports.
2036 final int NOT_FOUND = -1;
2037 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002038 if (transport == NOT_FOUND) {
2039 throw new IllegalArgumentException("unknown legacy type: " + type);
2040 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002041 nc.addTransportType(transport);
2042
2043 // Map from type to capabilities.
2044 nc.addCapability(sLegacyTypeToCapability.get(
2045 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2046 nc.maybeMarkCapabilitiesRestricted();
2047 return nc;
2048 }
2049
2050 /** @hide */
2051 public static class PacketKeepaliveCallback {
2052 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2053 public PacketKeepaliveCallback() {
2054 }
2055 /** The requested keepalive was successfully started. */
2056 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2057 public void onStarted() {}
2058 /** The keepalive was successfully stopped. */
2059 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2060 public void onStopped() {}
2061 /** An error occurred. */
2062 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2063 public void onError(int error) {}
2064 }
2065
2066 /**
2067 * Allows applications to request that the system periodically send specific packets on their
2068 * behalf, using hardware offload to save battery power.
2069 *
2070 * To request that the system send keepalives, call one of the methods that return a
2071 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2072 * passing in a non-null callback. If the callback is successfully started, the callback's
2073 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2074 * specifying one of the {@code ERROR_*} constants in this class.
2075 *
2076 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2077 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2078 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2079 *
2080 * @deprecated Use {@link SocketKeepalive} instead.
2081 *
2082 * @hide
2083 */
2084 public class PacketKeepalive {
2085
2086 private static final String TAG = "PacketKeepalive";
2087
2088 /** @hide */
2089 public static final int SUCCESS = 0;
2090
2091 /** @hide */
2092 public static final int NO_KEEPALIVE = -1;
2093
2094 /** @hide */
2095 public static final int BINDER_DIED = -10;
2096
2097 /** The specified {@code Network} is not connected. */
2098 public static final int ERROR_INVALID_NETWORK = -20;
2099 /** The specified IP addresses are invalid. For example, the specified source IP address is
2100 * not configured on the specified {@code Network}. */
2101 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2102 /** The requested port is invalid. */
2103 public static final int ERROR_INVALID_PORT = -22;
2104 /** The packet length is invalid (e.g., too long). */
2105 public static final int ERROR_INVALID_LENGTH = -23;
2106 /** The packet transmission interval is invalid (e.g., too short). */
2107 public static final int ERROR_INVALID_INTERVAL = -24;
2108
2109 /** The hardware does not support this request. */
2110 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2111 /** The hardware returned an error. */
2112 public static final int ERROR_HARDWARE_ERROR = -31;
2113
2114 /** The NAT-T destination port for IPsec */
2115 public static final int NATT_PORT = 4500;
2116
2117 /** The minimum interval in seconds between keepalive packet transmissions */
2118 public static final int MIN_INTERVAL = 10;
2119
2120 private final Network mNetwork;
2121 private final ISocketKeepaliveCallback mCallback;
2122 private final ExecutorService mExecutor;
2123
2124 private volatile Integer mSlot;
2125
2126 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2127 public void stop() {
2128 try {
2129 mExecutor.execute(() -> {
2130 try {
2131 if (mSlot != null) {
2132 mService.stopKeepalive(mNetwork, mSlot);
2133 }
2134 } catch (RemoteException e) {
2135 Log.e(TAG, "Error stopping packet keepalive: ", e);
2136 throw e.rethrowFromSystemServer();
2137 }
2138 });
2139 } catch (RejectedExecutionException e) {
2140 // The internal executor has already stopped due to previous event.
2141 }
2142 }
2143
2144 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002145 Objects.requireNonNull(network, "network cannot be null");
2146 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002147 mNetwork = network;
2148 mExecutor = Executors.newSingleThreadExecutor();
2149 mCallback = new ISocketKeepaliveCallback.Stub() {
2150 @Override
2151 public void onStarted(int slot) {
2152 final long token = Binder.clearCallingIdentity();
2153 try {
2154 mExecutor.execute(() -> {
2155 mSlot = slot;
2156 callback.onStarted();
2157 });
2158 } finally {
2159 Binder.restoreCallingIdentity(token);
2160 }
2161 }
2162
2163 @Override
2164 public void onStopped() {
2165 final long token = Binder.clearCallingIdentity();
2166 try {
2167 mExecutor.execute(() -> {
2168 mSlot = null;
2169 callback.onStopped();
2170 });
2171 } finally {
2172 Binder.restoreCallingIdentity(token);
2173 }
2174 mExecutor.shutdown();
2175 }
2176
2177 @Override
2178 public void onError(int error) {
2179 final long token = Binder.clearCallingIdentity();
2180 try {
2181 mExecutor.execute(() -> {
2182 mSlot = null;
2183 callback.onError(error);
2184 });
2185 } finally {
2186 Binder.restoreCallingIdentity(token);
2187 }
2188 mExecutor.shutdown();
2189 }
2190
2191 @Override
2192 public void onDataReceived() {
2193 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2194 // this callback when data is received.
2195 }
2196 };
2197 }
2198 }
2199
2200 /**
2201 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2202 *
2203 * @deprecated Use {@link #createSocketKeepalive} instead.
2204 *
2205 * @hide
2206 */
2207 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2208 public PacketKeepalive startNattKeepalive(
2209 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2210 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2211 final PacketKeepalive k = new PacketKeepalive(network, callback);
2212 try {
2213 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2214 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2215 } catch (RemoteException e) {
2216 Log.e(TAG, "Error starting packet keepalive: ", e);
2217 throw e.rethrowFromSystemServer();
2218 }
2219 return k;
2220 }
2221
2222 // Construct an invalid fd.
2223 private ParcelFileDescriptor createInvalidFd() {
2224 final int invalidFd = -1;
2225 return ParcelFileDescriptor.adoptFd(invalidFd);
2226 }
2227
2228 /**
2229 * Request that keepalives be started on a IPsec NAT-T socket.
2230 *
2231 * @param network The {@link Network} the socket is on.
2232 * @param socket The socket that needs to be kept alive.
2233 * @param source The source address of the {@link UdpEncapsulationSocket}.
2234 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2235 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2236 * must run callback sequentially, otherwise the order of callbacks cannot be
2237 * guaranteed.
2238 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2239 * changes. Must be extended by applications that use this API.
2240 *
2241 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2242 * given socket.
2243 **/
2244 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2245 @NonNull UdpEncapsulationSocket socket,
2246 @NonNull InetAddress source,
2247 @NonNull InetAddress destination,
2248 @NonNull @CallbackExecutor Executor executor,
2249 @NonNull Callback callback) {
2250 ParcelFileDescriptor dup;
2251 try {
2252 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2253 // which cannot be obtained by the app process.
2254 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2255 } catch (IOException ignored) {
2256 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2257 // ERROR_INVALID_SOCKET.
2258 dup = createInvalidFd();
2259 }
2260 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2261 destination, executor, callback);
2262 }
2263
2264 /**
2265 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2266 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2267 *
2268 * @param network The {@link Network} the socket is on.
2269 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2270 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2271 * from that port.
2272 * @param source The source address of the {@link UdpEncapsulationSocket}.
2273 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2274 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2275 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2276 * must run callback sequentially, otherwise the order of callbacks cannot be
2277 * guaranteed.
2278 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2279 * changes. Must be extended by applications that use this API.
2280 *
2281 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2282 * given socket.
2283 * @hide
2284 */
2285 @SystemApi
2286 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2287 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2288 @NonNull ParcelFileDescriptor pfd,
2289 @NonNull InetAddress source,
2290 @NonNull InetAddress destination,
2291 @NonNull @CallbackExecutor Executor executor,
2292 @NonNull Callback callback) {
2293 ParcelFileDescriptor dup;
2294 try {
2295 // TODO: Consider remove unnecessary dup.
2296 dup = pfd.dup();
2297 } catch (IOException ignored) {
2298 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2299 // ERROR_INVALID_SOCKET.
2300 dup = createInvalidFd();
2301 }
2302 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002303 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002304 }
2305
2306 /**
2307 * Request that keepalives be started on a TCP socket.
2308 * The socket must be established.
2309 *
2310 * @param network The {@link Network} the socket is on.
2311 * @param socket The socket that needs to be kept alive.
2312 * @param executor The executor on which callback will be invoked. This implementation assumes
2313 * the provided {@link Executor} runs the callbacks in sequence with no
2314 * concurrency. Failing this, no guarantee of correctness can be made. It is
2315 * the responsibility of the caller to ensure the executor provides this
2316 * guarantee. A simple way of creating such an executor is with the standard
2317 * tool {@code Executors.newSingleThreadExecutor}.
2318 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2319 * changes. Must be extended by applications that use this API.
2320 *
2321 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2322 * given socket.
2323 * @hide
2324 */
2325 @SystemApi
2326 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2327 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2328 @NonNull Socket socket,
2329 @NonNull Executor executor,
2330 @NonNull Callback callback) {
2331 ParcelFileDescriptor dup;
2332 try {
2333 dup = ParcelFileDescriptor.fromSocket(socket);
2334 } catch (UncheckedIOException ignored) {
2335 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2336 // ERROR_INVALID_SOCKET.
2337 dup = createInvalidFd();
2338 }
2339 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2340 }
2341
2342 /**
2343 * Ensure that a network route exists to deliver traffic to the specified
2344 * host via the specified network interface. An attempt to add a route that
2345 * already exists is ignored, but treated as successful.
2346 *
2347 * <p>This method requires the caller to hold either the
2348 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2349 * or the ability to modify system settings as determined by
2350 * {@link android.provider.Settings.System#canWrite}.</p>
2351 *
2352 * @param networkType the type of the network over which traffic to the specified
2353 * host is to be routed
2354 * @param hostAddress the IP address of the host to which the route is desired
2355 * @return {@code true} on success, {@code false} on failure
2356 *
2357 * @deprecated Deprecated in favor of the
2358 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2359 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2360 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2361 * throw {@code UnsupportedOperationException} if called.
2362 * @removed
2363 */
2364 @Deprecated
2365 public boolean requestRouteToHost(int networkType, int hostAddress) {
2366 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2367 }
2368
2369 /**
2370 * Ensure that a network route exists to deliver traffic to the specified
2371 * host via the specified network interface. An attempt to add a route that
2372 * already exists is ignored, but treated as successful.
2373 *
2374 * <p>This method requires the caller to hold either the
2375 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2376 * or the ability to modify system settings as determined by
2377 * {@link android.provider.Settings.System#canWrite}.</p>
2378 *
2379 * @param networkType the type of the network over which traffic to the specified
2380 * host is to be routed
2381 * @param hostAddress the IP address of the host to which the route is desired
2382 * @return {@code true} on success, {@code false} on failure
2383 * @hide
2384 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2385 * {@link #bindProcessToNetwork} API.
2386 */
2387 @Deprecated
2388 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002389 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002390 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2391 checkLegacyRoutingApiAccess();
2392 try {
2393 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2394 mContext.getOpPackageName(), getAttributionTag());
2395 } catch (RemoteException e) {
2396 throw e.rethrowFromSystemServer();
2397 }
2398 }
2399
2400 /**
2401 * @return the context's attribution tag
2402 */
2403 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2404 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002405 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002406 }
2407
2408 /**
2409 * Returns the value of the setting for background data usage. If false,
2410 * applications should not use the network if the application is not in the
2411 * foreground. Developers should respect this setting, and check the value
2412 * of this before performing any background data operations.
2413 * <p>
2414 * All applications that have background services that use the network
2415 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2416 * <p>
2417 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2418 * background data depends on several combined factors, and this method will
2419 * always return {@code true}. Instead, when background data is unavailable,
2420 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2421 *
2422 * @return Whether background data usage is allowed.
2423 */
2424 @Deprecated
2425 public boolean getBackgroundDataSetting() {
2426 // assume that background data is allowed; final authority is
2427 // NetworkInfo which may be blocked.
2428 return true;
2429 }
2430
2431 /**
2432 * Sets the value of the setting for background data usage.
2433 *
2434 * @param allowBackgroundData Whether an application should use data while
2435 * it is in the background.
2436 *
2437 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2438 * @see #getBackgroundDataSetting()
2439 * @hide
2440 */
2441 @Deprecated
2442 @UnsupportedAppUsage
2443 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2444 // ignored
2445 }
2446
2447 /**
2448 * @hide
2449 * @deprecated Talk to TelephonyManager directly
2450 */
2451 @Deprecated
2452 @UnsupportedAppUsage
2453 public boolean getMobileDataEnabled() {
2454 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2455 if (tm != null) {
2456 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2457 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2458 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2459 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2460 + " retVal=" + retVal);
2461 return retVal;
2462 }
2463 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2464 return false;
2465 }
2466
2467 /**
2468 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2469 * to find out when the system default network has gone in to a high power state.
2470 */
2471 public interface OnNetworkActiveListener {
2472 /**
2473 * Called on the main thread of the process to report that the current data network
2474 * has become active, and it is now a good time to perform any pending network
2475 * operations. Note that this listener only tells you when the network becomes
2476 * active; if at any other time you want to know whether it is active (and thus okay
2477 * to initiate network traffic), you can retrieve its instantaneous state with
2478 * {@link ConnectivityManager#isDefaultNetworkActive}.
2479 */
2480 void onNetworkActive();
2481 }
2482
Chiachang Wang2de41682021-09-23 10:46:03 +08002483 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002484 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2485 mNetworkActivityListeners = new ArrayMap<>();
2486
2487 /**
2488 * Start listening to reports when the system's default data network is active, meaning it is
2489 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2490 * to determine the current state of the system's default network after registering the
2491 * listener.
2492 * <p>
2493 * If the process default network has been set with
2494 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2495 * reflect the process's default, but the system default.
2496 *
2497 * @param l The listener to be told when the network is active.
2498 */
2499 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002500 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002501 @Override
2502 public void onNetworkActive() throws RemoteException {
2503 l.onNetworkActive();
2504 }
2505 };
2506
Chiachang Wang2de41682021-09-23 10:46:03 +08002507 synchronized (mNetworkActivityListeners) {
2508 try {
2509 mService.registerNetworkActivityListener(rl);
2510 mNetworkActivityListeners.put(l, rl);
2511 } catch (RemoteException e) {
2512 throw e.rethrowFromSystemServer();
2513 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002514 }
2515 }
2516
2517 /**
2518 * Remove network active listener previously registered with
2519 * {@link #addDefaultNetworkActiveListener}.
2520 *
2521 * @param l Previously registered listener.
2522 */
2523 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002524 synchronized (mNetworkActivityListeners) {
2525 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2526 if (rl == null) {
2527 throw new IllegalArgumentException("Listener was not registered.");
2528 }
2529 try {
2530 mService.unregisterNetworkActivityListener(rl);
2531 mNetworkActivityListeners.remove(l);
2532 } catch (RemoteException e) {
2533 throw e.rethrowFromSystemServer();
2534 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002535 }
2536 }
2537
2538 /**
2539 * Return whether the data network is currently active. An active network means that
2540 * it is currently in a high power state for performing data transmission. On some
2541 * types of networks, it may be expensive to move and stay in such a state, so it is
2542 * more power efficient to batch network traffic together when the radio is already in
2543 * this state. This method tells you whether right now is currently a good time to
2544 * initiate network traffic, as the network is already active.
2545 */
2546 public boolean isDefaultNetworkActive() {
2547 try {
lucaslin709eb842021-01-21 02:04:15 +08002548 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002549 } catch (RemoteException e) {
2550 throw e.rethrowFromSystemServer();
2551 }
2552 }
2553
2554 /**
2555 * {@hide}
2556 */
2557 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002558 mContext = Objects.requireNonNull(context, "missing context");
2559 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002560 sInstance = this;
2561 }
2562
2563 /** {@hide} */
2564 @UnsupportedAppUsage
2565 public static ConnectivityManager from(Context context) {
2566 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2567 }
2568
2569 /** @hide */
2570 public NetworkRequest getDefaultRequest() {
2571 try {
2572 // This is not racy as the default request is final in ConnectivityService.
2573 return mService.getDefaultRequest();
2574 } catch (RemoteException e) {
2575 throw e.rethrowFromSystemServer();
2576 }
2577 }
2578
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002579 /**
2580 * Check if the package is a allowed to write settings. This also accounts that such an access
2581 * happened.
2582 *
2583 * @return {@code true} iff the package is allowed to write settings.
2584 */
2585 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2586 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2587 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2588 boolean throwException) {
2589 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002590 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002591 }
2592
2593 /**
2594 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2595 * situations where a Context pointer is unavailable.
2596 * @hide
2597 */
2598 @Deprecated
2599 static ConnectivityManager getInstanceOrNull() {
2600 return sInstance;
2601 }
2602
2603 /**
2604 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2605 * situations where a Context pointer is unavailable.
2606 * @hide
2607 */
2608 @Deprecated
2609 @UnsupportedAppUsage
2610 private static ConnectivityManager getInstance() {
2611 if (getInstanceOrNull() == null) {
2612 throw new IllegalStateException("No ConnectivityManager yet constructed");
2613 }
2614 return getInstanceOrNull();
2615 }
2616
2617 /**
2618 * Get the set of tetherable, available interfaces. This list is limited by
2619 * device configuration and current interface existence.
2620 *
2621 * @return an array of 0 or more Strings of tetherable interface names.
2622 *
2623 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2624 * {@hide}
2625 */
2626 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2627 @UnsupportedAppUsage
2628 @Deprecated
2629 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002630 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002631 }
2632
2633 /**
2634 * Get the set of tethered interfaces.
2635 *
2636 * @return an array of 0 or more String of currently tethered interface names.
2637 *
2638 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2639 * {@hide}
2640 */
2641 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2642 @UnsupportedAppUsage
2643 @Deprecated
2644 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002645 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002646 }
2647
2648 /**
2649 * Get the set of interface names which attempted to tether but
2650 * failed. Re-attempting to tether may cause them to reset to the Tethered
2651 * state. Alternatively, causing the interface to be destroyed and recreated
2652 * may cause them to reset to the available state.
2653 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2654 * information on the cause of the errors.
2655 *
2656 * @return an array of 0 or more String indicating the interface names
2657 * which failed to tether.
2658 *
2659 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2660 * {@hide}
2661 */
2662 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2663 @UnsupportedAppUsage
2664 @Deprecated
2665 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002666 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002667 }
2668
2669 /**
2670 * Get the set of tethered dhcp ranges.
2671 *
2672 * @deprecated This method is not supported.
2673 * TODO: remove this function when all of clients are removed.
2674 * {@hide}
2675 */
2676 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2677 @Deprecated
2678 public String[] getTetheredDhcpRanges() {
2679 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2680 }
2681
2682 /**
2683 * Attempt to tether the named interface. This will setup a dhcp server
2684 * on the interface, forward and NAT IP packets and forward DNS requests
2685 * to the best active upstream network interface. Note that if no upstream
2686 * IP network interface is available, dhcp will still run and traffic will be
2687 * allowed between the tethered devices and this device, though upstream net
2688 * access will of course fail until an upstream network interface becomes
2689 * active.
2690 *
2691 * <p>This method requires the caller to hold either the
2692 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2693 * or the ability to modify system settings as determined by
2694 * {@link android.provider.Settings.System#canWrite}.</p>
2695 *
2696 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2697 * and WifiStateMachine which need direct access. All other clients should use
2698 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2699 * logic.</p>
2700 *
2701 * @param iface the interface name to tether.
2702 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2703 * @deprecated Use {@link TetheringManager#startTethering} instead
2704 *
2705 * {@hide}
2706 */
2707 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2708 @Deprecated
2709 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002710 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002711 }
2712
2713 /**
2714 * Stop tethering the named interface.
2715 *
2716 * <p>This method requires the caller to hold either the
2717 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2718 * or the ability to modify system settings as determined by
2719 * {@link android.provider.Settings.System#canWrite}.</p>
2720 *
2721 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2722 * and WifiStateMachine which need direct access. All other clients should use
2723 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2724 * logic.</p>
2725 *
2726 * @param iface the interface name to untether.
2727 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2728 *
2729 * {@hide}
2730 */
2731 @UnsupportedAppUsage
2732 @Deprecated
2733 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002734 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002735 }
2736
2737 /**
2738 * Check if the device allows for tethering. It may be disabled via
2739 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2740 * due to device configuration.
2741 *
2742 * <p>If this app does not have permission to use this API, it will always
2743 * return false rather than throw an exception.</p>
2744 *
2745 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2746 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2747 *
2748 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2749 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2750 *
2751 * @return a boolean - {@code true} indicating Tethering is supported.
2752 *
2753 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2754 * {@hide}
2755 */
2756 @SystemApi
2757 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2758 android.Manifest.permission.WRITE_SETTINGS})
2759 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002760 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002761 }
2762
2763 /**
2764 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2765 *
2766 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2767 * @hide
2768 */
2769 @SystemApi
2770 @Deprecated
2771 public static abstract class OnStartTetheringCallback {
2772 /**
2773 * Called when tethering has been successfully started.
2774 */
2775 public void onTetheringStarted() {}
2776
2777 /**
2778 * Called when starting tethering failed.
2779 */
2780 public void onTetheringFailed() {}
2781 }
2782
2783 /**
2784 * Convenient overload for
2785 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2786 * handler to run on the current thread's {@link Looper}.
2787 *
2788 * @deprecated Use {@link TetheringManager#startTethering} instead.
2789 * @hide
2790 */
2791 @SystemApi
2792 @Deprecated
2793 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2794 public void startTethering(int type, boolean showProvisioningUi,
2795 final OnStartTetheringCallback callback) {
2796 startTethering(type, showProvisioningUi, callback, null);
2797 }
2798
2799 /**
2800 * Runs tether provisioning for the given type if needed and then starts tethering if
2801 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2802 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2803 * schedules tether provisioning re-checks if appropriate.
2804 *
2805 * @param type The type of tethering to start. Must be one of
2806 * {@link ConnectivityManager.TETHERING_WIFI},
2807 * {@link ConnectivityManager.TETHERING_USB}, or
2808 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2809 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2810 * is one. This should be true the first time this function is called and also any time
2811 * the user can see this UI. It gives users information from their carrier about the
2812 * check failing and how they can sign up for tethering if possible.
2813 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2814 * of the result of trying to tether.
2815 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2816 *
2817 * @deprecated Use {@link TetheringManager#startTethering} instead.
2818 * @hide
2819 */
2820 @SystemApi
2821 @Deprecated
2822 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2823 public void startTethering(int type, boolean showProvisioningUi,
2824 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002825 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002826
2827 final Executor executor = new Executor() {
2828 @Override
2829 public void execute(Runnable command) {
2830 if (handler == null) {
2831 command.run();
2832 } else {
2833 handler.post(command);
2834 }
2835 }
2836 };
2837
2838 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2839 @Override
2840 public void onTetheringStarted() {
2841 callback.onTetheringStarted();
2842 }
2843
2844 @Override
2845 public void onTetheringFailed(final int error) {
2846 callback.onTetheringFailed();
2847 }
2848 };
2849
2850 final TetheringRequest request = new TetheringRequest.Builder(type)
2851 .setShouldShowEntitlementUi(showProvisioningUi).build();
2852
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002853 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002854 }
2855
2856 /**
2857 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2858 * applicable.
2859 *
2860 * @param type The type of tethering to stop. Must be one of
2861 * {@link ConnectivityManager.TETHERING_WIFI},
2862 * {@link ConnectivityManager.TETHERING_USB}, or
2863 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2864 *
2865 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2866 * @hide
2867 */
2868 @SystemApi
2869 @Deprecated
2870 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2871 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002872 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002873 }
2874
2875 /**
2876 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2877 * upstream status.
2878 *
2879 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2880 * @hide
2881 */
2882 @SystemApi
2883 @Deprecated
2884 public abstract static class OnTetheringEventCallback {
2885
2886 /**
2887 * Called when tethering upstream changed. This can be called multiple times and can be
2888 * called any time.
2889 *
2890 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2891 * have any upstream.
2892 */
2893 public void onUpstreamChanged(@Nullable Network network) {}
2894 }
2895
2896 @GuardedBy("mTetheringEventCallbacks")
2897 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2898 mTetheringEventCallbacks = new ArrayMap<>();
2899
2900 /**
2901 * Start listening to tethering change events. Any new added callback will receive the last
2902 * tethering status right away. If callback is registered when tethering has no upstream or
2903 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2904 * with a null argument. The same callback object cannot be registered twice.
2905 *
2906 * @param executor the executor on which callback will be invoked.
2907 * @param callback the callback to be called when tethering has change events.
2908 *
2909 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2910 * @hide
2911 */
2912 @SystemApi
2913 @Deprecated
2914 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2915 public void registerTetheringEventCallback(
2916 @NonNull @CallbackExecutor Executor executor,
2917 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002918 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002919
2920 final TetheringEventCallback tetherCallback =
2921 new TetheringEventCallback() {
2922 @Override
2923 public void onUpstreamChanged(@Nullable Network network) {
2924 callback.onUpstreamChanged(network);
2925 }
2926 };
2927
2928 synchronized (mTetheringEventCallbacks) {
2929 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002930 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002931 }
2932 }
2933
2934 /**
2935 * Remove tethering event callback previously registered with
2936 * {@link #registerTetheringEventCallback}.
2937 *
2938 * @param callback previously registered callback.
2939 *
2940 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
2941 * @hide
2942 */
2943 @SystemApi
2944 @Deprecated
2945 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2946 public void unregisterTetheringEventCallback(
2947 @NonNull final OnTetheringEventCallback callback) {
2948 Objects.requireNonNull(callback, "The callback must be non-null");
2949 synchronized (mTetheringEventCallbacks) {
2950 final TetheringEventCallback tetherCallback =
2951 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002952 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002953 }
2954 }
2955
2956
2957 /**
2958 * Get the list of regular expressions that define any tetherable
2959 * USB network interfaces. If USB tethering is not supported by the
2960 * device, this list should be empty.
2961 *
2962 * @return an array of 0 or more regular expression Strings defining
2963 * what interfaces are considered tetherable usb interfaces.
2964 *
2965 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2966 * {@hide}
2967 */
2968 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2969 @UnsupportedAppUsage
2970 @Deprecated
2971 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002972 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002973 }
2974
2975 /**
2976 * Get the list of regular expressions that define any tetherable
2977 * Wifi network interfaces. If Wifi tethering is not supported by the
2978 * device, this list should be empty.
2979 *
2980 * @return an array of 0 or more regular expression Strings defining
2981 * what interfaces are considered tetherable wifi interfaces.
2982 *
2983 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2984 * {@hide}
2985 */
2986 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2987 @UnsupportedAppUsage
2988 @Deprecated
2989 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002990 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002991 }
2992
2993 /**
2994 * Get the list of regular expressions that define any tetherable
2995 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2996 * device, this list should be empty.
2997 *
2998 * @return an array of 0 or more regular expression Strings defining
2999 * what interfaces are considered tetherable bluetooth interfaces.
3000 *
3001 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3002 *TetheringManager.TetheringInterfaceRegexps)} instead.
3003 * {@hide}
3004 */
3005 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3006 @UnsupportedAppUsage
3007 @Deprecated
3008 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003009 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003010 }
3011
3012 /**
3013 * Attempt to both alter the mode of USB and Tethering of USB. A
3014 * utility method to deal with some of the complexity of USB - will
3015 * attempt to switch to Rndis and subsequently tether the resulting
3016 * interface on {@code true} or turn off tethering and switch off
3017 * Rndis on {@code false}.
3018 *
3019 * <p>This method requires the caller to hold either the
3020 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3021 * or the ability to modify system settings as determined by
3022 * {@link android.provider.Settings.System#canWrite}.</p>
3023 *
3024 * @param enable a boolean - {@code true} to enable tethering
3025 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3026 * @deprecated Use {@link TetheringManager#startTethering} instead
3027 *
3028 * {@hide}
3029 */
3030 @UnsupportedAppUsage
3031 @Deprecated
3032 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003033 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003034 }
3035
3036 /**
3037 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3038 * {@hide}
3039 */
3040 @SystemApi
3041 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003042 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003043 /**
3044 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3045 * {@hide}
3046 */
3047 @Deprecated
3048 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3049 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3050 /**
3051 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3052 * {@hide}
3053 */
3054 @Deprecated
3055 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3056 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3057 /**
3058 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3059 * {@hide}
3060 */
3061 @Deprecated
3062 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3063 /**
3064 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3065 * {@hide}
3066 */
3067 @Deprecated
3068 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3069 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3070 /**
3071 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3072 * {@hide}
3073 */
3074 @Deprecated
3075 public static final int TETHER_ERROR_MASTER_ERROR =
3076 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3077 /**
3078 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3079 * {@hide}
3080 */
3081 @Deprecated
3082 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3083 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3084 /**
3085 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3086 * {@hide}
3087 */
3088 @Deprecated
3089 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3090 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3091 /**
3092 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3093 * {@hide}
3094 */
3095 @Deprecated
3096 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3097 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3098 /**
3099 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3100 * {@hide}
3101 */
3102 @Deprecated
3103 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3104 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3105 /**
3106 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3107 * {@hide}
3108 */
3109 @Deprecated
3110 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3111 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3112 /**
3113 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3114 * {@hide}
3115 */
3116 @SystemApi
3117 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003118 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003119 /**
3120 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3121 * {@hide}
3122 */
3123 @Deprecated
3124 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3125 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3126 /**
3127 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3128 * {@hide}
3129 */
3130 @SystemApi
3131 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003132 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003133
3134 /**
3135 * Get a more detailed error code after a Tethering or Untethering
3136 * request asynchronously failed.
3137 *
3138 * @param iface The name of the interface of interest
3139 * @return error The error code of the last error tethering or untethering the named
3140 * interface
3141 *
3142 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3143 * {@hide}
3144 */
3145 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3146 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3147 @Deprecated
3148 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003149 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003150 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3151 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3152 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3153 // instead.
3154 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3155 }
3156 return error;
3157 }
3158
3159 /** @hide */
3160 @Retention(RetentionPolicy.SOURCE)
3161 @IntDef(value = {
3162 TETHER_ERROR_NO_ERROR,
3163 TETHER_ERROR_PROVISION_FAILED,
3164 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3165 })
3166 public @interface EntitlementResultCode {
3167 }
3168
3169 /**
3170 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3171 * entitlement succeeded.
3172 *
3173 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3174 * @hide
3175 */
3176 @SystemApi
3177 @Deprecated
3178 public interface OnTetheringEntitlementResultListener {
3179 /**
3180 * Called to notify entitlement result.
3181 *
3182 * @param resultCode an int value of entitlement result. It may be one of
3183 * {@link #TETHER_ERROR_NO_ERROR},
3184 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3185 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3186 */
3187 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3188 }
3189
3190 /**
3191 * Get the last value of the entitlement check on this downstream. If the cached value is
3192 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3193 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3194 * guaranteed that the UI-based entitlement check will complete in any specific time period
3195 * and may in fact never complete. Any successful entitlement check the platform performs for
3196 * any reason will update the cached value.
3197 *
3198 * @param type the downstream type of tethering. Must be one of
3199 * {@link #TETHERING_WIFI},
3200 * {@link #TETHERING_USB}, or
3201 * {@link #TETHERING_BLUETOOTH}.
3202 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3203 * @param executor the executor on which callback will be invoked.
3204 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3205 * notify the caller of the result of entitlement check. The listener may be called zero
3206 * or one time.
3207 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3208 * {@hide}
3209 */
3210 @SystemApi
3211 @Deprecated
3212 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3213 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3214 @NonNull @CallbackExecutor Executor executor,
3215 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003216 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003217 ResultReceiver wrappedListener = new ResultReceiver(null) {
3218 @Override
3219 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003220 final long token = Binder.clearCallingIdentity();
3221 try {
3222 executor.execute(() -> {
3223 listener.onTetheringEntitlementResult(resultCode);
3224 });
3225 } finally {
3226 Binder.restoreCallingIdentity(token);
3227 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003228 }
3229 };
3230
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003231 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003232 showEntitlementUi);
3233 }
3234
3235 /**
3236 * Report network connectivity status. This is currently used only
3237 * to alter status bar UI.
3238 * <p>This method requires the caller to hold the permission
3239 * {@link android.Manifest.permission#STATUS_BAR}.
3240 *
3241 * @param networkType The type of network you want to report on
3242 * @param percentage The quality of the connection 0 is bad, 100 is good
3243 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3244 * {@hide}
3245 */
3246 public void reportInetCondition(int networkType, int percentage) {
3247 printStackTrace();
3248 try {
3249 mService.reportInetCondition(networkType, percentage);
3250 } catch (RemoteException e) {
3251 throw e.rethrowFromSystemServer();
3252 }
3253 }
3254
3255 /**
3256 * Report a problem network to the framework. This provides a hint to the system
3257 * that there might be connectivity problems on this network and may cause
3258 * the framework to re-evaluate network connectivity and/or switch to another
3259 * network.
3260 *
3261 * @param network The {@link Network} the application was attempting to use
3262 * or {@code null} to indicate the current default network.
3263 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3264 * working and non-working connectivity.
3265 */
3266 @Deprecated
3267 public void reportBadNetwork(@Nullable Network network) {
3268 printStackTrace();
3269 try {
3270 // One of these will be ignored because it matches system's current state.
3271 // The other will trigger the necessary reevaluation.
3272 mService.reportNetworkConnectivity(network, true);
3273 mService.reportNetworkConnectivity(network, false);
3274 } catch (RemoteException e) {
3275 throw e.rethrowFromSystemServer();
3276 }
3277 }
3278
3279 /**
3280 * Report to the framework whether a network has working connectivity.
3281 * This provides a hint to the system that a particular network is providing
3282 * working connectivity or not. In response the framework may re-evaluate
3283 * the network's connectivity and might take further action thereafter.
3284 *
3285 * @param network The {@link Network} the application was attempting to use
3286 * or {@code null} to indicate the current default network.
3287 * @param hasConnectivity {@code true} if the application was able to successfully access the
3288 * Internet using {@code network} or {@code false} if not.
3289 */
3290 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3291 printStackTrace();
3292 try {
3293 mService.reportNetworkConnectivity(network, hasConnectivity);
3294 } catch (RemoteException e) {
3295 throw e.rethrowFromSystemServer();
3296 }
3297 }
3298
3299 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003300 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003301 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003302 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3303 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3304 * accessing any network, regardless of what the settings for that network are.
3305 *
3306 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3307 * proxy is likely to break networking on multiple networks. This method is only meant
3308 * for device policy clients looking to do general internal filtering or similar use cases.
3309 *
3310 * {@see #getGlobalProxy}
3311 * {@see LinkProperties#getHttpProxy}
3312 *
3313 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3314 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003315 * @hide
3316 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003317 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003318 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003319 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003320 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003321 try {
3322 mService.setGlobalProxy(p);
3323 } catch (RemoteException e) {
3324 throw e.rethrowFromSystemServer();
3325 }
3326 }
3327
3328 /**
3329 * Retrieve any network-independent global HTTP proxy.
3330 *
3331 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3332 * if no global HTTP proxy is set.
3333 * @hide
3334 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003335 @SystemApi(client = MODULE_LIBRARIES)
3336 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003337 public ProxyInfo getGlobalProxy() {
3338 try {
3339 return mService.getGlobalProxy();
3340 } catch (RemoteException e) {
3341 throw e.rethrowFromSystemServer();
3342 }
3343 }
3344
3345 /**
3346 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3347 * network-specific HTTP proxy. If {@code network} is null, the
3348 * network-specific proxy returned is the proxy of the default active
3349 * network.
3350 *
3351 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3352 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3353 * or when {@code network} is {@code null},
3354 * the {@code ProxyInfo} for the default active network. Returns
3355 * {@code null} when no proxy applies or the caller doesn't have
3356 * permission to use {@code network}.
3357 * @hide
3358 */
3359 public ProxyInfo getProxyForNetwork(Network network) {
3360 try {
3361 return mService.getProxyForNetwork(network);
3362 } catch (RemoteException e) {
3363 throw e.rethrowFromSystemServer();
3364 }
3365 }
3366
3367 /**
3368 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3369 * otherwise if this process is bound to a {@link Network} using
3370 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3371 * the default network's proxy is returned.
3372 *
3373 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3374 * HTTP proxy is active.
3375 */
3376 @Nullable
3377 public ProxyInfo getDefaultProxy() {
3378 return getProxyForNetwork(getBoundNetworkForProcess());
3379 }
3380
3381 /**
3382 * Returns true if the hardware supports the given network type
3383 * else it returns false. This doesn't indicate we have coverage
3384 * or are authorized onto a network, just whether or not the
3385 * hardware supports it. For example a GSM phone without a SIM
3386 * should still return {@code true} for mobile data, but a wifi only
3387 * tablet would return {@code false}.
3388 *
3389 * @param networkType The network type we'd like to check
3390 * @return {@code true} if supported, else {@code false}
3391 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3392 * @hide
3393 */
3394 @Deprecated
3395 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3396 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3397 public boolean isNetworkSupported(int networkType) {
3398 try {
3399 return mService.isNetworkSupported(networkType);
3400 } catch (RemoteException e) {
3401 throw e.rethrowFromSystemServer();
3402 }
3403 }
3404
3405 /**
3406 * Returns if the currently active data network is metered. A network is
3407 * classified as metered when the user is sensitive to heavy data usage on
3408 * that connection due to monetary costs, data limitations or
3409 * battery/performance issues. You should check this before doing large
3410 * data transfers, and warn the user or delay the operation until another
3411 * network is available.
3412 *
3413 * @return {@code true} if large transfers should be avoided, otherwise
3414 * {@code false}.
3415 */
3416 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3417 public boolean isActiveNetworkMetered() {
3418 try {
3419 return mService.isActiveNetworkMetered();
3420 } catch (RemoteException e) {
3421 throw e.rethrowFromSystemServer();
3422 }
3423 }
3424
3425 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003426 * Set sign in error notification to visible or invisible
3427 *
3428 * @hide
3429 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3430 */
3431 @Deprecated
3432 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3433 String action) {
3434 try {
3435 mService.setProvisioningNotificationVisible(visible, networkType, action);
3436 } catch (RemoteException e) {
3437 throw e.rethrowFromSystemServer();
3438 }
3439 }
3440
3441 /**
3442 * Set the value for enabling/disabling airplane mode
3443 *
3444 * @param enable whether to enable airplane mode or not
3445 *
3446 * @hide
3447 */
3448 @RequiresPermission(anyOf = {
3449 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3450 android.Manifest.permission.NETWORK_SETTINGS,
3451 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3452 android.Manifest.permission.NETWORK_STACK})
3453 @SystemApi
3454 public void setAirplaneMode(boolean enable) {
3455 try {
3456 mService.setAirplaneMode(enable);
3457 } catch (RemoteException e) {
3458 throw e.rethrowFromSystemServer();
3459 }
3460 }
3461
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003462 /**
3463 * Registers the specified {@link NetworkProvider}.
3464 * Each listener must only be registered once. The listener can be unregistered with
3465 * {@link #unregisterNetworkProvider}.
3466 *
3467 * @param provider the provider to register
3468 * @return the ID of the provider. This ID must be used by the provider when registering
3469 * {@link android.net.NetworkAgent}s.
3470 * @hide
3471 */
3472 @SystemApi
3473 @RequiresPermission(anyOf = {
3474 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3475 android.Manifest.permission.NETWORK_FACTORY})
3476 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3477 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3478 throw new IllegalStateException("NetworkProviders can only be registered once");
3479 }
3480
3481 try {
3482 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3483 provider.getName());
3484 provider.setProviderId(providerId);
3485 } catch (RemoteException e) {
3486 throw e.rethrowFromSystemServer();
3487 }
3488 return provider.getProviderId();
3489 }
3490
3491 /**
3492 * Unregisters the specified NetworkProvider.
3493 *
3494 * @param provider the provider to unregister
3495 * @hide
3496 */
3497 @SystemApi
3498 @RequiresPermission(anyOf = {
3499 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3500 android.Manifest.permission.NETWORK_FACTORY})
3501 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3502 try {
3503 mService.unregisterNetworkProvider(provider.getMessenger());
3504 } catch (RemoteException e) {
3505 throw e.rethrowFromSystemServer();
3506 }
3507 provider.setProviderId(NetworkProvider.ID_NONE);
3508 }
3509
Chalard Jeand1b498b2021-01-05 08:40:09 +09003510 /**
3511 * Register or update a network offer with ConnectivityService.
3512 *
3513 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003514 * them to networking requests made by apps or the system. A callback identifies an offer
3515 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3516 * score and the capabilities of the network it might be able to bring up ; these act as
3517 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003518 * provider.
3519 *
3520 * The provider is under no obligation to be able to bring up the network it offers at any
3521 * given time. Instead, this mechanism is meant to limit requests received by providers
3522 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3523 * the quality of the network satisfying a given request to their own offer.
3524 *
3525 * An offer can be updated by calling this again with the same callback object. This is
3526 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3527 * provider with the changes caused by the changes in the offer.
3528 *
3529 * @param provider The provider making this offer.
3530 * @param score The prospective score of the network.
3531 * @param caps The prospective capabilities of the network.
3532 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003533 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003534 */
3535 @RequiresPermission(anyOf = {
3536 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3537 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003538 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003539 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3540 @NonNull final INetworkOfferCallback callback) {
3541 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003542 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003543 Objects.requireNonNull(score, "null score"),
3544 Objects.requireNonNull(caps, "null caps"),
3545 Objects.requireNonNull(callback, "null callback"));
3546 } catch (RemoteException e) {
3547 throw e.rethrowFromSystemServer();
3548 }
3549 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003550
Chalard Jeand1b498b2021-01-05 08:40:09 +09003551 /**
3552 * Withdraw a network offer made with {@link #offerNetwork}.
3553 *
3554 * @param callback The callback passed at registration time. This must be the same object
3555 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003556 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003557 */
3558 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3559 try {
3560 mService.unofferNetwork(Objects.requireNonNull(callback));
3561 } catch (RemoteException e) {
3562 throw e.rethrowFromSystemServer();
3563 }
3564 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003565 /** @hide exposed via the NetworkProvider class. */
3566 @RequiresPermission(anyOf = {
3567 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3568 android.Manifest.permission.NETWORK_FACTORY})
3569 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3570 try {
3571 mService.declareNetworkRequestUnfulfillable(request);
3572 } catch (RemoteException e) {
3573 throw e.rethrowFromSystemServer();
3574 }
3575 }
3576
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003577 /**
3578 * @hide
3579 * Register a NetworkAgent with ConnectivityService.
3580 * @return Network corresponding to NetworkAgent.
3581 */
3582 @RequiresPermission(anyOf = {
3583 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3584 android.Manifest.permission.NETWORK_FACTORY})
3585 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003586 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3587 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003588 try {
3589 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3590 } catch (RemoteException e) {
3591 throw e.rethrowFromSystemServer();
3592 }
3593 }
3594
3595 /**
3596 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3597 * changes. Should be extended by applications wanting notifications.
3598 *
3599 * A {@code NetworkCallback} is registered by calling
3600 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3601 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3602 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3603 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3604 * A {@code NetworkCallback} should be registered at most once at any time.
3605 * A {@code NetworkCallback} that has been unregistered can be registered again.
3606 */
3607 public static class NetworkCallback {
3608 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003609 * No flags associated with this callback.
3610 * @hide
3611 */
3612 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003613
Roshan Piuse08bc182020-12-22 15:10:42 -08003614 /**
lucaslinc582d502022-01-27 09:07:00 +08003615 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3616 *
3617 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3618 * Prior to Android 12, this information is always returned to apps holding the appropriate
3619 * permission, possibly noting that the app has used location.
3620 * <p>In Android 12 and above, by default the sent objects do not contain any location
3621 * information, even if the app holds the necessary permissions, and the system does not
3622 * take note of location usage by the app. Apps can request that location information is
3623 * included, in which case the system will check location permission and the location
3624 * toggle state, and take note of location usage by the app if any such information is
3625 * returned.
3626 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003627 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3628 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3629 * <p>
3630 * These include:
3631 * <li> Some transport info instances (retrieved via
3632 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3633 * contain location sensitive information.
3634 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003635 * sensitive for wifi suggestor apps (i.e using
3636 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003637 * </p>
3638 * <p>
3639 * Note:
3640 * <li> Retrieving this location sensitive information (subject to app's location
3641 * permissions) will be noted by system. </li>
3642 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003643 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003644 */
Roshan Pius189d0092021-03-11 21:16:44 -08003645 // Note: Some existing fields which are location sensitive may still be included without
3646 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003647 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3648
3649 /** @hide */
3650 @Retention(RetentionPolicy.SOURCE)
3651 @IntDef(flag = true, prefix = "FLAG_", value = {
3652 FLAG_NONE,
3653 FLAG_INCLUDE_LOCATION_INFO
3654 })
3655 public @interface Flag { }
3656
3657 /**
3658 * All the valid flags for error checking.
3659 */
3660 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3661
3662 public NetworkCallback() {
3663 this(FLAG_NONE);
3664 }
3665
3666 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003667 if ((flags & VALID_FLAGS) != flags) {
3668 throw new IllegalArgumentException("Invalid flags");
3669 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003670 mFlags = flags;
3671 }
3672
3673 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003674 * Called when the framework connects to a new network to evaluate whether it satisfies this
3675 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3676 * callback. There is no guarantee that this new network will satisfy any requests, or that
3677 * the network will stay connected for longer than the time necessary to evaluate it.
3678 * <p>
3679 * Most applications <b>should not</b> act on this callback, and should instead use
3680 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3681 * the framework in properly evaluating the network &mdash; for example, an application that
3682 * can automatically log in to a captive portal without user intervention.
3683 *
3684 * @param network The {@link Network} of the network that is being evaluated.
3685 *
3686 * @hide
3687 */
3688 public void onPreCheck(@NonNull Network network) {}
3689
3690 /**
3691 * Called when the framework connects and has declared a new network ready for use.
3692 * This callback may be called more than once if the {@link Network} that is
3693 * satisfying the request changes.
3694 *
3695 * @param network The {@link Network} of the satisfying network.
3696 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3697 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3698 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3699 * @hide
3700 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003701 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003702 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003703 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003704 // Internally only this method is called when a new network is available, and
3705 // it calls the callback in the same way and order that older versions used
3706 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003707 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3708 onBlockedStatusChanged(network, blocked);
3709 }
3710
3711 /**
3712 * Legacy variant of onAvailable that takes a boolean blocked reason.
3713 *
3714 * This method has never been public API, but it's not final, so there may be apps that
3715 * implemented it and rely on it being called. Do our best not to break them.
3716 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3717 * this method is called. There does not seem to be a way to avoid this.
3718 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3719 *
3720 * @hide
3721 */
3722 public void onAvailable(@NonNull Network network,
3723 @NonNull NetworkCapabilities networkCapabilities,
3724 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003725 onAvailable(network);
3726 if (!networkCapabilities.hasCapability(
3727 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3728 onNetworkSuspended(network);
3729 }
3730 onCapabilitiesChanged(network, networkCapabilities);
3731 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003732 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003733 }
3734
3735 /**
3736 * Called when the framework connects and has declared a new network ready for use.
3737 *
3738 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3739 * be available at the same time, and onAvailable will be called for each of these as they
3740 * appear.
3741 *
3742 * <p>For callbacks registered with {@link #requestNetwork} and
3743 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3744 * is the new best network for this request and is now tracked by this callback ; this
3745 * callback will no longer receive method calls about other networks that may have been
3746 * passed to this method previously. The previously-best network may have disconnected, or
3747 * it may still be around and the newly-best network may simply be better.
3748 *
3749 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3750 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3751 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3752 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3753 *
3754 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3755 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3756 * this callback as this is prone to race conditions (there is no guarantee the objects
3757 * returned by these methods will be current). Instead, wait for a call to
3758 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3759 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3760 * to be well-ordered with respect to other callbacks.
3761 *
3762 * @param network The {@link Network} of the satisfying network.
3763 */
3764 public void onAvailable(@NonNull Network network) {}
3765
3766 /**
3767 * Called when the network is about to be lost, typically because there are no outstanding
3768 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3769 * with the new replacement network for graceful handover. This method is not guaranteed
3770 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3771 * network is suddenly disconnected.
3772 *
3773 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3774 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3775 * this callback as this is prone to race conditions ; calling these methods while in a
3776 * callback may return an outdated or even a null object.
3777 *
3778 * @param network The {@link Network} that is about to be lost.
3779 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3780 * connected for graceful handover; note that the network may still
3781 * suffer a hard loss at any time.
3782 */
3783 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3784
3785 /**
3786 * Called when a network disconnects or otherwise no longer satisfies this request or
3787 * callback.
3788 *
3789 * <p>If the callback was registered with requestNetwork() or
3790 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3791 * returned by onAvailable() when that network is lost and no other network satisfies
3792 * the criteria of the request.
3793 *
3794 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3795 * each network which no longer satisfies the criteria of the callback.
3796 *
3797 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3798 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3799 * this callback as this is prone to race conditions ; calling these methods while in a
3800 * callback may return an outdated or even a null object.
3801 *
3802 * @param network The {@link Network} lost.
3803 */
3804 public void onLost(@NonNull Network network) {}
3805
3806 /**
3807 * Called if no network is found within the timeout time specified in
3808 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3809 * requested network request cannot be fulfilled (whether or not a timeout was
3810 * specified). When this callback is invoked the associated
3811 * {@link NetworkRequest} will have already been removed and released, as if
3812 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3813 */
3814 public void onUnavailable() {}
3815
3816 /**
3817 * Called when the network corresponding to this request changes capabilities but still
3818 * satisfies the requested criteria.
3819 *
3820 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3821 * to be called immediately after {@link #onAvailable}.
3822 *
3823 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3824 * ConnectivityManager methods in this callback as this is prone to race conditions :
3825 * calling these methods while in a callback may return an outdated or even a null object.
3826 *
3827 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003828 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003829 * network.
3830 */
3831 public void onCapabilitiesChanged(@NonNull Network network,
3832 @NonNull NetworkCapabilities networkCapabilities) {}
3833
3834 /**
3835 * Called when the network corresponding to this request changes {@link LinkProperties}.
3836 *
3837 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3838 * to be called immediately after {@link #onAvailable}.
3839 *
3840 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3841 * ConnectivityManager methods in this callback as this is prone to race conditions :
3842 * calling these methods while in a callback may return an outdated or even a null object.
3843 *
3844 * @param network The {@link Network} whose link properties have changed.
3845 * @param linkProperties The new {@link LinkProperties} for this network.
3846 */
3847 public void onLinkPropertiesChanged(@NonNull Network network,
3848 @NonNull LinkProperties linkProperties) {}
3849
3850 /**
3851 * Called when the network the framework connected to for this request suspends data
3852 * transmission temporarily.
3853 *
3854 * <p>This generally means that while the TCP connections are still live temporarily
3855 * network data fails to transfer. To give a specific example, this is used on cellular
3856 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3857 * means read operations on sockets on this network will block once the buffers are
3858 * drained, and write operations will block once the buffers are full.
3859 *
3860 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3861 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3862 * this callback as this is prone to race conditions (there is no guarantee the objects
3863 * returned by these methods will be current).
3864 *
3865 * @hide
3866 */
3867 public void onNetworkSuspended(@NonNull Network network) {}
3868
3869 /**
3870 * Called when the network the framework connected to for this request
3871 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3872 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3873
3874 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3875 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3876 * this callback as this is prone to race conditions : calling these methods while in a
3877 * callback may return an outdated or even a null object.
3878 *
3879 * @hide
3880 */
3881 public void onNetworkResumed(@NonNull Network network) {}
3882
3883 /**
3884 * Called when access to the specified network is blocked or unblocked.
3885 *
3886 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3887 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3888 * this callback as this is prone to race conditions : calling these methods while in a
3889 * callback may return an outdated or even a null object.
3890 *
3891 * @param network The {@link Network} whose blocked status has changed.
3892 * @param blocked The blocked status of this {@link Network}.
3893 */
3894 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3895
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003896 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09003897 * Called when access to the specified network is blocked or unblocked, or the reason for
3898 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003899 *
3900 * If a NetworkCallback object implements this method,
3901 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3902 *
3903 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3904 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3905 * this callback as this is prone to race conditions : calling these methods while in a
3906 * callback may return an outdated or even a null object.
3907 *
3908 * @param network The {@link Network} whose blocked status has changed.
3909 * @param blocked The blocked status of this {@link Network}.
3910 * @hide
3911 */
3912 @SystemApi(client = MODULE_LIBRARIES)
3913 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3914 onBlockedStatusChanged(network, blocked != 0);
3915 }
3916
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003917 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08003918 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003919 }
3920
3921 /**
3922 * Constant error codes used by ConnectivityService to communicate about failures and errors
3923 * across a Binder boundary.
3924 * @hide
3925 */
3926 public interface Errors {
3927 int TOO_MANY_REQUESTS = 1;
3928 }
3929
3930 /** @hide */
3931 public static class TooManyRequestsException extends RuntimeException {}
3932
3933 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3934 switch (e.errorCode) {
3935 case Errors.TOO_MANY_REQUESTS:
3936 return new TooManyRequestsException();
3937 default:
3938 Log.w(TAG, "Unknown service error code " + e.errorCode);
3939 return new RuntimeException(e);
3940 }
3941 }
3942
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003943 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003944 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003945 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003946 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003947 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003948 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003949 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003950 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003951 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003952 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003953 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003954 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003955 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003956 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003957 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003958 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003959 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003960 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003961 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003962 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003963 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003964 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003965
3966 /** @hide */
3967 public static String getCallbackName(int whichCallback) {
3968 switch (whichCallback) {
3969 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3970 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3971 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3972 case CALLBACK_LOST: return "CALLBACK_LOST";
3973 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3974 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3975 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
3976 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3977 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3978 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
3979 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
3980 default:
3981 return Integer.toString(whichCallback);
3982 }
3983 }
3984
3985 private class CallbackHandler extends Handler {
3986 private static final String TAG = "ConnectivityManager.CallbackHandler";
3987 private static final boolean DBG = false;
3988
3989 CallbackHandler(Looper looper) {
3990 super(looper);
3991 }
3992
3993 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003994 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003995 }
3996
3997 @Override
3998 public void handleMessage(Message message) {
3999 if (message.what == EXPIRE_LEGACY_REQUEST) {
4000 expireRequest((NetworkCapabilities) message.obj, message.arg1);
4001 return;
4002 }
4003
4004 final NetworkRequest request = getObject(message, NetworkRequest.class);
4005 final Network network = getObject(message, Network.class);
4006 final NetworkCallback callback;
4007 synchronized (sCallbacks) {
4008 callback = sCallbacks.get(request);
4009 if (callback == null) {
4010 Log.w(TAG,
4011 "callback not found for " + getCallbackName(message.what) + " message");
4012 return;
4013 }
4014 if (message.what == CALLBACK_UNAVAIL) {
4015 sCallbacks.remove(request);
4016 callback.networkRequest = ALREADY_UNREGISTERED;
4017 }
4018 }
4019 if (DBG) {
4020 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4021 }
4022
4023 switch (message.what) {
4024 case CALLBACK_PRECHECK: {
4025 callback.onPreCheck(network);
4026 break;
4027 }
4028 case CALLBACK_AVAILABLE: {
4029 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4030 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004031 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004032 break;
4033 }
4034 case CALLBACK_LOSING: {
4035 callback.onLosing(network, message.arg1);
4036 break;
4037 }
4038 case CALLBACK_LOST: {
4039 callback.onLost(network);
4040 break;
4041 }
4042 case CALLBACK_UNAVAIL: {
4043 callback.onUnavailable();
4044 break;
4045 }
4046 case CALLBACK_CAP_CHANGED: {
4047 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4048 callback.onCapabilitiesChanged(network, cap);
4049 break;
4050 }
4051 case CALLBACK_IP_CHANGED: {
4052 LinkProperties lp = getObject(message, LinkProperties.class);
4053 callback.onLinkPropertiesChanged(network, lp);
4054 break;
4055 }
4056 case CALLBACK_SUSPENDED: {
4057 callback.onNetworkSuspended(network);
4058 break;
4059 }
4060 case CALLBACK_RESUMED: {
4061 callback.onNetworkResumed(network);
4062 break;
4063 }
4064 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004065 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004066 }
4067 }
4068 }
4069
4070 private <T> T getObject(Message msg, Class<T> c) {
4071 return (T) msg.getData().getParcelable(c.getSimpleName());
4072 }
4073 }
4074
4075 private CallbackHandler getDefaultHandler() {
4076 synchronized (sCallbacks) {
4077 if (sCallbackHandler == null) {
4078 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4079 }
4080 return sCallbackHandler;
4081 }
4082 }
4083
4084 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4085 private static CallbackHandler sCallbackHandler;
4086
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004087 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4088 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4089 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004090 printStackTrace();
4091 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004092 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4093 throw new IllegalArgumentException("null NetworkCapabilities");
4094 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004095 final NetworkRequest request;
4096 final String callingPackageName = mContext.getOpPackageName();
4097 try {
4098 synchronized(sCallbacks) {
4099 if (callback.networkRequest != null
4100 && callback.networkRequest != ALREADY_UNREGISTERED) {
4101 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4102 // and requests (http://b/20701525).
4103 Log.e(TAG, "NetworkCallback was already registered");
4104 }
4105 Messenger messenger = new Messenger(handler);
4106 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004107 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004108 if (reqType == LISTEN) {
4109 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004110 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004111 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004112 } else {
4113 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004114 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4115 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004116 }
4117 if (request != null) {
4118 sCallbacks.put(request, callback);
4119 }
4120 callback.networkRequest = request;
4121 }
4122 } catch (RemoteException e) {
4123 throw e.rethrowFromSystemServer();
4124 } catch (ServiceSpecificException e) {
4125 throw convertServiceException(e);
4126 }
4127 return request;
4128 }
4129
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004130 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4131 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4132 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4133 legacyType, handler);
4134 }
4135
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004136 /**
4137 * Helper function to request a network with a particular legacy type.
4138 *
4139 * This API is only for use in internal system code that requests networks with legacy type and
4140 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4141 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4142 *
4143 * @param request {@link NetworkRequest} describing this request.
4144 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4145 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4146 * be a positive value (i.e. >0).
4147 * @param legacyType to specify the network type(#TYPE_*).
4148 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4149 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4150 * the callback must not be shared - it uniquely specifies this request.
4151 *
4152 * @hide
4153 */
4154 @SystemApi
4155 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4156 public void requestNetwork(@NonNull NetworkRequest request,
4157 int timeoutMs, int legacyType, @NonNull Handler handler,
4158 @NonNull NetworkCallback networkCallback) {
4159 if (legacyType == TYPE_NONE) {
4160 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4161 }
4162 CallbackHandler cbHandler = new CallbackHandler(handler);
4163 NetworkCapabilities nc = request.networkCapabilities;
4164 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4165 }
4166
4167 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004168 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004169 *
4170 * <p>This method will attempt to find the best network that matches the passed
4171 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4172 * criteria. The platform will evaluate which network is the best at its own discretion.
4173 * Throughput, latency, cost per byte, policy, user preference and other considerations
4174 * may be factored in the decision of what is considered the best network.
4175 *
4176 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4177 * matching this request, while always attempting to match the request to a better network if
4178 * possible. If a better match is found, the platform will switch this request to the now-best
4179 * network and inform the app of the newly best network by invoking
4180 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4181 * will not try to maintain any other network than the best one currently matching the request:
4182 * a network not matching any network request may be disconnected at any time.
4183 *
4184 * <p>For example, an application could use this method to obtain a connected cellular network
4185 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4186 * radio to consume additional power. Or, an application could inform the system that it wants
4187 * a network supporting sending MMSes and have the system let it know about the currently best
4188 * MMS-supporting network through the provided {@link NetworkCallback}.
4189 *
4190 * <p>The status of the request can be followed by listening to the various callbacks described
4191 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4192 * used to direct traffic to the network (although accessing some networks may be subject to
4193 * holding specific permissions). Callers will learn about the specific characteristics of the
4194 * network through
4195 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4196 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4197 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4198 * matching the request at any given time; therefore when a better network matching the request
4199 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4200 * with the new network after which no further updates are given about the previously-best
4201 * network, unless it becomes the best again at some later time. All callbacks are invoked
4202 * in order on the same thread, which by default is a thread created by the framework running
4203 * in the app.
4204 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4205 * callbacks are invoked.
4206 *
4207 * <p>This{@link NetworkRequest} will live until released via
4208 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4209 * which point the system may let go of the network at any time.
4210 *
4211 * <p>A version of this method which takes a timeout is
4212 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4213 * wait for a limited amount of time for the network to become unavailable.
4214 *
4215 * <p>It is presently unsupported to request a network with mutable
4216 * {@link NetworkCapabilities} such as
4217 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4218 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4219 * as these {@code NetworkCapabilities} represent states that a particular
4220 * network may never attain, and whether a network will attain these states
4221 * is unknown prior to bringing up the network so the framework does not
4222 * know how to go about satisfying a request with these capabilities.
4223 *
4224 * <p>This method requires the caller to hold either the
4225 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4226 * or the ability to modify system settings as determined by
4227 * {@link android.provider.Settings.System#canWrite}.</p>
4228 *
4229 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4230 * number of outstanding requests to 100 per app (identified by their UID), shared with
4231 * all variants of this method, of {@link #registerNetworkCallback} as well as
4232 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4233 * Requesting a network with this method will count toward this limit. If this limit is
4234 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4235 * make sure to unregister the callbacks with
4236 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4237 *
4238 * @param request {@link NetworkRequest} describing this request.
4239 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4240 * the callback must not be shared - it uniquely specifies this request.
4241 * The callback is invoked on the default internal Handler.
4242 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4243 * @throws SecurityException if missing the appropriate permissions.
4244 * @throws RuntimeException if the app already has too many callbacks registered.
4245 */
4246 public void requestNetwork(@NonNull NetworkRequest request,
4247 @NonNull NetworkCallback networkCallback) {
4248 requestNetwork(request, networkCallback, getDefaultHandler());
4249 }
4250
4251 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004252 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004253 *
4254 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4255 * but runs all the callbacks on the passed Handler.
4256 *
4257 * <p>This method has the same permission requirements as
4258 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4259 * and throws the same exceptions in the same conditions.
4260 *
4261 * @param request {@link NetworkRequest} describing this request.
4262 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4263 * the callback must not be shared - it uniquely specifies this request.
4264 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4265 */
4266 public void requestNetwork(@NonNull NetworkRequest request,
4267 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4268 CallbackHandler cbHandler = new CallbackHandler(handler);
4269 NetworkCapabilities nc = request.networkCapabilities;
4270 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4271 }
4272
4273 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004274 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004275 * by a timeout.
4276 *
4277 * This function behaves identically to the non-timed-out version
4278 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4279 * is not found within the given time (in milliseconds) the
4280 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4281 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4282 * not have to be released if timed-out (it is automatically released). Unregistering a
4283 * request that timed out is not an error.
4284 *
4285 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4286 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4287 * for that purpose. Calling this method will attempt to bring up the requested network.
4288 *
4289 * <p>This method has the same permission requirements as
4290 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4291 * and throws the same exceptions in the same conditions.
4292 *
4293 * @param request {@link NetworkRequest} describing this request.
4294 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4295 * the callback must not be shared - it uniquely specifies this request.
4296 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4297 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4298 * be a positive value (i.e. >0).
4299 */
4300 public void requestNetwork(@NonNull NetworkRequest request,
4301 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4302 checkTimeout(timeoutMs);
4303 NetworkCapabilities nc = request.networkCapabilities;
4304 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4305 getDefaultHandler());
4306 }
4307
4308 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004309 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004310 * by a timeout.
4311 *
4312 * This method behaves identically to
4313 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4314 * on the passed Handler.
4315 *
4316 * <p>This method has the same permission requirements as
4317 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4318 * and throws the same exceptions in the same conditions.
4319 *
4320 * @param request {@link NetworkRequest} describing this request.
4321 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4322 * the callback must not be shared - it uniquely specifies this request.
4323 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4324 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4325 * before {@link NetworkCallback#onUnavailable} is called.
4326 */
4327 public void requestNetwork(@NonNull NetworkRequest request,
4328 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4329 checkTimeout(timeoutMs);
4330 CallbackHandler cbHandler = new CallbackHandler(handler);
4331 NetworkCapabilities nc = request.networkCapabilities;
4332 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4333 }
4334
4335 /**
4336 * The lookup key for a {@link Network} object included with the intent after
4337 * successfully finding a network for the applications request. Retrieve it with
4338 * {@link android.content.Intent#getParcelableExtra(String)}.
4339 * <p>
4340 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4341 * then you must get a ConnectivityManager instance before doing so.
4342 */
4343 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4344
4345 /**
4346 * The lookup key for a {@link NetworkRequest} object included with the intent after
4347 * successfully finding a network for the applications request. Retrieve it with
4348 * {@link android.content.Intent#getParcelableExtra(String)}.
4349 */
4350 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4351
4352
4353 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004354 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004355 *
4356 * This function behaves identically to the version that takes a NetworkCallback, but instead
4357 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4358 * the request may outlive the calling application and get called back when a suitable
4359 * network is found.
4360 * <p>
4361 * The operation is an Intent broadcast that goes to a broadcast receiver that
4362 * you registered with {@link Context#registerReceiver} or through the
4363 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4364 * <p>
4365 * The operation Intent is delivered with two extras, a {@link Network} typed
4366 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4367 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4368 * the original requests parameters. It is important to create a new,
4369 * {@link NetworkCallback} based request before completing the processing of the
4370 * Intent to reserve the network or it will be released shortly after the Intent
4371 * is processed.
4372 * <p>
4373 * If there is already a request for this Intent registered (with the equality of
4374 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4375 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4376 * <p>
4377 * The request may be released normally by calling
4378 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4379 * <p>It is presently unsupported to request a network with either
4380 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4381 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4382 * as these {@code NetworkCapabilities} represent states that a particular
4383 * network may never attain, and whether a network will attain these states
4384 * is unknown prior to bringing up the network so the framework does not
4385 * know how to go about satisfying a request with these capabilities.
4386 *
4387 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4388 * number of outstanding requests to 100 per app (identified by their UID), shared with
4389 * all variants of this method, of {@link #registerNetworkCallback} as well as
4390 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4391 * Requesting a network with this method will count toward this limit. If this limit is
4392 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4393 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4394 * or {@link #releaseNetworkRequest(PendingIntent)}.
4395 *
4396 * <p>This method requires the caller to hold either the
4397 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4398 * or the ability to modify system settings as determined by
4399 * {@link android.provider.Settings.System#canWrite}.</p>
4400 *
4401 * @param request {@link NetworkRequest} describing this request.
4402 * @param operation Action to perform when the network is available (corresponds
4403 * to the {@link NetworkCallback#onAvailable} call. Typically
4404 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4405 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4406 * @throws SecurityException if missing the appropriate permissions.
4407 * @throws RuntimeException if the app already has too many callbacks registered.
4408 */
4409 public void requestNetwork(@NonNull NetworkRequest request,
4410 @NonNull PendingIntent operation) {
4411 printStackTrace();
4412 checkPendingIntentNotNull(operation);
4413 try {
4414 mService.pendingRequestForNetwork(
4415 request.networkCapabilities, operation, mContext.getOpPackageName(),
4416 getAttributionTag());
4417 } catch (RemoteException e) {
4418 throw e.rethrowFromSystemServer();
4419 } catch (ServiceSpecificException e) {
4420 throw convertServiceException(e);
4421 }
4422 }
4423
4424 /**
4425 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4426 * <p>
4427 * This method has the same behavior as
4428 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4429 * releasing network resources and disconnecting.
4430 *
4431 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4432 * PendingIntent passed to
4433 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4434 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4435 */
4436 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4437 printStackTrace();
4438 checkPendingIntentNotNull(operation);
4439 try {
4440 mService.releasePendingNetworkRequest(operation);
4441 } catch (RemoteException e) {
4442 throw e.rethrowFromSystemServer();
4443 }
4444 }
4445
4446 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004447 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004448 }
4449
4450 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004451 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004452 }
4453
4454 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004455 if (timeoutMs <= 0) {
4456 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4457 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004458 }
4459
4460 /**
4461 * Registers to receive notifications about all networks which satisfy the given
4462 * {@link NetworkRequest}. The callbacks will continue to be called until
4463 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4464 * called.
4465 *
4466 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4467 * number of outstanding requests to 100 per app (identified by their UID), shared with
4468 * all variants of this method, of {@link #requestNetwork} as well as
4469 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4470 * Requesting a network with this method will count toward this limit. If this limit is
4471 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4472 * make sure to unregister the callbacks with
4473 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4474 *
4475 * @param request {@link NetworkRequest} describing this request.
4476 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4477 * networks change state.
4478 * The callback is invoked on the default internal Handler.
4479 * @throws RuntimeException if the app already has too many callbacks registered.
4480 */
4481 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4482 public void registerNetworkCallback(@NonNull NetworkRequest request,
4483 @NonNull NetworkCallback networkCallback) {
4484 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4485 }
4486
4487 /**
4488 * Registers to receive notifications about all networks which satisfy the given
4489 * {@link NetworkRequest}. The callbacks will continue to be called until
4490 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4491 * called.
4492 *
4493 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4494 * number of outstanding requests to 100 per app (identified by their UID), shared with
4495 * all variants of this method, of {@link #requestNetwork} as well as
4496 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4497 * Requesting a network with this method will count toward this limit. If this limit is
4498 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4499 * make sure to unregister the callbacks with
4500 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4501 *
4502 *
4503 * @param request {@link NetworkRequest} describing this request.
4504 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4505 * networks change state.
4506 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4507 * @throws RuntimeException if the app already has too many callbacks registered.
4508 */
4509 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4510 public void registerNetworkCallback(@NonNull NetworkRequest request,
4511 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4512 CallbackHandler cbHandler = new CallbackHandler(handler);
4513 NetworkCapabilities nc = request.networkCapabilities;
4514 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4515 }
4516
4517 /**
4518 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4519 * {@link NetworkRequest}.
4520 *
4521 * This function behaves identically to the version that takes a NetworkCallback, but instead
4522 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4523 * the request may outlive the calling application and get called back when a suitable
4524 * network is found.
4525 * <p>
4526 * The operation is an Intent broadcast that goes to a broadcast receiver that
4527 * you registered with {@link Context#registerReceiver} or through the
4528 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4529 * <p>
4530 * The operation Intent is delivered with two extras, a {@link Network} typed
4531 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4532 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4533 * the original requests parameters.
4534 * <p>
4535 * If there is already a request for this Intent registered (with the equality of
4536 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4537 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4538 * <p>
4539 * The request may be released normally by calling
4540 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
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 {@link #unregisterNetworkCallback(PendingIntent)}
4549 * or {@link #releaseNetworkRequest(PendingIntent)}.
4550 *
4551 * @param request {@link NetworkRequest} describing this request.
4552 * @param operation Action to perform when the network is available (corresponds
4553 * to the {@link NetworkCallback#onAvailable} call. Typically
4554 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4555 * @throws RuntimeException if the app already has too many callbacks registered.
4556 */
4557 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4558 public void registerNetworkCallback(@NonNull NetworkRequest request,
4559 @NonNull PendingIntent operation) {
4560 printStackTrace();
4561 checkPendingIntentNotNull(operation);
4562 try {
4563 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004564 request.networkCapabilities, operation, mContext.getOpPackageName(),
4565 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004566 } catch (RemoteException e) {
4567 throw e.rethrowFromSystemServer();
4568 } catch (ServiceSpecificException e) {
4569 throw convertServiceException(e);
4570 }
4571 }
4572
4573 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004574 * Registers to receive notifications about changes in the application's default network. This
4575 * may be a physical network or a virtual network, such as a VPN that applies to the
4576 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004577 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4578 *
4579 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4580 * number of outstanding requests to 100 per app (identified by their UID), shared with
4581 * all variants of this method, of {@link #requestNetwork} as well as
4582 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4583 * Requesting a network with this method will count toward this limit. If this limit is
4584 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4585 * make sure to unregister the callbacks with
4586 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4587 *
4588 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004589 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004590 * The callback is invoked on the default internal Handler.
4591 * @throws RuntimeException if the app already has too many callbacks registered.
4592 */
4593 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4594 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4595 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4596 }
4597
4598 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004599 * Registers to receive notifications about changes in the application's default network. This
4600 * may be a physical network or a virtual network, such as a VPN that applies to the
4601 * application. The callbacks will continue to be called until either the application exits or
4602 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4603 *
4604 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4605 * number of outstanding requests to 100 per app (identified by their UID), shared with
4606 * all variants of this method, of {@link #requestNetwork} as well as
4607 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4608 * Requesting a network with this method will count toward this limit. If this limit is
4609 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4610 * make sure to unregister the callbacks with
4611 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4612 *
4613 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4614 * application's default network changes.
4615 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4616 * @throws RuntimeException if the app already has too many callbacks registered.
4617 */
4618 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4619 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4620 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004621 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004622 }
4623
4624 /**
4625 * Registers to receive notifications about changes in the default network for the specified
4626 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4627 * UID. The callbacks will continue to be called until either the application exits or
4628 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4629 *
4630 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4631 * number of outstanding requests to 100 per app (identified by their UID), shared with
4632 * all variants of this method, of {@link #requestNetwork} as well as
4633 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4634 * Requesting a network with this method will count toward this limit. If this limit is
4635 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4636 * make sure to unregister the callbacks with
4637 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4638 *
4639 * @param uid the UID for which to track default network changes.
4640 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4641 * UID's default network changes.
4642 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4643 * @throws RuntimeException if the app already has too many callbacks registered.
4644 * @hide
4645 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004646 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004647 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4648 @RequiresPermission(anyOf = {
4649 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4650 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004651 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004652 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004653 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004654 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004655 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4656 }
4657
4658 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004659 * Registers to receive notifications about changes in the system default network. The callbacks
4660 * will continue to be called until either the application exits or
4661 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4662 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004663 * This method should not be used to determine networking state seen by applications, because in
4664 * many cases, most or even all application traffic may not use the default network directly,
4665 * and traffic from different applications may go on different networks by default. As an
4666 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4667 * and not onto the system default network. Applications or system components desiring to do
4668 * determine network state as seen by applications should use other methods such as
4669 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4670 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004671 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4672 * number of outstanding requests to 100 per app (identified by their UID), shared with
4673 * all variants of this method, of {@link #requestNetwork} as well as
4674 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4675 * Requesting a network with this method will count toward this limit. If this limit is
4676 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4677 * make sure to unregister the callbacks with
4678 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4679 *
4680 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4681 * system default network changes.
4682 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4683 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004684 *
4685 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004686 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004687 @SystemApi(client = MODULE_LIBRARIES)
4688 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4689 @RequiresPermission(anyOf = {
4690 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4691 android.Manifest.permission.NETWORK_SETTINGS})
4692 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004693 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004694 CallbackHandler cbHandler = new CallbackHandler(handler);
4695 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004696 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004697 }
4698
4699 /**
junyulaibd123062021-03-15 11:48:48 +08004700 * Registers to receive notifications about the best matching network which satisfy the given
4701 * {@link NetworkRequest}. The callbacks will continue to be called until
4702 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4703 * called.
4704 *
4705 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4706 * number of outstanding requests to 100 per app (identified by their UID), shared with
4707 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4708 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4709 * Requesting a network with this method will count toward this limit. If this limit is
4710 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4711 * make sure to unregister the callbacks with
4712 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4713 *
4714 *
4715 * @param request {@link NetworkRequest} describing this request.
4716 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4717 * networks change state.
4718 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4719 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004720 */
junyulai5a5c99b2021-03-05 15:51:17 +08004721 @SuppressLint("ExecutorRegistration")
4722 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4723 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4724 final NetworkCapabilities nc = request.networkCapabilities;
4725 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004726 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004727 }
4728
4729 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004730 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4731 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4732 * network connection for updated bandwidth information. The caller will be notified via
4733 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4734 * method assumes that the caller has previously called
4735 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4736 * changes.
4737 *
4738 * @param network {@link Network} specifying which network you're interested.
4739 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4740 */
4741 public boolean requestBandwidthUpdate(@NonNull Network network) {
4742 try {
4743 return mService.requestBandwidthUpdate(network);
4744 } catch (RemoteException e) {
4745 throw e.rethrowFromSystemServer();
4746 }
4747 }
4748
4749 /**
4750 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4751 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4752 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4753 * If the given {@code NetworkCallback} had previously been used with
4754 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4755 * will be disconnected.
4756 *
4757 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4758 * triggering it as soon as this call returns.
4759 *
4760 * @param networkCallback The {@link NetworkCallback} used when making the request.
4761 */
4762 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4763 printStackTrace();
4764 checkCallbackNotNull(networkCallback);
4765 final List<NetworkRequest> reqs = new ArrayList<>();
4766 // Find all requests associated to this callback and stop callback triggers immediately.
4767 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4768 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004769 if (networkCallback.networkRequest == null) {
4770 throw new IllegalArgumentException("NetworkCallback was not registered");
4771 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004772 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4773 Log.d(TAG, "NetworkCallback was already unregistered");
4774 return;
4775 }
4776 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4777 if (e.getValue() == networkCallback) {
4778 reqs.add(e.getKey());
4779 }
4780 }
4781 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4782 for (NetworkRequest r : reqs) {
4783 try {
4784 mService.releaseNetworkRequest(r);
4785 } catch (RemoteException e) {
4786 throw e.rethrowFromSystemServer();
4787 }
4788 // Only remove mapping if rpc was successful.
4789 sCallbacks.remove(r);
4790 }
4791 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4792 }
4793 }
4794
4795 /**
4796 * Unregisters a callback previously registered via
4797 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4798 *
4799 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4800 * PendingIntent passed to
4801 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4802 * Cannot be null.
4803 */
4804 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4805 releaseNetworkRequest(operation);
4806 }
4807
4808 /**
4809 * Informs the system whether it should switch to {@code network} regardless of whether it is
4810 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4811 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4812 * the system default network regardless of any other network that's currently connected. If
4813 * {@code always} is true, then the choice is remembered, so that the next time the user
4814 * connects to this network, the system will switch to it.
4815 *
4816 * @param network The network to accept.
4817 * @param accept Whether to accept the network even if unvalidated.
4818 * @param always Whether to remember this choice in the future.
4819 *
4820 * @hide
4821 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004822 @SystemApi(client = MODULE_LIBRARIES)
4823 @RequiresPermission(anyOf = {
4824 android.Manifest.permission.NETWORK_SETTINGS,
4825 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4826 android.Manifest.permission.NETWORK_STACK,
4827 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4828 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004829 try {
4830 mService.setAcceptUnvalidated(network, accept, always);
4831 } catch (RemoteException e) {
4832 throw e.rethrowFromSystemServer();
4833 }
4834 }
4835
4836 /**
4837 * Informs the system whether it should consider the network as validated even if it only has
4838 * partial connectivity. If {@code accept} is true, then the network will be considered as
4839 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4840 * is remembered, so that the next time the user connects to this network, the system will
4841 * switch to it.
4842 *
4843 * @param network The network to accept.
4844 * @param accept Whether to consider the network as validated even if it has partial
4845 * connectivity.
4846 * @param always Whether to remember this choice in the future.
4847 *
4848 * @hide
4849 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004850 @SystemApi(client = MODULE_LIBRARIES)
4851 @RequiresPermission(anyOf = {
4852 android.Manifest.permission.NETWORK_SETTINGS,
4853 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4854 android.Manifest.permission.NETWORK_STACK,
4855 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4856 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4857 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004858 try {
4859 mService.setAcceptPartialConnectivity(network, accept, always);
4860 } catch (RemoteException e) {
4861 throw e.rethrowFromSystemServer();
4862 }
4863 }
4864
4865 /**
4866 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4867 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4868 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4869 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4870 *
4871 * @param network The network to accept.
4872 *
4873 * @hide
4874 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004875 @SystemApi(client = MODULE_LIBRARIES)
4876 @RequiresPermission(anyOf = {
4877 android.Manifest.permission.NETWORK_SETTINGS,
4878 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4879 android.Manifest.permission.NETWORK_STACK,
4880 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4881 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004882 try {
4883 mService.setAvoidUnvalidated(network);
4884 } catch (RemoteException e) {
4885 throw e.rethrowFromSystemServer();
4886 }
4887 }
4888
4889 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004890 * Temporarily allow bad wifi to override {@code config_networkAvoidBadWifi} configuration.
4891 *
4892 * @param timeMs The expired current time. The value should be set within a limited time from
4893 * now.
4894 *
4895 * @hide
4896 */
4897 public void setTestAllowBadWifiUntil(long timeMs) {
4898 try {
4899 mService.setTestAllowBadWifiUntil(timeMs);
4900 } catch (RemoteException e) {
4901 throw e.rethrowFromSystemServer();
4902 }
4903 }
4904
4905 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004906 * Requests that the system open the captive portal app on the specified network.
4907 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004908 * <p>This is to be used on networks where a captive portal was detected, as per
4909 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4910 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004911 * @param network The network to log into.
4912 *
4913 * @hide
4914 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004915 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4916 @RequiresPermission(anyOf = {
4917 android.Manifest.permission.NETWORK_SETTINGS,
4918 android.Manifest.permission.NETWORK_STACK,
4919 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4920 })
4921 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004922 try {
4923 mService.startCaptivePortalApp(network);
4924 } catch (RemoteException e) {
4925 throw e.rethrowFromSystemServer();
4926 }
4927 }
4928
4929 /**
4930 * Requests that the system open the captive portal app with the specified extras.
4931 *
4932 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4933 * corresponding permission.
4934 * @param network Network on which the captive portal was detected.
4935 * @param appExtras Extras to include in the app start intent.
4936 * @hide
4937 */
4938 @SystemApi
4939 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4940 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4941 try {
4942 mService.startCaptivePortalAppInternal(network, appExtras);
4943 } catch (RemoteException e) {
4944 throw e.rethrowFromSystemServer();
4945 }
4946 }
4947
4948 /**
4949 * Determine whether the device is configured to avoid bad wifi.
4950 * @hide
4951 */
4952 @SystemApi
4953 @RequiresPermission(anyOf = {
4954 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4955 android.Manifest.permission.NETWORK_STACK})
4956 public boolean shouldAvoidBadWifi() {
4957 try {
4958 return mService.shouldAvoidBadWifi();
4959 } catch (RemoteException e) {
4960 throw e.rethrowFromSystemServer();
4961 }
4962 }
4963
4964 /**
4965 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4966 * time-sensitive user-facing operations when the system default network is temporarily
4967 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4968 * this method), and the operation should be infrequent to ensure that data usage is limited.
4969 *
4970 * An example of such an operation might be a time-sensitive foreground activity, such as a
4971 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4972 */
4973 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4974
4975 /**
4976 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4977 * a backup channel for traffic that is primarily going over another network.
4978 *
4979 * An example might be maintaining backup connections to peers or servers for the purpose of
4980 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4981 * on backup paths should be negligible compared to the traffic on the main path.
4982 */
4983 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4984
4985 /**
4986 * It is acceptable to use metered data to improve network latency and performance.
4987 */
4988 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4989
4990 /**
4991 * Return value to use for unmetered networks. On such networks we currently set all the flags
4992 * to true.
4993 * @hide
4994 */
4995 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4996 MULTIPATH_PREFERENCE_HANDOVER |
4997 MULTIPATH_PREFERENCE_RELIABILITY |
4998 MULTIPATH_PREFERENCE_PERFORMANCE;
4999
Aaron Huangcff22942021-05-27 16:31:26 +08005000 /** @hide */
5001 @Retention(RetentionPolicy.SOURCE)
5002 @IntDef(flag = true, value = {
5003 MULTIPATH_PREFERENCE_HANDOVER,
5004 MULTIPATH_PREFERENCE_RELIABILITY,
5005 MULTIPATH_PREFERENCE_PERFORMANCE,
5006 })
5007 public @interface MultipathPreference {
5008 }
5009
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005010 /**
5011 * Provides a hint to the calling application on whether it is desirable to use the
5012 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5013 * for multipath data transfer on this network when it is not the system default network.
5014 * Applications desiring to use multipath network protocols should call this method before
5015 * each such operation.
5016 *
5017 * @param network The network on which the application desires to use multipath data.
5018 * If {@code null}, this method will return the a preference that will generally
5019 * apply to metered networks.
5020 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
5021 */
5022 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5023 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5024 try {
5025 return mService.getMultipathPreference(network);
5026 } catch (RemoteException e) {
5027 throw e.rethrowFromSystemServer();
5028 }
5029 }
5030
5031 /**
5032 * Resets all connectivity manager settings back to factory defaults.
5033 * @hide
5034 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005035 @SystemApi(client = MODULE_LIBRARIES)
5036 @RequiresPermission(anyOf = {
5037 android.Manifest.permission.NETWORK_SETTINGS,
5038 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005039 public void factoryReset() {
5040 try {
5041 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005042 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005043 } catch (RemoteException e) {
5044 throw e.rethrowFromSystemServer();
5045 }
5046 }
5047
5048 /**
5049 * Binds the current process to {@code network}. All Sockets created in the future
5050 * (and not explicitly bound via a bound SocketFactory from
5051 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5052 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5053 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5054 * work and all host name resolutions will fail. This is by design so an application doesn't
5055 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5056 * To clear binding pass {@code null} for {@code network}. Using individually bound
5057 * Sockets created by Network.getSocketFactory().createSocket() and
5058 * performing network-specific host name resolutions via
5059 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5060 * {@code bindProcessToNetwork}.
5061 *
5062 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5063 * the current binding.
5064 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5065 */
5066 public boolean bindProcessToNetwork(@Nullable Network network) {
5067 // Forcing callers to call through non-static function ensures ConnectivityManager
5068 // instantiated.
5069 return setProcessDefaultNetwork(network);
5070 }
5071
5072 /**
5073 * Binds the current process to {@code network}. All Sockets created in the future
5074 * (and not explicitly bound via a bound SocketFactory from
5075 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5076 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5077 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5078 * work and all host name resolutions will fail. This is by design so an application doesn't
5079 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5080 * To clear binding pass {@code null} for {@code network}. Using individually bound
5081 * Sockets created by Network.getSocketFactory().createSocket() and
5082 * performing network-specific host name resolutions via
5083 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5084 * {@code setProcessDefaultNetwork}.
5085 *
5086 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5087 * the current binding.
5088 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5089 * @deprecated This function can throw {@link IllegalStateException}. Use
5090 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5091 * is a direct replacement.
5092 */
5093 @Deprecated
5094 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5095 int netId = (network == null) ? NETID_UNSET : network.netId;
5096 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5097
5098 if (netId != NETID_UNSET) {
5099 netId = network.getNetIdForResolv();
5100 }
5101
5102 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5103 return false;
5104 }
5105
5106 if (!isSameNetId) {
5107 // Set HTTP proxy system properties to match network.
5108 // TODO: Deprecate this static method and replace it with a non-static version.
5109 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005110 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005111 } catch (SecurityException e) {
5112 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5113 Log.e(TAG, "Can't set proxy properties", e);
5114 }
5115 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005116 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005117 // Must flush socket pool as idle sockets will be bound to previous network and may
5118 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005119 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005120 }
5121
5122 return true;
5123 }
5124
5125 /**
5126 * Returns the {@link Network} currently bound to this process via
5127 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5128 *
5129 * @return {@code Network} to which this process is bound, or {@code null}.
5130 */
5131 @Nullable
5132 public Network getBoundNetworkForProcess() {
5133 // Forcing callers to call thru non-static function ensures ConnectivityManager
5134 // instantiated.
5135 return getProcessDefaultNetwork();
5136 }
5137
5138 /**
5139 * Returns the {@link Network} currently bound to this process via
5140 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5141 *
5142 * @return {@code Network} to which this process is bound, or {@code null}.
5143 * @deprecated Using this function can lead to other functions throwing
5144 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5145 * {@code getBoundNetworkForProcess} is a direct replacement.
5146 */
5147 @Deprecated
5148 @Nullable
5149 public static Network getProcessDefaultNetwork() {
5150 int netId = NetworkUtils.getBoundNetworkForProcess();
5151 if (netId == NETID_UNSET) return null;
5152 return new Network(netId);
5153 }
5154
5155 private void unsupportedStartingFrom(int version) {
5156 if (Process.myUid() == Process.SYSTEM_UID) {
5157 // The getApplicationInfo() call we make below is not supported in system context. Let
5158 // the call through here, and rely on the fact that ConnectivityService will refuse to
5159 // allow the system to use these APIs anyway.
5160 return;
5161 }
5162
5163 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5164 throw new UnsupportedOperationException(
5165 "This method is not supported in target SDK version " + version + " and above");
5166 }
5167 }
5168
5169 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5170 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5171 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5172 // remove these exemptions. Note that this check is not secure, and apps can still access these
5173 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5174 // so is unsupported and may break in the future. http://b/22728205
5175 private void checkLegacyRoutingApiAccess() {
5176 unsupportedStartingFrom(VERSION_CODES.M);
5177 }
5178
5179 /**
5180 * Binds host resolutions performed by this process to {@code network}.
5181 * {@link #bindProcessToNetwork} takes precedence over this setting.
5182 *
5183 * @param network The {@link Network} to bind host resolutions from the current process to, or
5184 * {@code null} to clear the current binding.
5185 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5186 * @hide
5187 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5188 */
5189 @Deprecated
5190 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5191 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5192 return NetworkUtils.bindProcessToNetworkForHostResolution(
5193 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5194 }
5195
5196 /**
5197 * Device is not restricting metered network activity while application is running on
5198 * background.
5199 */
5200 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5201
5202 /**
5203 * Device is restricting metered network activity while application is running on background,
5204 * but application is allowed to bypass it.
5205 * <p>
5206 * In this state, application should take action to mitigate metered network access.
5207 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5208 */
5209 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5210
5211 /**
5212 * Device is restricting metered network activity while application is running on background.
5213 * <p>
5214 * In this state, application should not try to use the network while running on background,
5215 * because it would be denied.
5216 */
5217 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5218
5219 /**
5220 * A change in the background metered network activity restriction has occurred.
5221 * <p>
5222 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5223 * applies to them.
5224 * <p>
5225 * This is only sent to registered receivers, not manifest receivers.
5226 */
5227 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5228 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5229 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5230
Aaron Huangcff22942021-05-27 16:31:26 +08005231 /** @hide */
5232 @Retention(RetentionPolicy.SOURCE)
5233 @IntDef(flag = false, value = {
5234 RESTRICT_BACKGROUND_STATUS_DISABLED,
5235 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5236 RESTRICT_BACKGROUND_STATUS_ENABLED,
5237 })
5238 public @interface RestrictBackgroundStatus {
5239 }
5240
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005241 /**
5242 * Determines if the calling application is subject to metered network restrictions while
5243 * running on background.
5244 *
5245 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5246 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5247 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5248 */
5249 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5250 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005251 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005252 } catch (RemoteException e) {
5253 throw e.rethrowFromSystemServer();
5254 }
5255 }
5256
5257 /**
5258 * The network watchlist is a list of domains and IP addresses that are associated with
5259 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5260 * currently used by the system for validation purposes.
5261 *
5262 * @return Hash of network watchlist config file. Null if config does not exist.
5263 */
5264 @Nullable
5265 public byte[] getNetworkWatchlistConfigHash() {
5266 try {
5267 return mService.getNetworkWatchlistConfigHash();
5268 } catch (RemoteException e) {
5269 Log.e(TAG, "Unable to get watchlist config hash");
5270 throw e.rethrowFromSystemServer();
5271 }
5272 }
5273
5274 /**
5275 * Returns the {@code uid} of the owner of a network connection.
5276 *
5277 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5278 * IPPROTO_UDP} currently supported.
5279 * @param local The local {@link InetSocketAddress} of a connection.
5280 * @param remote The remote {@link InetSocketAddress} of a connection.
5281 * @return {@code uid} if the connection is found and the app has permission to observe it
5282 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5283 * android.os.Process#INVALID_UID} if the connection is not found.
5284 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5285 * user.
5286 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5287 */
5288 public int getConnectionOwnerUid(
5289 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5290 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5291 try {
5292 return mService.getConnectionOwnerUid(connectionInfo);
5293 } catch (RemoteException e) {
5294 throw e.rethrowFromSystemServer();
5295 }
5296 }
5297
5298 private void printStackTrace() {
5299 if (DEBUG) {
5300 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5301 final StringBuffer sb = new StringBuffer();
5302 for (int i = 3; i < callStack.length; i++) {
5303 final String stackTrace = callStack[i].toString();
5304 if (stackTrace == null || stackTrace.contains("android.os")) {
5305 break;
5306 }
5307 sb.append(" [").append(stackTrace).append("]");
5308 }
5309 Log.d(TAG, "StackLog:" + sb.toString());
5310 }
5311 }
5312
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005313 /** @hide */
5314 public TestNetworkManager startOrGetTestNetworkManager() {
5315 final IBinder tnBinder;
5316 try {
5317 tnBinder = mService.startOrGetTestNetworkService();
5318 } catch (RemoteException e) {
5319 throw e.rethrowFromSystemServer();
5320 }
5321
5322 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5323 }
5324
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005325 /** @hide */
5326 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5327 return new ConnectivityDiagnosticsManager(mContext, mService);
5328 }
5329
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005330 /**
5331 * Simulates a Data Stall for the specified Network.
5332 *
5333 * <p>This method should only be used for tests.
5334 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005335 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5336 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005337 *
5338 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005339 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5340 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5341 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005342 * @param network The Network for which a Data Stall is being simluated.
5343 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5344 * @throws SecurityException if the caller is not the owner of the given network.
5345 * @hide
5346 */
5347 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5348 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5349 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005350 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005351 @NonNull Network network, @NonNull PersistableBundle extras) {
5352 try {
5353 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5354 } catch (RemoteException e) {
5355 e.rethrowFromSystemServer();
5356 }
5357 }
5358
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005359 @NonNull
5360 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5361
5362 /**
5363 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5364 * receive available QoS events related to the {@link Network} and local ip + port
5365 * specified within socketInfo.
5366 * <p/>
5367 * The same {@link QosCallback} must be unregistered before being registered a second time,
5368 * otherwise {@link QosCallbackRegistrationException} is thrown.
5369 * <p/>
5370 * This API does not, in itself, require any permission if called with a network that is not
5371 * restricted. However, the underlying implementation currently only supports the IMS network,
5372 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5373 * useful, because they'd never be called back on networks that they would have access to.
5374 *
5375 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5376 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5377 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5378 * @throws RuntimeException if the app already has too many callbacks registered.
5379 *
5380 * Exceptions after the time of registration is passed through
5381 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5382 *
5383 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005384 * @param executor The executor on which the callback will be invoked. The provided
5385 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005386 * callbacks cannot be guaranteed.onQosCallbackRegistered
5387 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005388 *
5389 * @hide
5390 */
5391 @SystemApi
5392 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005393 @CallbackExecutor @NonNull final Executor executor,
5394 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005395 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005396 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005397 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005398
5399 try {
5400 synchronized (mQosCallbackConnections) {
5401 if (getQosCallbackConnection(callback) == null) {
5402 final QosCallbackConnection connection =
5403 new QosCallbackConnection(this, callback, executor);
5404 mQosCallbackConnections.add(connection);
5405 mService.registerQosSocketCallback(socketInfo, connection);
5406 } else {
5407 Log.e(TAG, "registerQosCallback: Callback already registered");
5408 throw new QosCallbackRegistrationException();
5409 }
5410 }
5411 } catch (final RemoteException e) {
5412 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5413
5414 // The same unregister method method is called for consistency even though nothing
5415 // will be sent to the ConnectivityService since the callback was never successfully
5416 // registered.
5417 unregisterQosCallback(callback);
5418 e.rethrowFromSystemServer();
5419 } catch (final ServiceSpecificException e) {
5420 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5421 unregisterQosCallback(callback);
5422 throw convertServiceException(e);
5423 }
5424 }
5425
5426 /**
5427 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5428 * events once unregistered and can be registered a second time.
5429 * <p/>
5430 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5431 *
5432 * @param callback the callback being unregistered
5433 *
5434 * @hide
5435 */
5436 @SystemApi
5437 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5438 Objects.requireNonNull(callback, "The callback must be non-null");
5439 try {
5440 synchronized (mQosCallbackConnections) {
5441 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5442 if (connection != null) {
5443 connection.stopReceivingMessages();
5444 mService.unregisterQosCallback(connection);
5445 mQosCallbackConnections.remove(connection);
5446 } else {
5447 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5448 }
5449 }
5450 } catch (final RemoteException e) {
5451 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5452 e.rethrowFromSystemServer();
5453 }
5454 }
5455
5456 /**
5457 * Gets the connection related to the callback.
5458 *
5459 * @param callback the callback to look up
5460 * @return the related connection
5461 */
5462 @Nullable
5463 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5464 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5465 // Checking by reference here is intentional
5466 if (connection.getCallback() == callback) {
5467 return connection;
5468 }
5469 }
5470 return null;
5471 }
5472
5473 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005474 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005475 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5476 * be used to request that the system provide a network without causing the network to be
5477 * in the foreground.
5478 *
5479 * <p>This method will attempt to find the best network that matches the passed
5480 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5481 * criteria. The platform will evaluate which network is the best at its own discretion.
5482 * Throughput, latency, cost per byte, policy, user preference and other considerations
5483 * may be factored in the decision of what is considered the best network.
5484 *
5485 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5486 * matching this request, while always attempting to match the request to a better network if
5487 * possible. If a better match is found, the platform will switch this request to the now-best
5488 * network and inform the app of the newly best network by invoking
5489 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5490 * will not try to maintain any other network than the best one currently matching the request:
5491 * a network not matching any network request may be disconnected at any time.
5492 *
5493 * <p>For example, an application could use this method to obtain a connected cellular network
5494 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5495 * radio to consume additional power. Or, an application could inform the system that it wants
5496 * a network supporting sending MMSes and have the system let it know about the currently best
5497 * MMS-supporting network through the provided {@link NetworkCallback}.
5498 *
5499 * <p>The status of the request can be followed by listening to the various callbacks described
5500 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5501 * used to direct traffic to the network (although accessing some networks may be subject to
5502 * holding specific permissions). Callers will learn about the specific characteristics of the
5503 * network through
5504 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5505 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5506 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5507 * matching the request at any given time; therefore when a better network matching the request
5508 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5509 * with the new network after which no further updates are given about the previously-best
5510 * network, unless it becomes the best again at some later time. All callbacks are invoked
5511 * in order on the same thread, which by default is a thread created by the framework running
5512 * in the app.
5513 *
5514 * <p>This{@link NetworkRequest} will live until released via
5515 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5516 * which point the system may let go of the network at any time.
5517 *
5518 * <p>It is presently unsupported to request a network with mutable
5519 * {@link NetworkCapabilities} such as
5520 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5521 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5522 * as these {@code NetworkCapabilities} represent states that a particular
5523 * network may never attain, and whether a network will attain these states
5524 * is unknown prior to bringing up the network so the framework does not
5525 * know how to go about satisfying a request with these capabilities.
5526 *
5527 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5528 * number of outstanding requests to 100 per app (identified by their UID), shared with
5529 * all variants of this method, of {@link #registerNetworkCallback} as well as
5530 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5531 * Requesting a network with this method will count toward this limit. If this limit is
5532 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5533 * make sure to unregister the callbacks with
5534 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5535 *
5536 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005537 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5538 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005539 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5540 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005541 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5542 * @throws SecurityException if missing the appropriate permissions.
5543 * @throws RuntimeException if the app already has too many callbacks registered.
5544 *
5545 * @hide
5546 */
5547 @SystemApi(client = MODULE_LIBRARIES)
5548 @SuppressLint("ExecutorRegistration")
5549 @RequiresPermission(anyOf = {
5550 android.Manifest.permission.NETWORK_SETTINGS,
5551 android.Manifest.permission.NETWORK_STACK,
5552 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5553 })
5554 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005555 @NonNull NetworkCallback networkCallback,
5556 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005557 final NetworkCapabilities nc = request.networkCapabilities;
5558 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005559 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005560 }
James Mattis12aeab82021-01-10 14:24:24 -08005561
5562 /**
James Mattis12aeab82021-01-10 14:24:24 -08005563 * Used by automotive devices to set the network preferences used to direct traffic at an
5564 * application level as per the given OemNetworkPreferences. An example use-case would be an
5565 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5566 * vehicle via a particular network.
5567 *
5568 * Calling this will overwrite the existing preference.
5569 *
5570 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5571 * @param executor the executor on which listener will be invoked.
5572 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5573 * communicate completion of setOemNetworkPreference(). This will only be
5574 * called once upon successful completion of setOemNetworkPreference().
5575 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5576 * @throws SecurityException if missing the appropriate permissions.
5577 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005578 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005579 */
James Mattis6e2d7022021-01-26 16:23:52 -08005580 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005581 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005582 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005583 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005584 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005585 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5586 if (null != listener) {
5587 Objects.requireNonNull(executor, "Executor must be non-null");
5588 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005589 final IOnCompleteListener listenerInternal = listener == null ? null :
5590 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005591 @Override
5592 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005593 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005594 }
5595 };
5596
5597 try {
5598 mService.setOemNetworkPreference(preference, listenerInternal);
5599 } catch (RemoteException e) {
5600 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5601 throw e.rethrowFromSystemServer();
5602 }
5603 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005604
Chalard Jeanad565e22021-02-25 17:23:40 +09005605 /**
5606 * Request that a user profile is put by default on a network matching a given preference.
5607 *
5608 * See the documentation for the individual preferences for a description of the supported
5609 * behaviors.
5610 *
5611 * @param profile the profile concerned.
5612 * @param preference the preference for this profile.
5613 * @param executor an executor to execute the listener on. Optional if listener is null.
5614 * @param listener an optional listener to listen for completion of the operation.
5615 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5616 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005617 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5618 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005619 * @hide
5620 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005621 // This function is for establishing per-profile default networking and can only be called by
5622 // the device policy manager, running as the system server. It would make no sense to call it
5623 // on a context for a user because it does not establish a setting on behalf of a user, rather
5624 // it establishes a setting for a user on behalf of the DPM.
5625 @SuppressLint({"UserHandle"})
5626 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005627 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005628 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005629 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005630 @ProfileNetworkPreferencePolicy final int preference,
5631 @Nullable @CallbackExecutor final Executor executor,
5632 @Nullable final Runnable listener) {
5633
5634 ProfileNetworkPreference.Builder preferenceBuilder =
5635 new ProfileNetworkPreference.Builder();
5636 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005637 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5638 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5639 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005640 setProfileNetworkPreferences(profile,
5641 List.of(preferenceBuilder.build()), executor, listener);
5642 }
5643
5644 /**
5645 * Set a list of default network selection policies for a user profile.
5646 *
5647 * Calling this API with a user handle defines the entire policy for that user handle.
5648 * It will overwrite any setting previously set for the same user profile,
5649 * and not affect previously set settings for other handles.
5650 *
5651 * Call this API with an empty list to remove settings for this user profile.
5652 *
5653 * See {@link ProfileNetworkPreference} for more details on each preference
5654 * parameter.
5655 *
5656 * @param profile the user profile for which the preference is being set.
5657 * @param profileNetworkPreferences the list of profile network preferences for the
5658 * provided profile.
5659 * @param executor an executor to execute the listener on. Optional if listener is null.
5660 * @param listener an optional listener to listen for completion of the operation.
5661 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5662 * @throws SecurityException if missing the appropriate permissions.
5663 * @hide
5664 */
5665 @SystemApi(client = MODULE_LIBRARIES)
5666 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5667 public void setProfileNetworkPreferences(
5668 @NonNull final UserHandle profile,
5669 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005670 @Nullable @CallbackExecutor final Executor executor,
5671 @Nullable final Runnable listener) {
5672 if (null != listener) {
5673 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5674 }
5675 final IOnCompleteListener proxy;
5676 if (null == listener) {
5677 proxy = null;
5678 } else {
5679 proxy = new IOnCompleteListener.Stub() {
5680 @Override
5681 public void onComplete() {
5682 executor.execute(listener::run);
5683 }
5684 };
5685 }
5686 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005687 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005688 } catch (RemoteException e) {
5689 throw e.rethrowFromSystemServer();
5690 }
5691 }
5692
lucaslin5cdbcfb2021-03-12 00:46:33 +08005693 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005694 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005695 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005696 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005697
5698 /**
5699 * Get the network ID range reserved for IPSec tunnel interfaces.
5700 *
5701 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5702 * @hide
5703 */
5704 @SystemApi(client = MODULE_LIBRARIES)
5705 @NonNull
5706 public static Range<Integer> getIpSecNetIdRange() {
5707 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5708 }
markchien738ad912021-12-09 18:15:45 +08005709
5710 /**
markchiene46042b2022-03-02 18:07:35 +08005711 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5712 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005713 *
5714 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005715 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005716 * @hide
5717 */
5718 @SystemApi(client = MODULE_LIBRARIES)
5719 @RequiresPermission(anyOf = {
5720 android.Manifest.permission.NETWORK_SETTINGS,
5721 android.Manifest.permission.NETWORK_STACK,
5722 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5723 })
markchiene46042b2022-03-02 18:07:35 +08005724 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005725 try {
markchiene46042b2022-03-02 18:07:35 +08005726 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08005727 } catch (RemoteException e) {
5728 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005729 }
5730 }
5731
5732 /**
markchiene46042b2022-03-02 18:07:35 +08005733 * Removes the specified UID from the list of UIDs that are allowed to use background data on
5734 * metered networks when background data is restricted. The deny list takes precedence over
5735 * the allow list.
5736 *
5737 * @param uid uid of target app
5738 * @throws IllegalStateException if updating allow list failed.
5739 * @hide
5740 */
5741 @SystemApi(client = MODULE_LIBRARIES)
5742 @RequiresPermission(anyOf = {
5743 android.Manifest.permission.NETWORK_SETTINGS,
5744 android.Manifest.permission.NETWORK_STACK,
5745 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5746 })
5747 public void removeUidFromMeteredNetworkAllowList(final int uid) {
5748 try {
5749 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
5750 } catch (RemoteException e) {
5751 throw e.rethrowFromSystemServer();
5752 }
5753 }
5754
5755 /**
5756 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
5757 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08005758 *
5759 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005760 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08005761 * @hide
5762 */
5763 @SystemApi(client = MODULE_LIBRARIES)
5764 @RequiresPermission(anyOf = {
5765 android.Manifest.permission.NETWORK_SETTINGS,
5766 android.Manifest.permission.NETWORK_STACK,
5767 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5768 })
markchiene46042b2022-03-02 18:07:35 +08005769 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005770 try {
markchiene46042b2022-03-02 18:07:35 +08005771 mService.updateMeteredNetworkDenyList(uid, true /* add */);
5772 } catch (RemoteException e) {
5773 throw e.rethrowFromSystemServer();
5774 }
5775 }
5776
5777 /**
5778 * Removes the specified UID from the list of UIds that can use use background data on metered
5779 * networks if background data is not restricted. The deny list takes precedence over the
5780 * allow list.
5781 *
5782 * @param uid uid of target app
5783 * @throws IllegalStateException if updating deny list failed.
5784 * @hide
5785 */
5786 @SystemApi(client = MODULE_LIBRARIES)
5787 @RequiresPermission(anyOf = {
5788 android.Manifest.permission.NETWORK_SETTINGS,
5789 android.Manifest.permission.NETWORK_STACK,
5790 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5791 })
5792 public void removeUidFromMeteredNetworkDenyList(final int uid) {
5793 try {
5794 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08005795 } catch (RemoteException e) {
5796 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08005797 }
5798 }
5799
5800 /**
5801 * Sets a firewall rule for the specified UID on the specified chain.
5802 *
5803 * @param chain target chain.
5804 * @param uid uid to allow/deny.
markchien68cfadc2022-01-14 13:39:54 +08005805 * @param allow whether networking is allowed or denied.
5806 * @throws IllegalStateException if updating firewall rule failed.
markchiene1561fa2021-12-09 22:00:56 +08005807 * @hide
5808 */
5809 @SystemApi(client = MODULE_LIBRARIES)
5810 @RequiresPermission(anyOf = {
5811 android.Manifest.permission.NETWORK_SETTINGS,
5812 android.Manifest.permission.NETWORK_STACK,
5813 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5814 })
5815 public void updateFirewallRule(@FirewallChain final int chain, final int uid,
5816 final boolean allow) {
5817 try {
5818 mService.updateFirewallRule(chain, uid, allow);
5819 } catch (RemoteException e) {
5820 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005821 }
5822 }
markchien98a6f952022-01-13 23:43:53 +08005823
5824 /**
5825 * Enables or disables the specified firewall chain.
5826 *
5827 * @param chain target chain.
5828 * @param enable whether the chain should be enabled.
markchien68cfadc2022-01-14 13:39:54 +08005829 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08005830 * @hide
5831 */
5832 @SystemApi(client = MODULE_LIBRARIES)
5833 @RequiresPermission(anyOf = {
5834 android.Manifest.permission.NETWORK_SETTINGS,
5835 android.Manifest.permission.NETWORK_STACK,
5836 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5837 })
5838 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
5839 try {
5840 mService.setFirewallChainEnabled(chain, enable);
5841 } catch (RemoteException e) {
5842 throw e.rethrowFromSystemServer();
5843 }
5844 }
markchien00a0bed2022-01-13 23:46:13 +08005845
5846 /**
5847 * Replaces the contents of the specified UID-based firewall chain.
5848 *
5849 * @param chain target chain to replace.
5850 * @param uids The list of UIDs to be placed into chain.
markchien68cfadc2022-01-14 13:39:54 +08005851 * @throws IllegalStateException if replacing the firewall chain failed.
markchien00a0bed2022-01-13 23:46:13 +08005852 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
5853 * @hide
5854 */
5855 @SystemApi(client = MODULE_LIBRARIES)
5856 @RequiresPermission(anyOf = {
5857 android.Manifest.permission.NETWORK_SETTINGS,
5858 android.Manifest.permission.NETWORK_STACK,
5859 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5860 })
5861 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
5862 Objects.requireNonNull(uids);
5863 try {
5864 mService.replaceFirewallChain(chain, uids);
5865 } catch (RemoteException e) {
5866 throw e.rethrowFromSystemServer();
5867 }
5868 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005869}