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