blob: 4ecc8a127c3cc12623088db8b74b9fd3efd072e3 [file] [log] [blame]
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package android.net;
17
18import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080019import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
21import static android.net.NetworkRequest.Type.LISTEN;
junyulai7664f622021-03-12 20:05:08 +080022import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090023import static android.net.NetworkRequest.Type.REQUEST;
24import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colittia77d05e2021-01-29 20:14:04 +090025import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090026import static android.net.QosCallback.QosCallbackRegistrationException;
27
28import android.annotation.CallbackExecutor;
29import android.annotation.IntDef;
30import android.annotation.NonNull;
31import android.annotation.Nullable;
32import android.annotation.RequiresPermission;
33import android.annotation.SdkConstant;
34import android.annotation.SdkConstant.SdkConstantType;
35import android.annotation.SuppressLint;
36import android.annotation.SystemApi;
37import android.annotation.SystemService;
38import android.app.PendingIntent;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090039import android.app.admin.DevicePolicyManager;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090040import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090041import android.content.ComponentName;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090042import android.content.Context;
43import android.content.Intent;
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +090044import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090045import android.net.IpSecManager.UdpEncapsulationSocket;
46import android.net.SocketKeepalive.Callback;
47import android.net.TetheringManager.StartTetheringCallback;
48import android.net.TetheringManager.TetheringEventCallback;
49import android.net.TetheringManager.TetheringRequest;
50import android.os.Binder;
51import android.os.Build;
52import android.os.Build.VERSION_CODES;
53import android.os.Bundle;
54import android.os.Handler;
55import android.os.IBinder;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090056import android.os.Looper;
57import android.os.Message;
58import android.os.Messenger;
59import android.os.ParcelFileDescriptor;
60import android.os.PersistableBundle;
61import android.os.Process;
62import android.os.RemoteException;
63import android.os.ResultReceiver;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090064import android.os.ServiceSpecificException;
Chalard Jeanad565e22021-02-25 17:23:40 +090065import android.os.UserHandle;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090066import android.provider.Settings;
67import android.telephony.SubscriptionManager;
68import android.telephony.TelephonyManager;
69import android.util.ArrayMap;
70import android.util.Log;
71import android.util.Range;
72import android.util.SparseIntArray;
73
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090074import com.android.internal.annotations.GuardedBy;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090075
76import libcore.net.event.NetworkEventDispatcher;
77
78import java.io.IOException;
79import java.io.UncheckedIOException;
80import java.lang.annotation.Retention;
81import java.lang.annotation.RetentionPolicy;
82import java.net.DatagramSocket;
83import java.net.InetAddress;
84import java.net.InetSocketAddress;
85import java.net.Socket;
86import java.util.ArrayList;
87import java.util.Collection;
88import java.util.HashMap;
89import java.util.List;
90import java.util.Map;
91import java.util.Objects;
92import java.util.concurrent.Executor;
93import java.util.concurrent.ExecutorService;
94import java.util.concurrent.Executors;
95import java.util.concurrent.RejectedExecutionException;
96
97/**
98 * Class that answers queries about the state of network connectivity. It also
99 * notifies applications when network connectivity changes.
100 * <p>
101 * The primary responsibilities of this class are to:
102 * <ol>
103 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
104 * <li>Send broadcast intents when network connectivity changes</li>
105 * <li>Attempt to "fail over" to another network when connectivity to a network
106 * is lost</li>
107 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
108 * state of the available networks</li>
109 * <li>Provide an API that allows applications to request and select networks for their data
110 * traffic</li>
111 * </ol>
112 */
113@SystemService(Context.CONNECTIVITY_SERVICE)
114public class ConnectivityManager {
115 private static final String TAG = "ConnectivityManager";
116 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
117
118 /**
119 * A change in network connectivity has occurred. A default connection has either
120 * been established or lost. The NetworkInfo for the affected network is
121 * sent as an extra; it should be consulted to see what kind of
122 * connectivity event occurred.
123 * <p/>
124 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
125 * broadcast if they declare the broadcast receiver in their manifest. Apps
126 * will still receive broadcasts if they register their
127 * {@link android.content.BroadcastReceiver} with
128 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
129 * and that context is still valid.
130 * <p/>
131 * If this is a connection that was the result of failing over from a
132 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
133 * set to true.
134 * <p/>
135 * For a loss of connectivity, if the connectivity manager is attempting
136 * to connect (or has already connected) to another network, the
137 * NetworkInfo for the new network is also passed as an extra. This lets
138 * any receivers of the broadcast know that they should not necessarily
139 * tell the user that no data traffic will be possible. Instead, the
140 * receiver should expect another broadcast soon, indicating either that
141 * the failover attempt succeeded (and so there is still overall data
142 * connectivity), or that the failover attempt failed, meaning that all
143 * connectivity has been lost.
144 * <p/>
145 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
146 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900147 * <p />
148 * Note that this broadcast is deprecated and generally tries to implement backwards
149 * compatibility with older versions of Android. As such, it may not reflect new
150 * capabilities of the system, like multiple networks being connected at the same
151 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900152 *
153 * @deprecated apps should use the more versatile {@link #requestNetwork},
154 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
155 * functions instead for faster and more detailed updates about the network
156 * changes they care about.
157 */
158 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
159 @Deprecated
160 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
161
162 /**
163 * The device has connected to a network that has presented a captive
164 * portal, which is blocking Internet connectivity. The user was presented
165 * with a notification that network sign in is required,
166 * and the user invoked the notification's action indicating they
167 * desire to sign in to the network. Apps handling this activity should
168 * facilitate signing in to the network. This action includes a
169 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
170 * the network presenting the captive portal; all communication with the
171 * captive portal must be done using this {@code Network} object.
172 * <p/>
173 * This activity includes a {@link CaptivePortal} extra named
174 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
175 * outcomes of the captive portal sign in to the system:
176 * <ul>
177 * <li> When the app handling this action believes the user has signed in to
178 * the network and the captive portal has been dismissed, the app should
179 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
180 * reevaluate the network. If reevaluation finds the network no longer
181 * subject to a captive portal, the network may become the default active
182 * data network.</li>
183 * <li> When the app handling this action believes the user explicitly wants
184 * to ignore the captive portal and the network, the app should call
185 * {@link CaptivePortal#ignoreNetwork}. </li>
186 * </ul>
187 */
188 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
189 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
190
191 /**
192 * The lookup key for a {@link NetworkInfo} object. Retrieve with
193 * {@link android.content.Intent#getParcelableExtra(String)}.
194 *
195 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
196 * can't accurately represent modern network characteristics.
197 * Please obtain information about networks from the {@link NetworkCapabilities}
198 * or {@link LinkProperties} objects instead.
199 */
200 @Deprecated
201 public static final String EXTRA_NETWORK_INFO = "networkInfo";
202
203 /**
204 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
205 *
206 * @see android.content.Intent#getIntExtra(String, int)
207 * @deprecated The network type is not rich enough to represent the characteristics
208 * of modern networks. Please use {@link NetworkCapabilities} instead,
209 * in particular the transports.
210 */
211 @Deprecated
212 public static final String EXTRA_NETWORK_TYPE = "networkType";
213
214 /**
215 * The lookup key for a boolean that indicates whether a connect event
216 * is for a network to which the connectivity manager was failing over
217 * following a disconnect on another network.
218 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
219 *
220 * @deprecated See {@link NetworkInfo}.
221 */
222 @Deprecated
223 public static final String EXTRA_IS_FAILOVER = "isFailover";
224 /**
225 * The lookup key for a {@link NetworkInfo} object. This is supplied when
226 * there is another network that it may be possible to connect to. Retrieve with
227 * {@link android.content.Intent#getParcelableExtra(String)}.
228 *
229 * @deprecated See {@link NetworkInfo}.
230 */
231 @Deprecated
232 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
233 /**
234 * The lookup key for a boolean that indicates whether there is a
235 * complete lack of connectivity, i.e., no network is available.
236 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
237 */
238 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
239 /**
240 * The lookup key for a string that indicates why an attempt to connect
241 * to a network failed. The string has no particular structure. It is
242 * intended to be used in notifications presented to users. Retrieve
243 * it with {@link android.content.Intent#getStringExtra(String)}.
244 */
245 public static final String EXTRA_REASON = "reason";
246 /**
247 * The lookup key for a string that provides optionally supplied
248 * extra information about the network state. The information
249 * may be passed up from the lower networking layers, and its
250 * meaning may be specific to a particular network type. Retrieve
251 * it with {@link android.content.Intent#getStringExtra(String)}.
252 *
253 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
254 */
255 @Deprecated
256 public static final String EXTRA_EXTRA_INFO = "extraInfo";
257 /**
258 * The lookup key for an int that provides information about
259 * our connection to the internet at large. 0 indicates no connection,
260 * 100 indicates a great connection. Retrieve it with
261 * {@link android.content.Intent#getIntExtra(String, int)}.
262 * {@hide}
263 */
264 public static final String EXTRA_INET_CONDITION = "inetCondition";
265 /**
266 * The lookup key for a {@link CaptivePortal} object included with the
267 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
268 * object can be used to either indicate to the system that the captive
269 * portal has been dismissed or that the user does not want to pursue
270 * signing in to captive portal. Retrieve it with
271 * {@link android.content.Intent#getParcelableExtra(String)}.
272 */
273 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
274
275 /**
276 * Key for passing a URL to the captive portal login activity.
277 */
278 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
279
280 /**
281 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
282 * portal login activity.
283 * {@hide}
284 */
285 @SystemApi
286 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
287 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
288
289 /**
290 * Key for passing a user agent string to the captive portal login activity.
291 * {@hide}
292 */
293 @SystemApi
294 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
295 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
296
297 /**
298 * Broadcast action to indicate the change of data activity status
299 * (idle or active) on a network in a recent period.
300 * The network becomes active when data transmission is started, or
301 * idle if there is no data transmission for a period of time.
302 * {@hide}
303 */
304 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
305 public static final String ACTION_DATA_ACTIVITY_CHANGE =
306 "android.net.conn.DATA_ACTIVITY_CHANGE";
307 /**
308 * The lookup key for an enum that indicates the network device type on which this data activity
309 * change happens.
310 * {@hide}
311 */
312 public static final String EXTRA_DEVICE_TYPE = "deviceType";
313 /**
314 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
315 * it is actively sending or receiving data and {@code false} means it is idle.
316 * {@hide}
317 */
318 public static final String EXTRA_IS_ACTIVE = "isActive";
319 /**
320 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
321 * {@hide}
322 */
323 public static final String EXTRA_REALTIME_NS = "tsNanos";
324
325 /**
326 * Broadcast Action: The setting for background data usage has changed
327 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
328 * <p>
329 * If an application uses the network in the background, it should listen
330 * for this broadcast and stop using the background data if the value is
331 * {@code false}.
332 * <p>
333 *
334 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
335 * of background data depends on several combined factors, and
336 * this broadcast is no longer sent. Instead, when background
337 * data is unavailable, {@link #getActiveNetworkInfo()} will now
338 * appear disconnected. During first boot after a platform
339 * upgrade, this broadcast will be sent once if
340 * {@link #getBackgroundDataSetting()} was {@code false} before
341 * the upgrade.
342 */
343 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
344 @Deprecated
345 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
346 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
347
348 /**
349 * Broadcast Action: The network connection may not be good
350 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
351 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
352 * the network and it's condition.
353 * @hide
354 */
355 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
356 @UnsupportedAppUsage
357 public static final String INET_CONDITION_ACTION =
358 "android.net.conn.INET_CONDITION_ACTION";
359
360 /**
361 * Broadcast Action: A tetherable connection has come or gone.
362 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
363 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
364 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
365 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
366 * the current state of tethering. Each include a list of
367 * interface names in that state (may be empty).
368 * @hide
369 */
370 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
371 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
372 public static final String ACTION_TETHER_STATE_CHANGED =
373 TetheringManager.ACTION_TETHER_STATE_CHANGED;
374
375 /**
376 * @hide
377 * gives a String[] listing all the interfaces configured for
378 * tethering and currently available for tethering.
379 */
380 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
381 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
382
383 /**
384 * @hide
385 * gives a String[] listing all the interfaces currently in local-only
386 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
387 */
388 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
389
390 /**
391 * @hide
392 * gives a String[] listing all the interfaces currently tethered
393 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
394 */
395 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
396 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
397
398 /**
399 * @hide
400 * gives a String[] listing all the interfaces we tried to tether and
401 * failed. Use {@link #getLastTetherError} to find the error code
402 * for any interfaces listed here.
403 */
404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
405 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
406
407 /**
408 * Broadcast Action: The captive portal tracker has finished its test.
409 * Sent only while running Setup Wizard, in lieu of showing a user
410 * notification.
411 * @hide
412 */
413 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
414 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
415 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
416 /**
417 * The lookup key for a boolean that indicates whether a captive portal was detected.
418 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
419 * @hide
420 */
421 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
422
423 /**
424 * Action used to display a dialog that asks the user whether to connect to a network that is
425 * not validated. This intent is used to start the dialog in settings via startActivity.
426 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800427 * This action includes a {@link Network} typed extra which is called
428 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
429 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900430 * @hide
431 */
lucaslincf6d4502021-03-04 17:09:51 +0800432 @SystemApi(client = MODULE_LIBRARIES)
433 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900434
435 /**
436 * Action used to display a dialog that asks the user whether to avoid a network that is no
437 * longer validated. This intent is used to start the dialog in settings via startActivity.
438 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800439 * This action includes a {@link Network} typed extra which is called
440 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
441 * validated.
442 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900443 * @hide
444 */
lucaslincf6d4502021-03-04 17:09:51 +0800445 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900446 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800447 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900448
449 /**
450 * Action used to display a dialog that asks the user whether to stay connected to a network
451 * that has not validated. This intent is used to start the dialog in settings via
452 * startActivity.
453 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800454 * This action includes a {@link Network} typed extra which is called
455 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
456 * connectivity.
457 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900458 * @hide
459 */
lucaslincf6d4502021-03-04 17:09:51 +0800460 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900461 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800462 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900463
464 /**
paulhub49c8422021-04-07 16:18:13 +0800465 * Clear DNS Cache Action: This is broadcast when networks have changed and old
466 * DNS entries should be cleared.
467 * @hide
468 */
469 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
470 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
471 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
472
473 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900474 * Invalid tethering type.
475 * @see #startTethering(int, boolean, OnStartTetheringCallback)
476 * @hide
477 */
478 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
479
480 /**
481 * Wifi tethering type.
482 * @see #startTethering(int, boolean, OnStartTetheringCallback)
483 * @hide
484 */
485 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900486 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900487
488 /**
489 * USB tethering type.
490 * @see #startTethering(int, boolean, OnStartTetheringCallback)
491 * @hide
492 */
493 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900494 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900495
496 /**
497 * Bluetooth tethering type.
498 * @see #startTethering(int, boolean, OnStartTetheringCallback)
499 * @hide
500 */
501 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900502 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900503
504 /**
505 * Wifi P2p tethering type.
506 * Wifi P2p tethering is set through events automatically, and don't
507 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
508 * @hide
509 */
510 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
511
512 /**
513 * Extra used for communicating with the TetherService. Includes the type of tethering to
514 * enable if any.
515 * @hide
516 */
517 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
518
519 /**
520 * Extra used for communicating with the TetherService. Includes the type of tethering for
521 * which to cancel provisioning.
522 * @hide
523 */
524 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
525
526 /**
527 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
528 * provisioning.
529 * @hide
530 */
531 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
532
533 /**
534 * Tells the TetherService to run a provision check now.
535 * @hide
536 */
537 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
538
539 /**
540 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
541 * which will receive provisioning results. Can be left empty.
542 * @hide
543 */
544 public static final String EXTRA_PROVISION_CALLBACK =
545 TetheringConstants.EXTRA_PROVISION_CALLBACK;
546
547 /**
548 * The absence of a connection type.
549 * @hide
550 */
551 @SystemApi
552 public static final int TYPE_NONE = -1;
553
554 /**
555 * A Mobile data connection. Devices may support more than one.
556 *
557 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
558 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
559 * appropriate network. {@see NetworkCapabilities} for supported transports.
560 */
561 @Deprecated
562 public static final int TYPE_MOBILE = 0;
563
564 /**
565 * A WIFI data connection. Devices may support more than one.
566 *
567 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
568 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
569 * appropriate network. {@see NetworkCapabilities} for supported transports.
570 */
571 @Deprecated
572 public static final int TYPE_WIFI = 1;
573
574 /**
575 * An MMS-specific Mobile data connection. This network type may use the
576 * same network interface as {@link #TYPE_MOBILE} or it may use a different
577 * one. This is used by applications needing to talk to the carrier's
578 * Multimedia Messaging Service servers.
579 *
580 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
581 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
582 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
583 */
584 @Deprecated
585 public static final int TYPE_MOBILE_MMS = 2;
586
587 /**
588 * A SUPL-specific Mobile data connection. This network type may use the
589 * same network interface as {@link #TYPE_MOBILE} or it may use a different
590 * one. This is used by applications needing to talk to the carrier's
591 * Secure User Plane Location servers for help locating the device.
592 *
593 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
594 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
595 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
596 */
597 @Deprecated
598 public static final int TYPE_MOBILE_SUPL = 3;
599
600 /**
601 * A DUN-specific Mobile data connection. This network type may use the
602 * same network interface as {@link #TYPE_MOBILE} or it may use a different
603 * one. This is sometimes by the system when setting up an upstream connection
604 * for tethering so that the carrier is aware of DUN traffic.
605 *
606 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
607 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
608 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
609 */
610 @Deprecated
611 public static final int TYPE_MOBILE_DUN = 4;
612
613 /**
614 * A High Priority Mobile data connection. This network type uses the
615 * same network interface as {@link #TYPE_MOBILE} but the routing setup
616 * is different.
617 *
618 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
619 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
620 * appropriate network. {@see NetworkCapabilities} for supported transports.
621 */
622 @Deprecated
623 public static final int TYPE_MOBILE_HIPRI = 5;
624
625 /**
626 * A WiMAX data connection.
627 *
628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
630 * appropriate network. {@see NetworkCapabilities} for supported transports.
631 */
632 @Deprecated
633 public static final int TYPE_WIMAX = 6;
634
635 /**
636 * A Bluetooth data connection.
637 *
638 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
639 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
640 * appropriate network. {@see NetworkCapabilities} for supported transports.
641 */
642 @Deprecated
643 public static final int TYPE_BLUETOOTH = 7;
644
645 /**
646 * Fake data connection. This should not be used on shipping devices.
647 * @deprecated This is not used any more.
648 */
649 @Deprecated
650 public static final int TYPE_DUMMY = 8;
651
652 /**
653 * An Ethernet data connection.
654 *
655 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
656 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
657 * appropriate network. {@see NetworkCapabilities} for supported transports.
658 */
659 @Deprecated
660 public static final int TYPE_ETHERNET = 9;
661
662 /**
663 * Over the air Administration.
664 * @deprecated Use {@link NetworkCapabilities} instead.
665 * {@hide}
666 */
667 @Deprecated
668 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
669 public static final int TYPE_MOBILE_FOTA = 10;
670
671 /**
672 * IP Multimedia Subsystem.
673 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
674 * {@hide}
675 */
676 @Deprecated
677 @UnsupportedAppUsage
678 public static final int TYPE_MOBILE_IMS = 11;
679
680 /**
681 * Carrier Branded Services.
682 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
683 * {@hide}
684 */
685 @Deprecated
686 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
687 public static final int TYPE_MOBILE_CBS = 12;
688
689 /**
690 * A Wi-Fi p2p connection. Only requesting processes will have access to
691 * the peers connected.
692 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
693 * {@hide}
694 */
695 @Deprecated
696 @SystemApi
697 public static final int TYPE_WIFI_P2P = 13;
698
699 /**
700 * The network to use for initially attaching to the network
701 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
702 * {@hide}
703 */
704 @Deprecated
705 @UnsupportedAppUsage
706 public static final int TYPE_MOBILE_IA = 14;
707
708 /**
709 * Emergency PDN connection for emergency services. This
710 * may include IMS and MMS in emergency situations.
711 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
712 * {@hide}
713 */
714 @Deprecated
715 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
716 public static final int TYPE_MOBILE_EMERGENCY = 15;
717
718 /**
719 * The network that uses proxy to achieve connectivity.
720 * @deprecated Use {@link NetworkCapabilities} instead.
721 * {@hide}
722 */
723 @Deprecated
724 @SystemApi
725 public static final int TYPE_PROXY = 16;
726
727 /**
728 * A virtual network using one or more native bearers.
729 * It may or may not be providing security services.
730 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
731 */
732 @Deprecated
733 public static final int TYPE_VPN = 17;
734
735 /**
736 * A network that is exclusively meant to be used for testing
737 *
738 * @deprecated Use {@link NetworkCapabilities} instead.
739 * @hide
740 */
741 @Deprecated
742 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
743
744 /**
745 * @deprecated Use {@link NetworkCapabilities} instead.
746 * @hide
747 */
748 @Deprecated
749 @Retention(RetentionPolicy.SOURCE)
750 @IntDef(prefix = { "TYPE_" }, value = {
751 TYPE_NONE,
752 TYPE_MOBILE,
753 TYPE_WIFI,
754 TYPE_MOBILE_MMS,
755 TYPE_MOBILE_SUPL,
756 TYPE_MOBILE_DUN,
757 TYPE_MOBILE_HIPRI,
758 TYPE_WIMAX,
759 TYPE_BLUETOOTH,
760 TYPE_DUMMY,
761 TYPE_ETHERNET,
762 TYPE_MOBILE_FOTA,
763 TYPE_MOBILE_IMS,
764 TYPE_MOBILE_CBS,
765 TYPE_WIFI_P2P,
766 TYPE_MOBILE_IA,
767 TYPE_MOBILE_EMERGENCY,
768 TYPE_PROXY,
769 TYPE_VPN,
770 TYPE_TEST
771 })
772 public @interface LegacyNetworkType {}
773
774 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
775 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
776 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
777 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
778 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
779
780 /** {@hide} */
781 public static final int MAX_RADIO_TYPE = TYPE_TEST;
782
783 /** {@hide} */
784 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
785
786 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
787
788 /**
789 * If you want to set the default network preference,you can directly
790 * change the networkAttributes array in framework's config.xml.
791 *
792 * @deprecated Since we support so many more networks now, the single
793 * network default network preference can't really express
794 * the hierarchy. Instead, the default is defined by the
795 * networkAttributes in config.xml. You can determine
796 * the current value by calling {@link #getNetworkPreference()}
797 * from an App.
798 */
799 @Deprecated
800 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
801
802 /**
803 * @hide
804 */
805 public static final int REQUEST_ID_UNSET = 0;
806
807 /**
808 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
809 * This allows to distinguish when unregistering NetworkCallbacks those that were never
810 * registered from those that were already unregistered.
811 * @hide
812 */
813 private static final NetworkRequest ALREADY_UNREGISTERED =
814 new NetworkRequest.Builder().clearCapabilities().build();
815
816 /**
817 * A NetID indicating no Network is selected.
818 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
819 * @hide
820 */
821 public static final int NETID_UNSET = 0;
822
823 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000824 * Flag to indicate that an app is not subject to any restrictions that could result in its
825 * network access blocked.
826 *
827 * @hide
828 */
829 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
830 public static final int BLOCKED_REASON_NONE = 0;
831
832 /**
833 * Flag to indicate that an app is subject to Battery saver restrictions that would
834 * result in its network access being blocked.
835 *
836 * @hide
837 */
838 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
839 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
840
841 /**
842 * Flag to indicate that an app is subject to Doze restrictions that would
843 * result in its network access being blocked.
844 *
845 * @hide
846 */
847 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
848 public static final int BLOCKED_REASON_DOZE = 1 << 1;
849
850 /**
851 * Flag to indicate that an app is subject to App Standby restrictions that would
852 * result in its network access being blocked.
853 *
854 * @hide
855 */
856 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
857 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
858
859 /**
860 * Flag to indicate that an app is subject to Restricted mode restrictions that would
861 * result in its network access being blocked.
862 *
863 * @hide
864 */
865 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
866 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
867
868 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900869 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
870 * is not currently connected.
871 *
872 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
873 *
874 * @hide
875 */
876 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
877 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
878
879 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100880 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
881 * result in its network access being blocked.
882 *
883 * @hide
884 */
885 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
886 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
887
888 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000889 * Flag to indicate that an app is subject to Data saver restrictions that would
890 * result in its metered network access being blocked.
891 *
892 * @hide
893 */
894 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
895 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
896
897 /**
898 * Flag to indicate that an app is subject to user restrictions that would
899 * result in its metered network access being blocked.
900 *
901 * @hide
902 */
903 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
904 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
905
906 /**
907 * Flag to indicate that an app is subject to Device admin restrictions that would
908 * result in its metered network access being blocked.
909 *
910 * @hide
911 */
912 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
913 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
914
915 /**
916 * @hide
917 */
918 @Retention(RetentionPolicy.SOURCE)
919 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
920 BLOCKED_REASON_NONE,
921 BLOCKED_REASON_BATTERY_SAVER,
922 BLOCKED_REASON_DOZE,
923 BLOCKED_REASON_APP_STANDBY,
924 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900925 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100926 BLOCKED_REASON_LOW_POWER_STANDBY,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000927 BLOCKED_METERED_REASON_DATA_SAVER,
928 BLOCKED_METERED_REASON_USER_RESTRICTED,
929 BLOCKED_METERED_REASON_ADMIN_DISABLED,
930 })
931 public @interface BlockedReason {}
932
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900933 /**
934 * Set of blocked reasons that are only applicable on metered networks.
935 *
936 * @hide
937 */
938 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
939 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
940
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900941 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
942 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900943
Robert Horvathd945bf02022-01-27 19:55:16 +0100944 // LINT.IfChange(firewall_chain)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900945 /**
markchiene1561fa2021-12-09 22:00:56 +0800946 * Firewall chain for device idle (doze mode).
947 * Allowlist of apps that have network access in device idle.
948 * @hide
949 */
950 @SystemApi(client = MODULE_LIBRARIES)
951 public static final int FIREWALL_CHAIN_DOZABLE = 1;
952
953 /**
954 * Firewall chain used for app standby.
955 * Denylist of apps that do not have network access.
956 * @hide
957 */
958 @SystemApi(client = MODULE_LIBRARIES)
959 public static final int FIREWALL_CHAIN_STANDBY = 2;
960
961 /**
962 * Firewall chain used for battery saver.
963 * Allowlist of apps that have network access when battery saver is on.
964 * @hide
965 */
966 @SystemApi(client = MODULE_LIBRARIES)
967 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
968
969 /**
970 * Firewall chain used for restricted networking mode.
971 * Allowlist of apps that have access in restricted networking mode.
972 * @hide
973 */
974 @SystemApi(client = MODULE_LIBRARIES)
975 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
976
Robert Horvath34cba142022-01-27 19:52:43 +0100977 /**
978 * Firewall chain used for low power standby.
979 * Allowlist of apps that have access in low power standby.
980 * @hide
981 */
982 @SystemApi(client = MODULE_LIBRARIES)
983 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
984
Motomu Utsumi966ff7f2022-05-11 05:56:26 +0000985 /**
986 * Firewall chain used for lockdown VPN.
987 * Denylist of apps that cannot receive incoming packets except on loopback because they are
988 * subject to an always-on VPN which is not currently connected.
989 *
990 * @see #BLOCKED_REASON_LOCKDOWN_VPN
991 * @hide
992 */
993 public static final int FIREWALL_CHAIN_LOCKDOWN_VPN = 6;
994
markchiene1561fa2021-12-09 22:00:56 +0800995 /** @hide */
996 @Retention(RetentionPolicy.SOURCE)
997 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
998 FIREWALL_CHAIN_DOZABLE,
999 FIREWALL_CHAIN_STANDBY,
1000 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001001 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumi966ff7f2022-05-11 05:56:26 +00001002 FIREWALL_CHAIN_LOW_POWER_STANDBY,
1003 FIREWALL_CHAIN_LOCKDOWN_VPN
markchiene1561fa2021-12-09 22:00:56 +08001004 })
1005 public @interface FirewallChain {}
Robert Horvathd945bf02022-01-27 19:55:16 +01001006 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
markchiene1561fa2021-12-09 22:00:56 +08001007
1008 /**
markchien011a7f52022-03-29 01:07:22 +08001009 * A firewall rule which allows or drops packets depending on existing policy.
1010 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1011 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001012 * @hide
1013 */
1014 @SystemApi(client = MODULE_LIBRARIES)
1015 public static final int FIREWALL_RULE_DEFAULT = 0;
1016
1017 /**
markchien011a7f52022-03-29 01:07:22 +08001018 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1019 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001020 * @hide
1021 */
1022 @SystemApi(client = MODULE_LIBRARIES)
1023 public static final int FIREWALL_RULE_ALLOW = 1;
1024
1025 /**
markchien011a7f52022-03-29 01:07:22 +08001026 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1027 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001028 * @hide
1029 */
1030 @SystemApi(client = MODULE_LIBRARIES)
1031 public static final int FIREWALL_RULE_DENY = 2;
1032
1033 /** @hide */
1034 @Retention(RetentionPolicy.SOURCE)
1035 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1036 FIREWALL_RULE_DEFAULT,
1037 FIREWALL_RULE_ALLOW,
1038 FIREWALL_RULE_DENY
1039 })
1040 public @interface FirewallRule {}
1041
1042 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001043 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1044 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1045 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1046 * methods that take a Context argument.
1047 */
1048 private static ConnectivityManager sInstance;
1049
1050 private final Context mContext;
1051
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001052 @GuardedBy("mTetheringEventCallbacks")
1053 private TetheringManager mTetheringManager;
1054
1055 private TetheringManager getTetheringManager() {
1056 synchronized (mTetheringEventCallbacks) {
1057 if (mTetheringManager == null) {
1058 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1059 }
1060 return mTetheringManager;
1061 }
1062 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001063
1064 /**
1065 * Tests if a given integer represents a valid network type.
1066 * @param networkType the type to be tested
1067 * @return a boolean. {@code true} if the type is valid, else {@code false}
1068 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1069 * validate a network type.
1070 */
1071 @Deprecated
1072 public static boolean isNetworkTypeValid(int networkType) {
1073 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1074 }
1075
1076 /**
1077 * Returns a non-localized string representing a given network type.
1078 * ONLY used for debugging output.
1079 * @param type the type needing naming
1080 * @return a String for the given type, or a string version of the type ("87")
1081 * if no name is known.
1082 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1083 * {@hide}
1084 */
1085 @Deprecated
1086 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1087 public static String getNetworkTypeName(int type) {
1088 switch (type) {
1089 case TYPE_NONE:
1090 return "NONE";
1091 case TYPE_MOBILE:
1092 return "MOBILE";
1093 case TYPE_WIFI:
1094 return "WIFI";
1095 case TYPE_MOBILE_MMS:
1096 return "MOBILE_MMS";
1097 case TYPE_MOBILE_SUPL:
1098 return "MOBILE_SUPL";
1099 case TYPE_MOBILE_DUN:
1100 return "MOBILE_DUN";
1101 case TYPE_MOBILE_HIPRI:
1102 return "MOBILE_HIPRI";
1103 case TYPE_WIMAX:
1104 return "WIMAX";
1105 case TYPE_BLUETOOTH:
1106 return "BLUETOOTH";
1107 case TYPE_DUMMY:
1108 return "DUMMY";
1109 case TYPE_ETHERNET:
1110 return "ETHERNET";
1111 case TYPE_MOBILE_FOTA:
1112 return "MOBILE_FOTA";
1113 case TYPE_MOBILE_IMS:
1114 return "MOBILE_IMS";
1115 case TYPE_MOBILE_CBS:
1116 return "MOBILE_CBS";
1117 case TYPE_WIFI_P2P:
1118 return "WIFI_P2P";
1119 case TYPE_MOBILE_IA:
1120 return "MOBILE_IA";
1121 case TYPE_MOBILE_EMERGENCY:
1122 return "MOBILE_EMERGENCY";
1123 case TYPE_PROXY:
1124 return "PROXY";
1125 case TYPE_VPN:
1126 return "VPN";
1127 default:
1128 return Integer.toString(type);
1129 }
1130 }
1131
1132 /**
1133 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001134 */
lucaslin10774b72021-03-17 14:16:01 +08001135 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001136 public void systemReady() {
1137 try {
1138 mService.systemReady();
1139 } catch (RemoteException e) {
1140 throw e.rethrowFromSystemServer();
1141 }
1142 }
1143
1144 /**
1145 * Checks if a given type uses the cellular data connection.
1146 * This should be replaced in the future by a network property.
1147 * @param networkType the type to check
1148 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1149 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1150 * {@hide}
1151 */
1152 @Deprecated
1153 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1154 public static boolean isNetworkTypeMobile(int networkType) {
1155 switch (networkType) {
1156 case TYPE_MOBILE:
1157 case TYPE_MOBILE_MMS:
1158 case TYPE_MOBILE_SUPL:
1159 case TYPE_MOBILE_DUN:
1160 case TYPE_MOBILE_HIPRI:
1161 case TYPE_MOBILE_FOTA:
1162 case TYPE_MOBILE_IMS:
1163 case TYPE_MOBILE_CBS:
1164 case TYPE_MOBILE_IA:
1165 case TYPE_MOBILE_EMERGENCY:
1166 return true;
1167 default:
1168 return false;
1169 }
1170 }
1171
1172 /**
1173 * Checks if the given network type is backed by a Wi-Fi radio.
1174 *
1175 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1176 * @hide
1177 */
1178 @Deprecated
1179 public static boolean isNetworkTypeWifi(int networkType) {
1180 switch (networkType) {
1181 case TYPE_WIFI:
1182 case TYPE_WIFI_P2P:
1183 return true;
1184 default:
1185 return false;
1186 }
1187 }
1188
1189 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001190 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1191 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001192 * Specify that the traffic for this user should by follow the default rules.
1193 * @hide
1194 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001195 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001196 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1197
1198 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001199 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1200 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001201 * Specify that the traffic for this user should by default go on a network with
1202 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1203 * if no such network is available.
1204 * @hide
1205 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001206 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001207 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1208
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001209 /**
1210 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1211 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1212 * Specify that the traffic for this user should by default go on a network with
1213 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
1214 * should not go on the system default network
1215 * @hide
1216 */
1217 @SystemApi(client = MODULE_LIBRARIES)
1218 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1219
Chalard Jeanad565e22021-02-25 17:23:40 +09001220 /** @hide */
1221 @Retention(RetentionPolicy.SOURCE)
1222 @IntDef(value = {
1223 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001224 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1225 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001226 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001227 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001228 }
1229
1230 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001231 * Specifies the preferred network type. When the device has more
1232 * than one type available the preferred network type will be used.
1233 *
1234 * @param preference the network type to prefer over all others. It is
1235 * unspecified what happens to the old preferred network in the
1236 * overall ordering.
1237 * @deprecated Functionality has been removed as it no longer makes sense,
1238 * with many more than two networks - we'd need an array to express
1239 * preference. Instead we use dynamic network properties of
1240 * the networks to describe their precedence.
1241 */
1242 @Deprecated
1243 public void setNetworkPreference(int preference) {
1244 }
1245
1246 /**
1247 * Retrieves the current preferred network type.
1248 *
1249 * @return an integer representing the preferred network type
1250 *
1251 * @deprecated Functionality has been removed as it no longer makes sense,
1252 * with many more than two networks - we'd need an array to express
1253 * preference. Instead we use dynamic network properties of
1254 * the networks to describe their precedence.
1255 */
1256 @Deprecated
1257 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1258 public int getNetworkPreference() {
1259 return TYPE_NONE;
1260 }
1261
1262 /**
1263 * Returns details about the currently active default data network. When
1264 * connected, this network is the default route for outgoing connections.
1265 * You should always check {@link NetworkInfo#isConnected()} before initiating
1266 * network traffic. This may return {@code null} when there is no default
1267 * network.
1268 * Note that if the default network is a VPN, this method will return the
1269 * NetworkInfo for one of its underlying networks instead, or null if the
1270 * VPN agent did not specify any. Apps interested in learning about VPNs
1271 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1272 *
1273 * @return a {@link NetworkInfo} object for the current default network
1274 * or {@code null} if no default network is currently active
1275 * @deprecated See {@link NetworkInfo}.
1276 */
1277 @Deprecated
1278 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1279 @Nullable
1280 public NetworkInfo getActiveNetworkInfo() {
1281 try {
1282 return mService.getActiveNetworkInfo();
1283 } catch (RemoteException e) {
1284 throw e.rethrowFromSystemServer();
1285 }
1286 }
1287
1288 /**
1289 * Returns a {@link Network} object corresponding to the currently active
1290 * default data network. In the event that the current active default data
1291 * network disconnects, the returned {@code Network} object will no longer
1292 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001293 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001294 *
1295 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001296 * {@code null} if no default network is currently active or if
1297 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001298 */
1299 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1300 @Nullable
1301 public Network getActiveNetwork() {
1302 try {
1303 return mService.getActiveNetwork();
1304 } catch (RemoteException e) {
1305 throw e.rethrowFromSystemServer();
1306 }
1307 }
1308
1309 /**
1310 * Returns a {@link Network} object corresponding to the currently active
1311 * default data network for a specific UID. In the event that the default data
1312 * network disconnects, the returned {@code Network} object will no longer
1313 * be usable. This will return {@code null} when there is no default
1314 * network for the UID.
1315 *
1316 * @return a {@link Network} object for the current default network for the
1317 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001318 *
1319 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001320 */
1321 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1322 @Nullable
1323 public Network getActiveNetworkForUid(int uid) {
1324 return getActiveNetworkForUid(uid, false);
1325 }
1326
1327 /** {@hide} */
1328 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1329 try {
1330 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1331 } catch (RemoteException e) {
1332 throw e.rethrowFromSystemServer();
1333 }
1334 }
1335
1336 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001337 * Adds or removes a requirement for given UID ranges to use the VPN.
1338 *
1339 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1340 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1341 * otherwise have permission to bypass the VPN (e.g., because they have the
1342 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1343 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1344 * set to {@code false}, a previously-added restriction is removed.
1345 * <p>
1346 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1347 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1348 * remove a previously-added range, the exact range must be removed as is.
1349 * <p>
1350 * The changes are applied asynchronously and may not have been applied by the time the method
1351 * returns. Apps will be notified about any changes that apply to them via
1352 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1353 * effect.
1354 * <p>
1355 * This method should be called only by the VPN code.
1356 *
1357 * @param ranges the UID ranges to restrict
1358 * @param requireVpn whether the specified UID ranges must use a VPN
1359 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001360 * @hide
1361 */
1362 @RequiresPermission(anyOf = {
1363 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001364 android.Manifest.permission.NETWORK_STACK,
1365 android.Manifest.permission.NETWORK_SETTINGS})
1366 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001367 public void setRequireVpnForUids(boolean requireVpn,
1368 @NonNull Collection<Range<Integer>> ranges) {
1369 Objects.requireNonNull(ranges);
1370 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1371 // This method is not necessarily expected to be used outside the system server, so
1372 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1373 // stack process, or by tests.
1374 UidRange[] rangesArray = new UidRange[ranges.size()];
1375 int index = 0;
1376 for (Range<Integer> range : ranges) {
1377 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1378 }
1379 try {
1380 mService.setRequireVpnForUids(requireVpn, rangesArray);
1381 } catch (RemoteException e) {
1382 throw e.rethrowFromSystemServer();
1383 }
1384 }
1385
1386 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001387 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1388 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1389 * but is still supported for backwards compatibility.
1390 * <p>
1391 * This type of VPN is assumed always to use the system default network, and must always declare
1392 * exactly one underlying network, which is the network that was the default when the VPN
1393 * connected.
1394 * <p>
1395 * Calling this method with {@code true} enables legacy behaviour, specifically:
1396 * <ul>
1397 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1398 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1399 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1400 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1401 * underlying the VPN.</li>
1402 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1403 * similarly replaced by the VPN network state.</li>
1404 * <li>Information on current network interfaces passed to NetworkStatsService will not
1405 * include any VPN interfaces.</li>
1406 * </ul>
1407 *
1408 * @param enabled whether legacy lockdown VPN is enabled or disabled
1409 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001410 * @hide
1411 */
1412 @RequiresPermission(anyOf = {
1413 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001414 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001415 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001416 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001417 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1418 try {
1419 mService.setLegacyLockdownVpnEnabled(enabled);
1420 } catch (RemoteException e) {
1421 throw e.rethrowFromSystemServer();
1422 }
1423 }
1424
1425 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001426 * Returns details about the currently active default data network
1427 * for a given uid. This is for internal use only to avoid spying
1428 * other apps.
1429 *
1430 * @return a {@link NetworkInfo} object for the current default network
1431 * for the given uid or {@code null} if no default network is
1432 * available for the specified uid.
1433 *
1434 * {@hide}
1435 */
1436 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1437 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1438 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1439 return getActiveNetworkInfoForUid(uid, false);
1440 }
1441
1442 /** {@hide} */
1443 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1444 try {
1445 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1446 } catch (RemoteException e) {
1447 throw e.rethrowFromSystemServer();
1448 }
1449 }
1450
1451 /**
1452 * Returns connection status information about a particular
1453 * network type.
1454 *
1455 * @param networkType integer specifying which networkType in
1456 * which you're interested.
1457 * @return a {@link NetworkInfo} object for the requested
1458 * network type or {@code null} if the type is not
1459 * supported by the device. If {@code networkType} is
1460 * TYPE_VPN and a VPN is active for the calling app,
1461 * then this method will try to return one of the
1462 * underlying networks for the VPN or null if the
1463 * VPN agent didn't specify any.
1464 *
1465 * @deprecated This method does not support multiple connected networks
1466 * of the same type. Use {@link #getAllNetworks} and
1467 * {@link #getNetworkInfo(android.net.Network)} instead.
1468 */
1469 @Deprecated
1470 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1471 @Nullable
1472 public NetworkInfo getNetworkInfo(int networkType) {
1473 try {
1474 return mService.getNetworkInfo(networkType);
1475 } catch (RemoteException e) {
1476 throw e.rethrowFromSystemServer();
1477 }
1478 }
1479
1480 /**
1481 * Returns connection status information about a particular
1482 * Network.
1483 *
1484 * @param network {@link Network} specifying which network
1485 * in which you're interested.
1486 * @return a {@link NetworkInfo} object for the requested
1487 * network or {@code null} if the {@code Network}
1488 * is not valid.
1489 * @deprecated See {@link NetworkInfo}.
1490 */
1491 @Deprecated
1492 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1493 @Nullable
1494 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1495 return getNetworkInfoForUid(network, Process.myUid(), false);
1496 }
1497
1498 /** {@hide} */
1499 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1500 try {
1501 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1502 } catch (RemoteException e) {
1503 throw e.rethrowFromSystemServer();
1504 }
1505 }
1506
1507 /**
1508 * Returns connection status information about all network
1509 * types supported by the device.
1510 *
1511 * @return an array of {@link NetworkInfo} objects. Check each
1512 * {@link NetworkInfo#getType} for which type each applies.
1513 *
1514 * @deprecated This method does not support multiple connected networks
1515 * of the same type. Use {@link #getAllNetworks} and
1516 * {@link #getNetworkInfo(android.net.Network)} instead.
1517 */
1518 @Deprecated
1519 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1520 @NonNull
1521 public NetworkInfo[] getAllNetworkInfo() {
1522 try {
1523 return mService.getAllNetworkInfo();
1524 } catch (RemoteException e) {
1525 throw e.rethrowFromSystemServer();
1526 }
1527 }
1528
1529 /**
junyulaib1211372021-03-03 12:09:05 +08001530 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1531 * connected.
1532 * @hide
1533 */
1534 @SystemApi(client = MODULE_LIBRARIES)
1535 @RequiresPermission(anyOf = {
1536 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1537 android.Manifest.permission.NETWORK_STACK,
1538 android.Manifest.permission.NETWORK_SETTINGS})
1539 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001540 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001541 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001542 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001543 } catch (RemoteException e) {
1544 throw e.rethrowFromSystemServer();
1545 }
1546 }
1547
1548 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001549 * Returns the {@link Network} object currently serving a given type, or
1550 * null if the given type is not connected.
1551 *
1552 * @hide
1553 * @deprecated This method does not support multiple connected networks
1554 * of the same type. Use {@link #getAllNetworks} and
1555 * {@link #getNetworkInfo(android.net.Network)} instead.
1556 */
1557 @Deprecated
1558 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1559 @UnsupportedAppUsage
1560 public Network getNetworkForType(int networkType) {
1561 try {
1562 return mService.getNetworkForType(networkType);
1563 } catch (RemoteException e) {
1564 throw e.rethrowFromSystemServer();
1565 }
1566 }
1567
1568 /**
1569 * Returns an array of all {@link Network} currently tracked by the
1570 * framework.
1571 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001572 * @deprecated This method does not provide any notification of network state changes, forcing
1573 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1574 * Apps should use methods such as
1575 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1576 * Apps that desire to obtain information about networks that do not apply to them
1577 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1578 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001579 * @return an array of {@link Network} objects.
1580 */
1581 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1582 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001583 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001584 public Network[] getAllNetworks() {
1585 try {
1586 return mService.getAllNetworks();
1587 } catch (RemoteException e) {
1588 throw e.rethrowFromSystemServer();
1589 }
1590 }
1591
1592 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001593 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001594 * the Networks that applications run by the given user will use by default.
1595 * @hide
1596 */
1597 @UnsupportedAppUsage
1598 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1599 try {
1600 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001601 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001602 } catch (RemoteException e) {
1603 throw e.rethrowFromSystemServer();
1604 }
1605 }
1606
1607 /**
1608 * Returns the IP information for the current default network.
1609 *
1610 * @return a {@link LinkProperties} object describing the IP info
1611 * for the current default network, or {@code null} if there
1612 * is no current default network.
1613 *
1614 * {@hide}
1615 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1616 * value of {@link #getActiveNetwork()} instead. In particular,
1617 * this method will return non-null LinkProperties even if the
1618 * app is blocked by policy from using this network.
1619 */
1620 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1621 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1622 public LinkProperties getActiveLinkProperties() {
1623 try {
1624 return mService.getActiveLinkProperties();
1625 } catch (RemoteException e) {
1626 throw e.rethrowFromSystemServer();
1627 }
1628 }
1629
1630 /**
1631 * Returns the IP information for a given network type.
1632 *
1633 * @param networkType the network type of interest.
1634 * @return a {@link LinkProperties} object describing the IP info
1635 * for the given networkType, or {@code null} if there is
1636 * no current default network.
1637 *
1638 * {@hide}
1639 * @deprecated This method does not support multiple connected networks
1640 * of the same type. Use {@link #getAllNetworks},
1641 * {@link #getNetworkInfo(android.net.Network)}, and
1642 * {@link #getLinkProperties(android.net.Network)} instead.
1643 */
1644 @Deprecated
1645 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1646 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1647 public LinkProperties getLinkProperties(int networkType) {
1648 try {
1649 return mService.getLinkPropertiesForType(networkType);
1650 } catch (RemoteException e) {
1651 throw e.rethrowFromSystemServer();
1652 }
1653 }
1654
1655 /**
1656 * Get the {@link LinkProperties} for the given {@link Network}. This
1657 * will return {@code null} if the network is unknown.
1658 *
1659 * @param network The {@link Network} object identifying the network in question.
1660 * @return The {@link LinkProperties} for the network, or {@code null}.
1661 */
1662 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1663 @Nullable
1664 public LinkProperties getLinkProperties(@Nullable Network network) {
1665 try {
1666 return mService.getLinkProperties(network);
1667 } catch (RemoteException e) {
1668 throw e.rethrowFromSystemServer();
1669 }
1670 }
1671
1672 /**
lucaslinc582d502022-01-27 09:07:00 +08001673 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001674 *
lucaslinc582d502022-01-27 09:07:00 +08001675 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1676 * given package, considering its permissions.
1677 *
1678 * @param lp A {@link LinkProperties} which will be redacted.
1679 * @param uid The target uid.
1680 * @param packageName The name of the package, for appops logging.
1681 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1682 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1683 * @hide
1684 */
1685 @RequiresPermission(anyOf = {
1686 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1687 android.Manifest.permission.NETWORK_STACK,
1688 android.Manifest.permission.NETWORK_SETTINGS})
1689 @SystemApi(client = MODULE_LIBRARIES)
1690 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001691 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001692 @NonNull String packageName) {
1693 try {
lucaslind2b06132022-03-02 10:56:57 +08001694 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001695 lp, uid, packageName, getAttributionTag());
1696 } catch (RemoteException e) {
1697 throw e.rethrowFromSystemServer();
1698 }
1699 }
1700
1701 /**
1702 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1703 *
1704 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1705 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1706 * sensitive information. To retrieve this location sensitive information (subject to
1707 * the caller's location permissions), use a {@link NetworkCallback} with the
1708 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1709 *
1710 * This method returns {@code null} if the network is unknown or if the |network| argument
1711 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001712 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001713 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001714 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001715 */
1716 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1717 @Nullable
1718 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1719 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001720 return mService.getNetworkCapabilities(
1721 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001722 } catch (RemoteException e) {
1723 throw e.rethrowFromSystemServer();
1724 }
1725 }
1726
1727 /**
lucaslinc582d502022-01-27 09:07:00 +08001728 * Redact {@link NetworkCapabilities} for a given package.
1729 *
1730 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001731 * to the given package, considering its permissions. If the passed capabilities contain
1732 * location-sensitive information, they will be redacted to the correct degree for the location
1733 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1734 * that level of location. If the UID holds no location permission, the returned object will
1735 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001736 *
1737 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1738 * @param uid The target uid.
1739 * @param packageName The name of the package, for appops logging.
1740 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1741 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1742 * @hide
1743 */
1744 @RequiresPermission(anyOf = {
1745 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1746 android.Manifest.permission.NETWORK_STACK,
1747 android.Manifest.permission.NETWORK_SETTINGS})
1748 @SystemApi(client = MODULE_LIBRARIES)
1749 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001750 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001751 @NonNull NetworkCapabilities nc,
1752 int uid, @NonNull String packageName) {
1753 try {
lucaslind2b06132022-03-02 10:56:57 +08001754 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001755 getAttributionTag());
1756 } catch (RemoteException e) {
1757 throw e.rethrowFromSystemServer();
1758 }
1759 }
1760
1761 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001762 * Gets a URL that can be used for resolving whether a captive portal is present.
1763 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1764 * portal is present.
1765 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1766 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1767 *
1768 * The system network validation may be using different strategies to detect captive portals,
1769 * so this method does not necessarily return a URL used by the system. It only returns a URL
1770 * that may be relevant for other components trying to detect captive portals.
1771 *
1772 * @hide
1773 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1774 * system.
1775 */
1776 @Deprecated
1777 @SystemApi
1778 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1779 public String getCaptivePortalServerUrl() {
1780 try {
1781 return mService.getCaptivePortalServerUrl();
1782 } catch (RemoteException e) {
1783 throw e.rethrowFromSystemServer();
1784 }
1785 }
1786
1787 /**
1788 * Tells the underlying networking system that the caller wants to
1789 * begin using the named feature. The interpretation of {@code feature}
1790 * is completely up to each networking implementation.
1791 *
1792 * <p>This method requires the caller to hold either the
1793 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1794 * or the ability to modify system settings as determined by
1795 * {@link android.provider.Settings.System#canWrite}.</p>
1796 *
1797 * @param networkType specifies which network the request pertains to
1798 * @param feature the name of the feature to be used
1799 * @return an integer value representing the outcome of the request.
1800 * The interpretation of this value is specific to each networking
1801 * implementation+feature combination, except that the value {@code -1}
1802 * always indicates failure.
1803 *
1804 * @deprecated Deprecated in favor of the cleaner
1805 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1806 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1807 * throw {@code UnsupportedOperationException} if called.
1808 * @removed
1809 */
1810 @Deprecated
1811 public int startUsingNetworkFeature(int networkType, String feature) {
1812 checkLegacyRoutingApiAccess();
1813 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1814 if (netCap == null) {
1815 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1816 feature);
1817 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1818 }
1819
1820 NetworkRequest request = null;
1821 synchronized (sLegacyRequests) {
1822 LegacyRequest l = sLegacyRequests.get(netCap);
1823 if (l != null) {
1824 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1825 renewRequestLocked(l);
1826 if (l.currentNetwork != null) {
1827 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1828 } else {
1829 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1830 }
1831 }
1832
1833 request = requestNetworkForFeatureLocked(netCap);
1834 }
1835 if (request != null) {
1836 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1837 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1838 } else {
1839 Log.d(TAG, " request Failed");
1840 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1841 }
1842 }
1843
1844 /**
1845 * Tells the underlying networking system that the caller is finished
1846 * using the named feature. The interpretation of {@code feature}
1847 * is completely up to each networking implementation.
1848 *
1849 * <p>This method requires the caller to hold either the
1850 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1851 * or the ability to modify system settings as determined by
1852 * {@link android.provider.Settings.System#canWrite}.</p>
1853 *
1854 * @param networkType specifies which network the request pertains to
1855 * @param feature the name of the feature that is no longer needed
1856 * @return an integer value representing the outcome of the request.
1857 * The interpretation of this value is specific to each networking
1858 * implementation+feature combination, except that the value {@code -1}
1859 * always indicates failure.
1860 *
1861 * @deprecated Deprecated in favor of the cleaner
1862 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1863 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1864 * throw {@code UnsupportedOperationException} if called.
1865 * @removed
1866 */
1867 @Deprecated
1868 public int stopUsingNetworkFeature(int networkType, String feature) {
1869 checkLegacyRoutingApiAccess();
1870 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1871 if (netCap == null) {
1872 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1873 feature);
1874 return -1;
1875 }
1876
1877 if (removeRequestForFeature(netCap)) {
1878 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1879 }
1880 return 1;
1881 }
1882
1883 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1884 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1885 if (networkType == TYPE_MOBILE) {
1886 switch (feature) {
1887 case "enableCBS":
1888 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1889 case "enableDUN":
1890 case "enableDUNAlways":
1891 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1892 case "enableFOTA":
1893 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1894 case "enableHIPRI":
1895 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1896 case "enableIMS":
1897 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1898 case "enableMMS":
1899 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1900 case "enableSUPL":
1901 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1902 default:
1903 return null;
1904 }
1905 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1906 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1907 }
1908 return null;
1909 }
1910
1911 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1912 if (netCap == null) return TYPE_NONE;
1913 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1914 return TYPE_MOBILE_CBS;
1915 }
1916 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1917 return TYPE_MOBILE_IMS;
1918 }
1919 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1920 return TYPE_MOBILE_FOTA;
1921 }
1922 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1923 return TYPE_MOBILE_DUN;
1924 }
1925 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1926 return TYPE_MOBILE_SUPL;
1927 }
1928 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1929 return TYPE_MOBILE_MMS;
1930 }
1931 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1932 return TYPE_MOBILE_HIPRI;
1933 }
1934 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1935 return TYPE_WIFI_P2P;
1936 }
1937 return TYPE_NONE;
1938 }
1939
1940 private static class LegacyRequest {
1941 NetworkCapabilities networkCapabilities;
1942 NetworkRequest networkRequest;
1943 int expireSequenceNumber;
1944 Network currentNetwork;
1945 int delay = -1;
1946
1947 private void clearDnsBinding() {
1948 if (currentNetwork != null) {
1949 currentNetwork = null;
1950 setProcessDefaultNetworkForHostResolution(null);
1951 }
1952 }
1953
1954 NetworkCallback networkCallback = new NetworkCallback() {
1955 @Override
1956 public void onAvailable(Network network) {
1957 currentNetwork = network;
1958 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1959 setProcessDefaultNetworkForHostResolution(network);
1960 }
1961 @Override
1962 public void onLost(Network network) {
1963 if (network.equals(currentNetwork)) clearDnsBinding();
1964 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1965 }
1966 };
1967 }
1968
1969 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1970 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1971 new HashMap<>();
1972
1973 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1974 synchronized (sLegacyRequests) {
1975 LegacyRequest l = sLegacyRequests.get(netCap);
1976 if (l != null) return l.networkRequest;
1977 }
1978 return null;
1979 }
1980
1981 private void renewRequestLocked(LegacyRequest l) {
1982 l.expireSequenceNumber++;
1983 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1984 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1985 }
1986
1987 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1988 int ourSeqNum = -1;
1989 synchronized (sLegacyRequests) {
1990 LegacyRequest l = sLegacyRequests.get(netCap);
1991 if (l == null) return;
1992 ourSeqNum = l.expireSequenceNumber;
1993 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
1994 }
1995 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1996 }
1997
1998 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1999 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2000 int delay = -1;
2001 int type = legacyTypeForNetworkCapabilities(netCap);
2002 try {
2003 delay = mService.getRestoreDefaultNetworkDelay(type);
2004 } catch (RemoteException e) {
2005 throw e.rethrowFromSystemServer();
2006 }
2007 LegacyRequest l = new LegacyRequest();
2008 l.networkCapabilities = netCap;
2009 l.delay = delay;
2010 l.expireSequenceNumber = 0;
2011 l.networkRequest = sendRequestForNetwork(
2012 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2013 if (l.networkRequest == null) return null;
2014 sLegacyRequests.put(netCap, l);
2015 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2016 return l.networkRequest;
2017 }
2018
2019 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2020 if (delay >= 0) {
2021 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2022 CallbackHandler handler = getDefaultHandler();
2023 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2024 handler.sendMessageDelayed(msg, delay);
2025 }
2026 }
2027
2028 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2029 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2030 final LegacyRequest l;
2031 synchronized (sLegacyRequests) {
2032 l = sLegacyRequests.remove(netCap);
2033 }
2034 if (l == null) return false;
2035 unregisterNetworkCallback(l.networkCallback);
2036 l.clearDnsBinding();
2037 return true;
2038 }
2039
2040 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2041 static {
2042 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2043 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2044 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2045 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2046 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2047 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2048 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2049 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2050 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2051 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2052 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2053 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2054 }
2055
2056 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2057 static {
2058 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2059 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2060 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2061 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2062 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2063 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2064 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2065 }
2066
2067 /**
2068 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2069 * instance suitable for registering a request or callback. Throws an
2070 * IllegalArgumentException if no mapping from the legacy type to
2071 * NetworkCapabilities is known.
2072 *
2073 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2074 * to find the network instead.
2075 * @hide
2076 */
2077 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2078 final NetworkCapabilities nc = new NetworkCapabilities();
2079
2080 // Map from type to transports.
2081 final int NOT_FOUND = -1;
2082 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002083 if (transport == NOT_FOUND) {
2084 throw new IllegalArgumentException("unknown legacy type: " + type);
2085 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002086 nc.addTransportType(transport);
2087
2088 // Map from type to capabilities.
2089 nc.addCapability(sLegacyTypeToCapability.get(
2090 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2091 nc.maybeMarkCapabilitiesRestricted();
2092 return nc;
2093 }
2094
2095 /** @hide */
2096 public static class PacketKeepaliveCallback {
2097 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2098 public PacketKeepaliveCallback() {
2099 }
2100 /** The requested keepalive was successfully started. */
2101 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2102 public void onStarted() {}
2103 /** The keepalive was successfully stopped. */
2104 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2105 public void onStopped() {}
2106 /** An error occurred. */
2107 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2108 public void onError(int error) {}
2109 }
2110
2111 /**
2112 * Allows applications to request that the system periodically send specific packets on their
2113 * behalf, using hardware offload to save battery power.
2114 *
2115 * To request that the system send keepalives, call one of the methods that return a
2116 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2117 * passing in a non-null callback. If the callback is successfully started, the callback's
2118 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2119 * specifying one of the {@code ERROR_*} constants in this class.
2120 *
2121 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2122 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2123 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2124 *
2125 * @deprecated Use {@link SocketKeepalive} instead.
2126 *
2127 * @hide
2128 */
2129 public class PacketKeepalive {
2130
2131 private static final String TAG = "PacketKeepalive";
2132
2133 /** @hide */
2134 public static final int SUCCESS = 0;
2135
2136 /** @hide */
2137 public static final int NO_KEEPALIVE = -1;
2138
2139 /** @hide */
2140 public static final int BINDER_DIED = -10;
2141
2142 /** The specified {@code Network} is not connected. */
2143 public static final int ERROR_INVALID_NETWORK = -20;
2144 /** The specified IP addresses are invalid. For example, the specified source IP address is
2145 * not configured on the specified {@code Network}. */
2146 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2147 /** The requested port is invalid. */
2148 public static final int ERROR_INVALID_PORT = -22;
2149 /** The packet length is invalid (e.g., too long). */
2150 public static final int ERROR_INVALID_LENGTH = -23;
2151 /** The packet transmission interval is invalid (e.g., too short). */
2152 public static final int ERROR_INVALID_INTERVAL = -24;
2153
2154 /** The hardware does not support this request. */
2155 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2156 /** The hardware returned an error. */
2157 public static final int ERROR_HARDWARE_ERROR = -31;
2158
2159 /** The NAT-T destination port for IPsec */
2160 public static final int NATT_PORT = 4500;
2161
2162 /** The minimum interval in seconds between keepalive packet transmissions */
2163 public static final int MIN_INTERVAL = 10;
2164
2165 private final Network mNetwork;
2166 private final ISocketKeepaliveCallback mCallback;
2167 private final ExecutorService mExecutor;
2168
2169 private volatile Integer mSlot;
2170
2171 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2172 public void stop() {
2173 try {
2174 mExecutor.execute(() -> {
2175 try {
2176 if (mSlot != null) {
2177 mService.stopKeepalive(mNetwork, mSlot);
2178 }
2179 } catch (RemoteException e) {
2180 Log.e(TAG, "Error stopping packet keepalive: ", e);
2181 throw e.rethrowFromSystemServer();
2182 }
2183 });
2184 } catch (RejectedExecutionException e) {
2185 // The internal executor has already stopped due to previous event.
2186 }
2187 }
2188
2189 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002190 Objects.requireNonNull(network, "network cannot be null");
2191 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002192 mNetwork = network;
2193 mExecutor = Executors.newSingleThreadExecutor();
2194 mCallback = new ISocketKeepaliveCallback.Stub() {
2195 @Override
2196 public void onStarted(int slot) {
2197 final long token = Binder.clearCallingIdentity();
2198 try {
2199 mExecutor.execute(() -> {
2200 mSlot = slot;
2201 callback.onStarted();
2202 });
2203 } finally {
2204 Binder.restoreCallingIdentity(token);
2205 }
2206 }
2207
2208 @Override
2209 public void onStopped() {
2210 final long token = Binder.clearCallingIdentity();
2211 try {
2212 mExecutor.execute(() -> {
2213 mSlot = null;
2214 callback.onStopped();
2215 });
2216 } finally {
2217 Binder.restoreCallingIdentity(token);
2218 }
2219 mExecutor.shutdown();
2220 }
2221
2222 @Override
2223 public void onError(int error) {
2224 final long token = Binder.clearCallingIdentity();
2225 try {
2226 mExecutor.execute(() -> {
2227 mSlot = null;
2228 callback.onError(error);
2229 });
2230 } finally {
2231 Binder.restoreCallingIdentity(token);
2232 }
2233 mExecutor.shutdown();
2234 }
2235
2236 @Override
2237 public void onDataReceived() {
2238 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2239 // this callback when data is received.
2240 }
2241 };
2242 }
2243 }
2244
2245 /**
2246 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2247 *
2248 * @deprecated Use {@link #createSocketKeepalive} instead.
2249 *
2250 * @hide
2251 */
2252 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2253 public PacketKeepalive startNattKeepalive(
2254 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2255 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2256 final PacketKeepalive k = new PacketKeepalive(network, callback);
2257 try {
2258 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2259 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2260 } catch (RemoteException e) {
2261 Log.e(TAG, "Error starting packet keepalive: ", e);
2262 throw e.rethrowFromSystemServer();
2263 }
2264 return k;
2265 }
2266
2267 // Construct an invalid fd.
2268 private ParcelFileDescriptor createInvalidFd() {
2269 final int invalidFd = -1;
2270 return ParcelFileDescriptor.adoptFd(invalidFd);
2271 }
2272
2273 /**
2274 * Request that keepalives be started on a IPsec NAT-T socket.
2275 *
2276 * @param network The {@link Network} the socket is on.
2277 * @param socket The socket that needs to be kept alive.
2278 * @param source The source address of the {@link UdpEncapsulationSocket}.
2279 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2280 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2281 * must run callback sequentially, otherwise the order of callbacks cannot be
2282 * guaranteed.
2283 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2284 * changes. Must be extended by applications that use this API.
2285 *
2286 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2287 * given socket.
2288 **/
2289 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2290 @NonNull UdpEncapsulationSocket socket,
2291 @NonNull InetAddress source,
2292 @NonNull InetAddress destination,
2293 @NonNull @CallbackExecutor Executor executor,
2294 @NonNull Callback callback) {
2295 ParcelFileDescriptor dup;
2296 try {
2297 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2298 // which cannot be obtained by the app process.
2299 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2300 } catch (IOException ignored) {
2301 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2302 // ERROR_INVALID_SOCKET.
2303 dup = createInvalidFd();
2304 }
2305 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2306 destination, executor, callback);
2307 }
2308
2309 /**
2310 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2311 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2312 *
2313 * @param network The {@link Network} the socket is on.
2314 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2315 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2316 * from that port.
2317 * @param source The source address of the {@link UdpEncapsulationSocket}.
2318 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2319 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2320 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2321 * must run callback sequentially, otherwise the order of callbacks cannot be
2322 * guaranteed.
2323 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2324 * changes. Must be extended by applications that use this API.
2325 *
2326 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2327 * given socket.
2328 * @hide
2329 */
2330 @SystemApi
2331 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2332 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2333 @NonNull ParcelFileDescriptor pfd,
2334 @NonNull InetAddress source,
2335 @NonNull InetAddress destination,
2336 @NonNull @CallbackExecutor Executor executor,
2337 @NonNull Callback callback) {
2338 ParcelFileDescriptor dup;
2339 try {
2340 // TODO: Consider remove unnecessary dup.
2341 dup = pfd.dup();
2342 } catch (IOException ignored) {
2343 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2344 // ERROR_INVALID_SOCKET.
2345 dup = createInvalidFd();
2346 }
2347 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002348 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002349 }
2350
2351 /**
2352 * Request that keepalives be started on a TCP socket.
2353 * The socket must be established.
2354 *
2355 * @param network The {@link Network} the socket is on.
2356 * @param socket The socket that needs to be kept alive.
2357 * @param executor The executor on which callback will be invoked. This implementation assumes
2358 * the provided {@link Executor} runs the callbacks in sequence with no
2359 * concurrency. Failing this, no guarantee of correctness can be made. It is
2360 * the responsibility of the caller to ensure the executor provides this
2361 * guarantee. A simple way of creating such an executor is with the standard
2362 * tool {@code Executors.newSingleThreadExecutor}.
2363 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2364 * changes. Must be extended by applications that use this API.
2365 *
2366 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2367 * given socket.
2368 * @hide
2369 */
2370 @SystemApi
2371 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2372 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2373 @NonNull Socket socket,
2374 @NonNull Executor executor,
2375 @NonNull Callback callback) {
2376 ParcelFileDescriptor dup;
2377 try {
2378 dup = ParcelFileDescriptor.fromSocket(socket);
2379 } catch (UncheckedIOException ignored) {
2380 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2381 // ERROR_INVALID_SOCKET.
2382 dup = createInvalidFd();
2383 }
2384 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2385 }
2386
2387 /**
2388 * Ensure that a network route exists to deliver traffic to the specified
2389 * host via the specified network interface. An attempt to add a route that
2390 * already exists is ignored, but treated as successful.
2391 *
2392 * <p>This method requires the caller to hold either the
2393 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2394 * or the ability to modify system settings as determined by
2395 * {@link android.provider.Settings.System#canWrite}.</p>
2396 *
2397 * @param networkType the type of the network over which traffic to the specified
2398 * host is to be routed
2399 * @param hostAddress the IP address of the host to which the route is desired
2400 * @return {@code true} on success, {@code false} on failure
2401 *
2402 * @deprecated Deprecated in favor of the
2403 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2404 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2405 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2406 * throw {@code UnsupportedOperationException} if called.
2407 * @removed
2408 */
2409 @Deprecated
2410 public boolean requestRouteToHost(int networkType, int hostAddress) {
2411 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2412 }
2413
2414 /**
2415 * Ensure that a network route exists to deliver traffic to the specified
2416 * host via the specified network interface. An attempt to add a route that
2417 * already exists is ignored, but treated as successful.
2418 *
2419 * <p>This method requires the caller to hold either the
2420 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2421 * or the ability to modify system settings as determined by
2422 * {@link android.provider.Settings.System#canWrite}.</p>
2423 *
2424 * @param networkType the type of the network over which traffic to the specified
2425 * host is to be routed
2426 * @param hostAddress the IP address of the host to which the route is desired
2427 * @return {@code true} on success, {@code false} on failure
2428 * @hide
2429 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2430 * {@link #bindProcessToNetwork} API.
2431 */
2432 @Deprecated
2433 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002434 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002435 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2436 checkLegacyRoutingApiAccess();
2437 try {
2438 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2439 mContext.getOpPackageName(), getAttributionTag());
2440 } catch (RemoteException e) {
2441 throw e.rethrowFromSystemServer();
2442 }
2443 }
2444
2445 /**
2446 * @return the context's attribution tag
2447 */
2448 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2449 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002450 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002451 }
2452
2453 /**
2454 * Returns the value of the setting for background data usage. If false,
2455 * applications should not use the network if the application is not in the
2456 * foreground. Developers should respect this setting, and check the value
2457 * of this before performing any background data operations.
2458 * <p>
2459 * All applications that have background services that use the network
2460 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2461 * <p>
2462 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2463 * background data depends on several combined factors, and this method will
2464 * always return {@code true}. Instead, when background data is unavailable,
2465 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2466 *
2467 * @return Whether background data usage is allowed.
2468 */
2469 @Deprecated
2470 public boolean getBackgroundDataSetting() {
2471 // assume that background data is allowed; final authority is
2472 // NetworkInfo which may be blocked.
2473 return true;
2474 }
2475
2476 /**
2477 * Sets the value of the setting for background data usage.
2478 *
2479 * @param allowBackgroundData Whether an application should use data while
2480 * it is in the background.
2481 *
2482 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2483 * @see #getBackgroundDataSetting()
2484 * @hide
2485 */
2486 @Deprecated
2487 @UnsupportedAppUsage
2488 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2489 // ignored
2490 }
2491
2492 /**
2493 * @hide
2494 * @deprecated Talk to TelephonyManager directly
2495 */
2496 @Deprecated
2497 @UnsupportedAppUsage
2498 public boolean getMobileDataEnabled() {
2499 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2500 if (tm != null) {
2501 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2502 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2503 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2504 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2505 + " retVal=" + retVal);
2506 return retVal;
2507 }
2508 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2509 return false;
2510 }
2511
2512 /**
2513 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2514 * to find out when the system default network has gone in to a high power state.
2515 */
2516 public interface OnNetworkActiveListener {
2517 /**
2518 * Called on the main thread of the process to report that the current data network
2519 * has become active, and it is now a good time to perform any pending network
2520 * operations. Note that this listener only tells you when the network becomes
2521 * active; if at any other time you want to know whether it is active (and thus okay
2522 * to initiate network traffic), you can retrieve its instantaneous state with
2523 * {@link ConnectivityManager#isDefaultNetworkActive}.
2524 */
2525 void onNetworkActive();
2526 }
2527
Chiachang Wang2de41682021-09-23 10:46:03 +08002528 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002529 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2530 mNetworkActivityListeners = new ArrayMap<>();
2531
2532 /**
2533 * Start listening to reports when the system's default data network is active, meaning it is
2534 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2535 * to determine the current state of the system's default network after registering the
2536 * listener.
2537 * <p>
2538 * If the process default network has been set with
2539 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2540 * reflect the process's default, but the system default.
2541 *
2542 * @param l The listener to be told when the network is active.
2543 */
2544 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002545 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002546 @Override
2547 public void onNetworkActive() throws RemoteException {
2548 l.onNetworkActive();
2549 }
2550 };
2551
Chiachang Wang2de41682021-09-23 10:46:03 +08002552 synchronized (mNetworkActivityListeners) {
2553 try {
2554 mService.registerNetworkActivityListener(rl);
2555 mNetworkActivityListeners.put(l, rl);
2556 } catch (RemoteException e) {
2557 throw e.rethrowFromSystemServer();
2558 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002559 }
2560 }
2561
2562 /**
2563 * Remove network active listener previously registered with
2564 * {@link #addDefaultNetworkActiveListener}.
2565 *
2566 * @param l Previously registered listener.
2567 */
2568 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002569 synchronized (mNetworkActivityListeners) {
2570 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2571 if (rl == null) {
2572 throw new IllegalArgumentException("Listener was not registered.");
2573 }
2574 try {
2575 mService.unregisterNetworkActivityListener(rl);
2576 mNetworkActivityListeners.remove(l);
2577 } catch (RemoteException e) {
2578 throw e.rethrowFromSystemServer();
2579 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002580 }
2581 }
2582
2583 /**
2584 * Return whether the data network is currently active. An active network means that
2585 * it is currently in a high power state for performing data transmission. On some
2586 * types of networks, it may be expensive to move and stay in such a state, so it is
2587 * more power efficient to batch network traffic together when the radio is already in
2588 * this state. This method tells you whether right now is currently a good time to
2589 * initiate network traffic, as the network is already active.
2590 */
2591 public boolean isDefaultNetworkActive() {
2592 try {
lucaslin709eb842021-01-21 02:04:15 +08002593 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002594 } catch (RemoteException e) {
2595 throw e.rethrowFromSystemServer();
2596 }
2597 }
2598
2599 /**
2600 * {@hide}
2601 */
2602 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002603 mContext = Objects.requireNonNull(context, "missing context");
2604 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002605 sInstance = this;
2606 }
2607
2608 /** {@hide} */
2609 @UnsupportedAppUsage
2610 public static ConnectivityManager from(Context context) {
2611 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2612 }
2613
2614 /** @hide */
2615 public NetworkRequest getDefaultRequest() {
2616 try {
2617 // This is not racy as the default request is final in ConnectivityService.
2618 return mService.getDefaultRequest();
2619 } catch (RemoteException e) {
2620 throw e.rethrowFromSystemServer();
2621 }
2622 }
2623
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002624 /**
2625 * Check if the package is a allowed to write settings. This also accounts that such an access
2626 * happened.
2627 *
2628 * @return {@code true} iff the package is allowed to write settings.
2629 */
2630 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2631 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2632 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2633 boolean throwException) {
2634 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002635 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002636 }
2637
2638 /**
2639 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2640 * situations where a Context pointer is unavailable.
2641 * @hide
2642 */
2643 @Deprecated
2644 static ConnectivityManager getInstanceOrNull() {
2645 return sInstance;
2646 }
2647
2648 /**
2649 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2650 * situations where a Context pointer is unavailable.
2651 * @hide
2652 */
2653 @Deprecated
2654 @UnsupportedAppUsage
2655 private static ConnectivityManager getInstance() {
2656 if (getInstanceOrNull() == null) {
2657 throw new IllegalStateException("No ConnectivityManager yet constructed");
2658 }
2659 return getInstanceOrNull();
2660 }
2661
2662 /**
2663 * Get the set of tetherable, available interfaces. This list is limited by
2664 * device configuration and current interface existence.
2665 *
2666 * @return an array of 0 or more Strings of tetherable 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[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002675 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002676 }
2677
2678 /**
2679 * Get the set of tethered interfaces.
2680 *
2681 * @return an array of 0 or more String of currently tethered interface names.
2682 *
2683 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2684 * {@hide}
2685 */
2686 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2687 @UnsupportedAppUsage
2688 @Deprecated
2689 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002690 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002691 }
2692
2693 /**
2694 * Get the set of interface names which attempted to tether but
2695 * failed. Re-attempting to tether may cause them to reset to the Tethered
2696 * state. Alternatively, causing the interface to be destroyed and recreated
2697 * may cause them to reset to the available state.
2698 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2699 * information on the cause of the errors.
2700 *
2701 * @return an array of 0 or more String indicating the interface names
2702 * which failed to tether.
2703 *
2704 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2705 * {@hide}
2706 */
2707 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2708 @UnsupportedAppUsage
2709 @Deprecated
2710 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002711 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002712 }
2713
2714 /**
2715 * Get the set of tethered dhcp ranges.
2716 *
2717 * @deprecated This method is not supported.
2718 * TODO: remove this function when all of clients are removed.
2719 * {@hide}
2720 */
2721 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2722 @Deprecated
2723 public String[] getTetheredDhcpRanges() {
2724 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2725 }
2726
2727 /**
2728 * Attempt to tether the named interface. This will setup a dhcp server
2729 * on the interface, forward and NAT IP packets and forward DNS requests
2730 * to the best active upstream network interface. Note that if no upstream
2731 * IP network interface is available, dhcp will still run and traffic will be
2732 * allowed between the tethered devices and this device, though upstream net
2733 * access will of course fail until an upstream network interface becomes
2734 * active.
2735 *
2736 * <p>This method requires the caller to hold either the
2737 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2738 * or the ability to modify system settings as determined by
2739 * {@link android.provider.Settings.System#canWrite}.</p>
2740 *
2741 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2742 * and WifiStateMachine which need direct access. All other clients should use
2743 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2744 * logic.</p>
2745 *
2746 * @param iface the interface name to tether.
2747 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2748 * @deprecated Use {@link TetheringManager#startTethering} instead
2749 *
2750 * {@hide}
2751 */
2752 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2753 @Deprecated
2754 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002755 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002756 }
2757
2758 /**
2759 * Stop tethering the named interface.
2760 *
2761 * <p>This method requires the caller to hold either the
2762 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2763 * or the ability to modify system settings as determined by
2764 * {@link android.provider.Settings.System#canWrite}.</p>
2765 *
2766 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2767 * and WifiStateMachine which need direct access. All other clients should use
2768 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2769 * logic.</p>
2770 *
2771 * @param iface the interface name to untether.
2772 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2773 *
2774 * {@hide}
2775 */
2776 @UnsupportedAppUsage
2777 @Deprecated
2778 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002779 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002780 }
2781
2782 /**
2783 * Check if the device allows for tethering. It may be disabled via
2784 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2785 * due to device configuration.
2786 *
2787 * <p>If this app does not have permission to use this API, it will always
2788 * return false rather than throw an exception.</p>
2789 *
2790 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2791 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2792 *
2793 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2794 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2795 *
2796 * @return a boolean - {@code true} indicating Tethering is supported.
2797 *
2798 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2799 * {@hide}
2800 */
2801 @SystemApi
2802 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2803 android.Manifest.permission.WRITE_SETTINGS})
2804 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002805 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002806 }
2807
2808 /**
2809 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2810 *
2811 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2812 * @hide
2813 */
2814 @SystemApi
2815 @Deprecated
2816 public static abstract class OnStartTetheringCallback {
2817 /**
2818 * Called when tethering has been successfully started.
2819 */
2820 public void onTetheringStarted() {}
2821
2822 /**
2823 * Called when starting tethering failed.
2824 */
2825 public void onTetheringFailed() {}
2826 }
2827
2828 /**
2829 * Convenient overload for
2830 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2831 * handler to run on the current thread's {@link Looper}.
2832 *
2833 * @deprecated Use {@link TetheringManager#startTethering} instead.
2834 * @hide
2835 */
2836 @SystemApi
2837 @Deprecated
2838 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2839 public void startTethering(int type, boolean showProvisioningUi,
2840 final OnStartTetheringCallback callback) {
2841 startTethering(type, showProvisioningUi, callback, null);
2842 }
2843
2844 /**
2845 * Runs tether provisioning for the given type if needed and then starts tethering if
2846 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2847 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2848 * schedules tether provisioning re-checks if appropriate.
2849 *
2850 * @param type The type of tethering to start. Must be one of
2851 * {@link ConnectivityManager.TETHERING_WIFI},
2852 * {@link ConnectivityManager.TETHERING_USB}, or
2853 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2854 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2855 * is one. This should be true the first time this function is called and also any time
2856 * the user can see this UI. It gives users information from their carrier about the
2857 * check failing and how they can sign up for tethering if possible.
2858 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2859 * of the result of trying to tether.
2860 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2861 *
2862 * @deprecated Use {@link TetheringManager#startTethering} instead.
2863 * @hide
2864 */
2865 @SystemApi
2866 @Deprecated
2867 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2868 public void startTethering(int type, boolean showProvisioningUi,
2869 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002870 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002871
2872 final Executor executor = new Executor() {
2873 @Override
2874 public void execute(Runnable command) {
2875 if (handler == null) {
2876 command.run();
2877 } else {
2878 handler.post(command);
2879 }
2880 }
2881 };
2882
2883 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2884 @Override
2885 public void onTetheringStarted() {
2886 callback.onTetheringStarted();
2887 }
2888
2889 @Override
2890 public void onTetheringFailed(final int error) {
2891 callback.onTetheringFailed();
2892 }
2893 };
2894
2895 final TetheringRequest request = new TetheringRequest.Builder(type)
2896 .setShouldShowEntitlementUi(showProvisioningUi).build();
2897
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002898 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002899 }
2900
2901 /**
2902 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2903 * applicable.
2904 *
2905 * @param type The type of tethering to stop. Must be one of
2906 * {@link ConnectivityManager.TETHERING_WIFI},
2907 * {@link ConnectivityManager.TETHERING_USB}, or
2908 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2909 *
2910 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2911 * @hide
2912 */
2913 @SystemApi
2914 @Deprecated
2915 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2916 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002917 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002918 }
2919
2920 /**
2921 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2922 * upstream status.
2923 *
2924 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2925 * @hide
2926 */
2927 @SystemApi
2928 @Deprecated
2929 public abstract static class OnTetheringEventCallback {
2930
2931 /**
2932 * Called when tethering upstream changed. This can be called multiple times and can be
2933 * called any time.
2934 *
2935 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2936 * have any upstream.
2937 */
2938 public void onUpstreamChanged(@Nullable Network network) {}
2939 }
2940
2941 @GuardedBy("mTetheringEventCallbacks")
2942 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2943 mTetheringEventCallbacks = new ArrayMap<>();
2944
2945 /**
2946 * Start listening to tethering change events. Any new added callback will receive the last
2947 * tethering status right away. If callback is registered when tethering has no upstream or
2948 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2949 * with a null argument. The same callback object cannot be registered twice.
2950 *
2951 * @param executor the executor on which callback will be invoked.
2952 * @param callback the callback to be called when tethering has change events.
2953 *
2954 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2955 * @hide
2956 */
2957 @SystemApi
2958 @Deprecated
2959 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2960 public void registerTetheringEventCallback(
2961 @NonNull @CallbackExecutor Executor executor,
2962 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002963 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002964
2965 final TetheringEventCallback tetherCallback =
2966 new TetheringEventCallback() {
2967 @Override
2968 public void onUpstreamChanged(@Nullable Network network) {
2969 callback.onUpstreamChanged(network);
2970 }
2971 };
2972
2973 synchronized (mTetheringEventCallbacks) {
2974 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002975 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002976 }
2977 }
2978
2979 /**
2980 * Remove tethering event callback previously registered with
2981 * {@link #registerTetheringEventCallback}.
2982 *
2983 * @param callback previously registered callback.
2984 *
2985 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
2986 * @hide
2987 */
2988 @SystemApi
2989 @Deprecated
2990 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2991 public void unregisterTetheringEventCallback(
2992 @NonNull final OnTetheringEventCallback callback) {
2993 Objects.requireNonNull(callback, "The callback must be non-null");
2994 synchronized (mTetheringEventCallbacks) {
2995 final TetheringEventCallback tetherCallback =
2996 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002997 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002998 }
2999 }
3000
3001
3002 /**
3003 * Get the list of regular expressions that define any tetherable
3004 * USB network interfaces. If USB tethering is not supported by the
3005 * device, this list should be empty.
3006 *
3007 * @return an array of 0 or more regular expression Strings defining
3008 * what interfaces are considered tetherable usb interfaces.
3009 *
3010 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3011 * {@hide}
3012 */
3013 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3014 @UnsupportedAppUsage
3015 @Deprecated
3016 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003017 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003018 }
3019
3020 /**
3021 * Get the list of regular expressions that define any tetherable
3022 * Wifi network interfaces. If Wifi tethering is not supported by the
3023 * device, this list should be empty.
3024 *
3025 * @return an array of 0 or more regular expression Strings defining
3026 * what interfaces are considered tetherable wifi interfaces.
3027 *
3028 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3029 * {@hide}
3030 */
3031 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3032 @UnsupportedAppUsage
3033 @Deprecated
3034 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003035 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003036 }
3037
3038 /**
3039 * Get the list of regular expressions that define any tetherable
3040 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3041 * device, this list should be empty.
3042 *
3043 * @return an array of 0 or more regular expression Strings defining
3044 * what interfaces are considered tetherable bluetooth interfaces.
3045 *
3046 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3047 *TetheringManager.TetheringInterfaceRegexps)} instead.
3048 * {@hide}
3049 */
3050 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3051 @UnsupportedAppUsage
3052 @Deprecated
3053 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003054 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003055 }
3056
3057 /**
3058 * Attempt to both alter the mode of USB and Tethering of USB. A
3059 * utility method to deal with some of the complexity of USB - will
3060 * attempt to switch to Rndis and subsequently tether the resulting
3061 * interface on {@code true} or turn off tethering and switch off
3062 * Rndis on {@code false}.
3063 *
3064 * <p>This method requires the caller to hold either the
3065 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3066 * or the ability to modify system settings as determined by
3067 * {@link android.provider.Settings.System#canWrite}.</p>
3068 *
3069 * @param enable a boolean - {@code true} to enable tethering
3070 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3071 * @deprecated Use {@link TetheringManager#startTethering} instead
3072 *
3073 * {@hide}
3074 */
3075 @UnsupportedAppUsage
3076 @Deprecated
3077 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003078 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003079 }
3080
3081 /**
3082 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3083 * {@hide}
3084 */
3085 @SystemApi
3086 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003087 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003088 /**
3089 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3090 * {@hide}
3091 */
3092 @Deprecated
3093 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3094 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3095 /**
3096 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3097 * {@hide}
3098 */
3099 @Deprecated
3100 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3101 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3102 /**
3103 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3104 * {@hide}
3105 */
3106 @Deprecated
3107 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3108 /**
3109 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3110 * {@hide}
3111 */
3112 @Deprecated
3113 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3114 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3115 /**
3116 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3117 * {@hide}
3118 */
3119 @Deprecated
3120 public static final int TETHER_ERROR_MASTER_ERROR =
3121 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3122 /**
3123 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3124 * {@hide}
3125 */
3126 @Deprecated
3127 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3128 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3129 /**
3130 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3131 * {@hide}
3132 */
3133 @Deprecated
3134 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3135 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3136 /**
3137 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3138 * {@hide}
3139 */
3140 @Deprecated
3141 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3142 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3143 /**
3144 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3145 * {@hide}
3146 */
3147 @Deprecated
3148 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3149 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3150 /**
3151 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3152 * {@hide}
3153 */
3154 @Deprecated
3155 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3156 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3157 /**
3158 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3159 * {@hide}
3160 */
3161 @SystemApi
3162 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003163 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003164 /**
3165 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3166 * {@hide}
3167 */
3168 @Deprecated
3169 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3170 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3171 /**
3172 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3173 * {@hide}
3174 */
3175 @SystemApi
3176 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003177 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003178
3179 /**
3180 * Get a more detailed error code after a Tethering or Untethering
3181 * request asynchronously failed.
3182 *
3183 * @param iface The name of the interface of interest
3184 * @return error The error code of the last error tethering or untethering the named
3185 * interface
3186 *
3187 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3188 * {@hide}
3189 */
3190 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3191 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3192 @Deprecated
3193 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003194 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003195 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3196 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3197 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3198 // instead.
3199 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3200 }
3201 return error;
3202 }
3203
3204 /** @hide */
3205 @Retention(RetentionPolicy.SOURCE)
3206 @IntDef(value = {
3207 TETHER_ERROR_NO_ERROR,
3208 TETHER_ERROR_PROVISION_FAILED,
3209 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3210 })
3211 public @interface EntitlementResultCode {
3212 }
3213
3214 /**
3215 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3216 * entitlement succeeded.
3217 *
3218 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3219 * @hide
3220 */
3221 @SystemApi
3222 @Deprecated
3223 public interface OnTetheringEntitlementResultListener {
3224 /**
3225 * Called to notify entitlement result.
3226 *
3227 * @param resultCode an int value of entitlement result. It may be one of
3228 * {@link #TETHER_ERROR_NO_ERROR},
3229 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3230 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3231 */
3232 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3233 }
3234
3235 /**
3236 * Get the last value of the entitlement check on this downstream. If the cached value is
3237 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3238 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3239 * guaranteed that the UI-based entitlement check will complete in any specific time period
3240 * and may in fact never complete. Any successful entitlement check the platform performs for
3241 * any reason will update the cached value.
3242 *
3243 * @param type the downstream type of tethering. Must be one of
3244 * {@link #TETHERING_WIFI},
3245 * {@link #TETHERING_USB}, or
3246 * {@link #TETHERING_BLUETOOTH}.
3247 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3248 * @param executor the executor on which callback will be invoked.
3249 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3250 * notify the caller of the result of entitlement check. The listener may be called zero
3251 * or one time.
3252 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3253 * {@hide}
3254 */
3255 @SystemApi
3256 @Deprecated
3257 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3258 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3259 @NonNull @CallbackExecutor Executor executor,
3260 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003261 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003262 ResultReceiver wrappedListener = new ResultReceiver(null) {
3263 @Override
3264 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003265 final long token = Binder.clearCallingIdentity();
3266 try {
3267 executor.execute(() -> {
3268 listener.onTetheringEntitlementResult(resultCode);
3269 });
3270 } finally {
3271 Binder.restoreCallingIdentity(token);
3272 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003273 }
3274 };
3275
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003276 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003277 showEntitlementUi);
3278 }
3279
3280 /**
3281 * Report network connectivity status. This is currently used only
3282 * to alter status bar UI.
3283 * <p>This method requires the caller to hold the permission
3284 * {@link android.Manifest.permission#STATUS_BAR}.
3285 *
3286 * @param networkType The type of network you want to report on
3287 * @param percentage The quality of the connection 0 is bad, 100 is good
3288 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3289 * {@hide}
3290 */
3291 public void reportInetCondition(int networkType, int percentage) {
3292 printStackTrace();
3293 try {
3294 mService.reportInetCondition(networkType, percentage);
3295 } catch (RemoteException e) {
3296 throw e.rethrowFromSystemServer();
3297 }
3298 }
3299
3300 /**
3301 * Report a problem network to the framework. This provides a hint to the system
3302 * that there might be connectivity problems on this network and may cause
3303 * the framework to re-evaluate network connectivity and/or switch to another
3304 * network.
3305 *
3306 * @param network The {@link Network} the application was attempting to use
3307 * or {@code null} to indicate the current default network.
3308 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3309 * working and non-working connectivity.
3310 */
3311 @Deprecated
3312 public void reportBadNetwork(@Nullable Network network) {
3313 printStackTrace();
3314 try {
3315 // One of these will be ignored because it matches system's current state.
3316 // The other will trigger the necessary reevaluation.
3317 mService.reportNetworkConnectivity(network, true);
3318 mService.reportNetworkConnectivity(network, false);
3319 } catch (RemoteException e) {
3320 throw e.rethrowFromSystemServer();
3321 }
3322 }
3323
3324 /**
3325 * Report to the framework whether a network has working connectivity.
3326 * This provides a hint to the system that a particular network is providing
3327 * working connectivity or not. In response the framework may re-evaluate
3328 * the network's connectivity and might take further action thereafter.
3329 *
3330 * @param network The {@link Network} the application was attempting to use
3331 * or {@code null} to indicate the current default network.
3332 * @param hasConnectivity {@code true} if the application was able to successfully access the
3333 * Internet using {@code network} or {@code false} if not.
3334 */
3335 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3336 printStackTrace();
3337 try {
3338 mService.reportNetworkConnectivity(network, hasConnectivity);
3339 } catch (RemoteException e) {
3340 throw e.rethrowFromSystemServer();
3341 }
3342 }
3343
3344 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003345 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003346 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003347 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3348 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3349 * accessing any network, regardless of what the settings for that network are.
3350 *
3351 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3352 * proxy is likely to break networking on multiple networks. This method is only meant
3353 * for device policy clients looking to do general internal filtering or similar use cases.
3354 *
3355 * {@see #getGlobalProxy}
3356 * {@see LinkProperties#getHttpProxy}
3357 *
3358 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3359 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003360 * @hide
3361 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003362 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003363 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003364 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003365 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003366 try {
3367 mService.setGlobalProxy(p);
3368 } catch (RemoteException e) {
3369 throw e.rethrowFromSystemServer();
3370 }
3371 }
3372
3373 /**
3374 * Retrieve any network-independent global HTTP proxy.
3375 *
3376 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3377 * if no global HTTP proxy is set.
3378 * @hide
3379 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003380 @SystemApi(client = MODULE_LIBRARIES)
3381 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003382 public ProxyInfo getGlobalProxy() {
3383 try {
3384 return mService.getGlobalProxy();
3385 } catch (RemoteException e) {
3386 throw e.rethrowFromSystemServer();
3387 }
3388 }
3389
3390 /**
3391 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3392 * network-specific HTTP proxy. If {@code network} is null, the
3393 * network-specific proxy returned is the proxy of the default active
3394 * network.
3395 *
3396 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3397 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3398 * or when {@code network} is {@code null},
3399 * the {@code ProxyInfo} for the default active network. Returns
3400 * {@code null} when no proxy applies or the caller doesn't have
3401 * permission to use {@code network}.
3402 * @hide
3403 */
3404 public ProxyInfo getProxyForNetwork(Network network) {
3405 try {
3406 return mService.getProxyForNetwork(network);
3407 } catch (RemoteException e) {
3408 throw e.rethrowFromSystemServer();
3409 }
3410 }
3411
3412 /**
3413 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3414 * otherwise if this process is bound to a {@link Network} using
3415 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3416 * the default network's proxy is returned.
3417 *
3418 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3419 * HTTP proxy is active.
3420 */
3421 @Nullable
3422 public ProxyInfo getDefaultProxy() {
3423 return getProxyForNetwork(getBoundNetworkForProcess());
3424 }
3425
3426 /**
3427 * Returns true if the hardware supports the given network type
3428 * else it returns false. This doesn't indicate we have coverage
3429 * or are authorized onto a network, just whether or not the
3430 * hardware supports it. For example a GSM phone without a SIM
3431 * should still return {@code true} for mobile data, but a wifi only
3432 * tablet would return {@code false}.
3433 *
3434 * @param networkType The network type we'd like to check
3435 * @return {@code true} if supported, else {@code false}
3436 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3437 * @hide
3438 */
3439 @Deprecated
3440 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3441 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3442 public boolean isNetworkSupported(int networkType) {
3443 try {
3444 return mService.isNetworkSupported(networkType);
3445 } catch (RemoteException e) {
3446 throw e.rethrowFromSystemServer();
3447 }
3448 }
3449
3450 /**
3451 * Returns if the currently active data network is metered. A network is
3452 * classified as metered when the user is sensitive to heavy data usage on
3453 * that connection due to monetary costs, data limitations or
3454 * battery/performance issues. You should check this before doing large
3455 * data transfers, and warn the user or delay the operation until another
3456 * network is available.
3457 *
3458 * @return {@code true} if large transfers should be avoided, otherwise
3459 * {@code false}.
3460 */
3461 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3462 public boolean isActiveNetworkMetered() {
3463 try {
3464 return mService.isActiveNetworkMetered();
3465 } catch (RemoteException e) {
3466 throw e.rethrowFromSystemServer();
3467 }
3468 }
3469
3470 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003471 * Set sign in error notification to visible or invisible
3472 *
3473 * @hide
3474 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3475 */
3476 @Deprecated
3477 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3478 String action) {
3479 try {
3480 mService.setProvisioningNotificationVisible(visible, networkType, action);
3481 } catch (RemoteException e) {
3482 throw e.rethrowFromSystemServer();
3483 }
3484 }
3485
3486 /**
3487 * Set the value for enabling/disabling airplane mode
3488 *
3489 * @param enable whether to enable airplane mode or not
3490 *
3491 * @hide
3492 */
3493 @RequiresPermission(anyOf = {
3494 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3495 android.Manifest.permission.NETWORK_SETTINGS,
3496 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3497 android.Manifest.permission.NETWORK_STACK})
3498 @SystemApi
3499 public void setAirplaneMode(boolean enable) {
3500 try {
3501 mService.setAirplaneMode(enable);
3502 } catch (RemoteException e) {
3503 throw e.rethrowFromSystemServer();
3504 }
3505 }
3506
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003507 /**
3508 * Registers the specified {@link NetworkProvider}.
3509 * Each listener must only be registered once. The listener can be unregistered with
3510 * {@link #unregisterNetworkProvider}.
3511 *
3512 * @param provider the provider to register
3513 * @return the ID of the provider. This ID must be used by the provider when registering
3514 * {@link android.net.NetworkAgent}s.
3515 * @hide
3516 */
3517 @SystemApi
3518 @RequiresPermission(anyOf = {
3519 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3520 android.Manifest.permission.NETWORK_FACTORY})
3521 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3522 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3523 throw new IllegalStateException("NetworkProviders can only be registered once");
3524 }
3525
3526 try {
3527 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3528 provider.getName());
3529 provider.setProviderId(providerId);
3530 } catch (RemoteException e) {
3531 throw e.rethrowFromSystemServer();
3532 }
3533 return provider.getProviderId();
3534 }
3535
3536 /**
3537 * Unregisters the specified NetworkProvider.
3538 *
3539 * @param provider the provider to unregister
3540 * @hide
3541 */
3542 @SystemApi
3543 @RequiresPermission(anyOf = {
3544 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3545 android.Manifest.permission.NETWORK_FACTORY})
3546 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3547 try {
3548 mService.unregisterNetworkProvider(provider.getMessenger());
3549 } catch (RemoteException e) {
3550 throw e.rethrowFromSystemServer();
3551 }
3552 provider.setProviderId(NetworkProvider.ID_NONE);
3553 }
3554
Chalard Jeand1b498b2021-01-05 08:40:09 +09003555 /**
3556 * Register or update a network offer with ConnectivityService.
3557 *
3558 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003559 * them to networking requests made by apps or the system. A callback identifies an offer
3560 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3561 * score and the capabilities of the network it might be able to bring up ; these act as
3562 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003563 * provider.
3564 *
3565 * The provider is under no obligation to be able to bring up the network it offers at any
3566 * given time. Instead, this mechanism is meant to limit requests received by providers
3567 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3568 * the quality of the network satisfying a given request to their own offer.
3569 *
3570 * An offer can be updated by calling this again with the same callback object. This is
3571 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3572 * provider with the changes caused by the changes in the offer.
3573 *
3574 * @param provider The provider making this offer.
3575 * @param score The prospective score of the network.
3576 * @param caps The prospective capabilities of the network.
3577 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003578 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003579 */
3580 @RequiresPermission(anyOf = {
3581 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3582 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003583 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003584 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3585 @NonNull final INetworkOfferCallback callback) {
3586 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003587 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003588 Objects.requireNonNull(score, "null score"),
3589 Objects.requireNonNull(caps, "null caps"),
3590 Objects.requireNonNull(callback, "null callback"));
3591 } catch (RemoteException e) {
3592 throw e.rethrowFromSystemServer();
3593 }
3594 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003595
Chalard Jeand1b498b2021-01-05 08:40:09 +09003596 /**
3597 * Withdraw a network offer made with {@link #offerNetwork}.
3598 *
3599 * @param callback The callback passed at registration time. This must be the same object
3600 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003601 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003602 */
3603 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3604 try {
3605 mService.unofferNetwork(Objects.requireNonNull(callback));
3606 } catch (RemoteException e) {
3607 throw e.rethrowFromSystemServer();
3608 }
3609 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003610 /** @hide exposed via the NetworkProvider class. */
3611 @RequiresPermission(anyOf = {
3612 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3613 android.Manifest.permission.NETWORK_FACTORY})
3614 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3615 try {
3616 mService.declareNetworkRequestUnfulfillable(request);
3617 } catch (RemoteException e) {
3618 throw e.rethrowFromSystemServer();
3619 }
3620 }
3621
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003622 /**
3623 * @hide
3624 * Register a NetworkAgent with ConnectivityService.
3625 * @return Network corresponding to NetworkAgent.
3626 */
3627 @RequiresPermission(anyOf = {
3628 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3629 android.Manifest.permission.NETWORK_FACTORY})
3630 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003631 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3632 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003633 try {
3634 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3635 } catch (RemoteException e) {
3636 throw e.rethrowFromSystemServer();
3637 }
3638 }
3639
3640 /**
3641 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3642 * changes. Should be extended by applications wanting notifications.
3643 *
3644 * A {@code NetworkCallback} is registered by calling
3645 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3646 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3647 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3648 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3649 * A {@code NetworkCallback} should be registered at most once at any time.
3650 * A {@code NetworkCallback} that has been unregistered can be registered again.
3651 */
3652 public static class NetworkCallback {
3653 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003654 * No flags associated with this callback.
3655 * @hide
3656 */
3657 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003658
Roshan Piuse08bc182020-12-22 15:10:42 -08003659 /**
lucaslinc582d502022-01-27 09:07:00 +08003660 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3661 *
3662 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3663 * Prior to Android 12, this information is always returned to apps holding the appropriate
3664 * permission, possibly noting that the app has used location.
3665 * <p>In Android 12 and above, by default the sent objects do not contain any location
3666 * information, even if the app holds the necessary permissions, and the system does not
3667 * take note of location usage by the app. Apps can request that location information is
3668 * included, in which case the system will check location permission and the location
3669 * toggle state, and take note of location usage by the app if any such information is
3670 * returned.
3671 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003672 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3673 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3674 * <p>
3675 * These include:
3676 * <li> Some transport info instances (retrieved via
3677 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3678 * contain location sensitive information.
3679 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003680 * sensitive for wifi suggestor apps (i.e using
3681 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003682 * </p>
3683 * <p>
3684 * Note:
3685 * <li> Retrieving this location sensitive information (subject to app's location
3686 * permissions) will be noted by system. </li>
3687 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003688 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003689 */
Roshan Pius189d0092021-03-11 21:16:44 -08003690 // Note: Some existing fields which are location sensitive may still be included without
3691 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003692 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3693
3694 /** @hide */
3695 @Retention(RetentionPolicy.SOURCE)
3696 @IntDef(flag = true, prefix = "FLAG_", value = {
3697 FLAG_NONE,
3698 FLAG_INCLUDE_LOCATION_INFO
3699 })
3700 public @interface Flag { }
3701
3702 /**
3703 * All the valid flags for error checking.
3704 */
3705 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3706
3707 public NetworkCallback() {
3708 this(FLAG_NONE);
3709 }
3710
3711 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003712 if ((flags & VALID_FLAGS) != flags) {
3713 throw new IllegalArgumentException("Invalid flags");
3714 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003715 mFlags = flags;
3716 }
3717
3718 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003719 * Called when the framework connects to a new network to evaluate whether it satisfies this
3720 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3721 * callback. There is no guarantee that this new network will satisfy any requests, or that
3722 * the network will stay connected for longer than the time necessary to evaluate it.
3723 * <p>
3724 * Most applications <b>should not</b> act on this callback, and should instead use
3725 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3726 * the framework in properly evaluating the network &mdash; for example, an application that
3727 * can automatically log in to a captive portal without user intervention.
3728 *
3729 * @param network The {@link Network} of the network that is being evaluated.
3730 *
3731 * @hide
3732 */
3733 public void onPreCheck(@NonNull Network network) {}
3734
3735 /**
3736 * Called when the framework connects and has declared a new network ready for use.
3737 * This callback may be called more than once if the {@link Network} that is
3738 * satisfying the request changes.
3739 *
3740 * @param network The {@link Network} of the satisfying network.
3741 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3742 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3743 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3744 * @hide
3745 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003746 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003747 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003748 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003749 // Internally only this method is called when a new network is available, and
3750 // it calls the callback in the same way and order that older versions used
3751 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003752 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3753 onBlockedStatusChanged(network, blocked);
3754 }
3755
3756 /**
3757 * Legacy variant of onAvailable that takes a boolean blocked reason.
3758 *
3759 * This method has never been public API, but it's not final, so there may be apps that
3760 * implemented it and rely on it being called. Do our best not to break them.
3761 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3762 * this method is called. There does not seem to be a way to avoid this.
3763 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3764 *
3765 * @hide
3766 */
3767 public void onAvailable(@NonNull Network network,
3768 @NonNull NetworkCapabilities networkCapabilities,
3769 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003770 onAvailable(network);
3771 if (!networkCapabilities.hasCapability(
3772 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3773 onNetworkSuspended(network);
3774 }
3775 onCapabilitiesChanged(network, networkCapabilities);
3776 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003777 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003778 }
3779
3780 /**
3781 * Called when the framework connects and has declared a new network ready for use.
3782 *
3783 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3784 * be available at the same time, and onAvailable will be called for each of these as they
3785 * appear.
3786 *
3787 * <p>For callbacks registered with {@link #requestNetwork} and
3788 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3789 * is the new best network for this request and is now tracked by this callback ; this
3790 * callback will no longer receive method calls about other networks that may have been
3791 * passed to this method previously. The previously-best network may have disconnected, or
3792 * it may still be around and the newly-best network may simply be better.
3793 *
3794 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3795 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3796 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3797 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3798 *
3799 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3800 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3801 * this callback as this is prone to race conditions (there is no guarantee the objects
3802 * returned by these methods will be current). Instead, wait for a call to
3803 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3804 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3805 * to be well-ordered with respect to other callbacks.
3806 *
3807 * @param network The {@link Network} of the satisfying network.
3808 */
3809 public void onAvailable(@NonNull Network network) {}
3810
3811 /**
3812 * Called when the network is about to be lost, typically because there are no outstanding
3813 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3814 * with the new replacement network for graceful handover. This method is not guaranteed
3815 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3816 * network is suddenly disconnected.
3817 *
3818 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3819 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3820 * this callback as this is prone to race conditions ; calling these methods while in a
3821 * callback may return an outdated or even a null object.
3822 *
3823 * @param network The {@link Network} that is about to be lost.
3824 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3825 * connected for graceful handover; note that the network may still
3826 * suffer a hard loss at any time.
3827 */
3828 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3829
3830 /**
3831 * Called when a network disconnects or otherwise no longer satisfies this request or
3832 * callback.
3833 *
3834 * <p>If the callback was registered with requestNetwork() or
3835 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3836 * returned by onAvailable() when that network is lost and no other network satisfies
3837 * the criteria of the request.
3838 *
3839 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3840 * each network which no longer satisfies the criteria of the callback.
3841 *
3842 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3843 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3844 * this callback as this is prone to race conditions ; calling these methods while in a
3845 * callback may return an outdated or even a null object.
3846 *
3847 * @param network The {@link Network} lost.
3848 */
3849 public void onLost(@NonNull Network network) {}
3850
3851 /**
3852 * Called if no network is found within the timeout time specified in
3853 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3854 * requested network request cannot be fulfilled (whether or not a timeout was
3855 * specified). When this callback is invoked the associated
3856 * {@link NetworkRequest} will have already been removed and released, as if
3857 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3858 */
3859 public void onUnavailable() {}
3860
3861 /**
3862 * Called when the network corresponding to this request changes capabilities but still
3863 * satisfies the requested criteria.
3864 *
3865 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3866 * to be called immediately after {@link #onAvailable}.
3867 *
3868 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3869 * ConnectivityManager methods in this callback as this is prone to race conditions :
3870 * calling these methods while in a callback may return an outdated or even a null object.
3871 *
3872 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003873 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003874 * network.
3875 */
3876 public void onCapabilitiesChanged(@NonNull Network network,
3877 @NonNull NetworkCapabilities networkCapabilities) {}
3878
3879 /**
3880 * Called when the network corresponding to this request changes {@link LinkProperties}.
3881 *
3882 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3883 * to be called immediately after {@link #onAvailable}.
3884 *
3885 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3886 * ConnectivityManager methods in this callback as this is prone to race conditions :
3887 * calling these methods while in a callback may return an outdated or even a null object.
3888 *
3889 * @param network The {@link Network} whose link properties have changed.
3890 * @param linkProperties The new {@link LinkProperties} for this network.
3891 */
3892 public void onLinkPropertiesChanged(@NonNull Network network,
3893 @NonNull LinkProperties linkProperties) {}
3894
3895 /**
3896 * Called when the network the framework connected to for this request suspends data
3897 * transmission temporarily.
3898 *
3899 * <p>This generally means that while the TCP connections are still live temporarily
3900 * network data fails to transfer. To give a specific example, this is used on cellular
3901 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3902 * means read operations on sockets on this network will block once the buffers are
3903 * drained, and write operations will block once the buffers are full.
3904 *
3905 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3906 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3907 * this callback as this is prone to race conditions (there is no guarantee the objects
3908 * returned by these methods will be current).
3909 *
3910 * @hide
3911 */
3912 public void onNetworkSuspended(@NonNull Network network) {}
3913
3914 /**
3915 * Called when the network the framework connected to for this request
3916 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3917 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3918
3919 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3920 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3921 * this callback as this is prone to race conditions : calling these methods while in a
3922 * callback may return an outdated or even a null object.
3923 *
3924 * @hide
3925 */
3926 public void onNetworkResumed(@NonNull Network network) {}
3927
3928 /**
3929 * Called when access to the specified network is blocked or unblocked.
3930 *
3931 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3932 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3933 * this callback as this is prone to race conditions : calling these methods while in a
3934 * callback may return an outdated or even a null object.
3935 *
3936 * @param network The {@link Network} whose blocked status has changed.
3937 * @param blocked The blocked status of this {@link Network}.
3938 */
3939 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3940
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003941 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09003942 * Called when access to the specified network is blocked or unblocked, or the reason for
3943 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003944 *
3945 * If a NetworkCallback object implements this method,
3946 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3947 *
3948 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3949 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3950 * this callback as this is prone to race conditions : calling these methods while in a
3951 * callback may return an outdated or even a null object.
3952 *
3953 * @param network The {@link Network} whose blocked status has changed.
3954 * @param blocked The blocked status of this {@link Network}.
3955 * @hide
3956 */
3957 @SystemApi(client = MODULE_LIBRARIES)
3958 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3959 onBlockedStatusChanged(network, blocked != 0);
3960 }
3961
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003962 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08003963 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003964 }
3965
3966 /**
3967 * Constant error codes used by ConnectivityService to communicate about failures and errors
3968 * across a Binder boundary.
3969 * @hide
3970 */
3971 public interface Errors {
3972 int TOO_MANY_REQUESTS = 1;
3973 }
3974
3975 /** @hide */
3976 public static class TooManyRequestsException extends RuntimeException {}
3977
3978 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3979 switch (e.errorCode) {
3980 case Errors.TOO_MANY_REQUESTS:
3981 return new TooManyRequestsException();
3982 default:
3983 Log.w(TAG, "Unknown service error code " + e.errorCode);
3984 return new RuntimeException(e);
3985 }
3986 }
3987
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003988 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003989 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003990 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003991 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003992 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003993 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003994 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003995 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003996 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003997 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003998 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003999 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004000 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004001 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004002 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004003 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004004 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004005 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004006 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004007 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004008 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004009 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004010
4011 /** @hide */
4012 public static String getCallbackName(int whichCallback) {
4013 switch (whichCallback) {
4014 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4015 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4016 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4017 case CALLBACK_LOST: return "CALLBACK_LOST";
4018 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4019 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4020 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4021 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4022 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4023 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4024 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4025 default:
4026 return Integer.toString(whichCallback);
4027 }
4028 }
4029
4030 private class CallbackHandler extends Handler {
4031 private static final String TAG = "ConnectivityManager.CallbackHandler";
4032 private static final boolean DBG = false;
4033
4034 CallbackHandler(Looper looper) {
4035 super(looper);
4036 }
4037
4038 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004039 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004040 }
4041
4042 @Override
4043 public void handleMessage(Message message) {
4044 if (message.what == EXPIRE_LEGACY_REQUEST) {
4045 expireRequest((NetworkCapabilities) message.obj, message.arg1);
4046 return;
4047 }
4048
4049 final NetworkRequest request = getObject(message, NetworkRequest.class);
4050 final Network network = getObject(message, Network.class);
4051 final NetworkCallback callback;
4052 synchronized (sCallbacks) {
4053 callback = sCallbacks.get(request);
4054 if (callback == null) {
4055 Log.w(TAG,
4056 "callback not found for " + getCallbackName(message.what) + " message");
4057 return;
4058 }
4059 if (message.what == CALLBACK_UNAVAIL) {
4060 sCallbacks.remove(request);
4061 callback.networkRequest = ALREADY_UNREGISTERED;
4062 }
4063 }
4064 if (DBG) {
4065 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4066 }
4067
4068 switch (message.what) {
4069 case CALLBACK_PRECHECK: {
4070 callback.onPreCheck(network);
4071 break;
4072 }
4073 case CALLBACK_AVAILABLE: {
4074 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4075 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004076 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004077 break;
4078 }
4079 case CALLBACK_LOSING: {
4080 callback.onLosing(network, message.arg1);
4081 break;
4082 }
4083 case CALLBACK_LOST: {
4084 callback.onLost(network);
4085 break;
4086 }
4087 case CALLBACK_UNAVAIL: {
4088 callback.onUnavailable();
4089 break;
4090 }
4091 case CALLBACK_CAP_CHANGED: {
4092 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4093 callback.onCapabilitiesChanged(network, cap);
4094 break;
4095 }
4096 case CALLBACK_IP_CHANGED: {
4097 LinkProperties lp = getObject(message, LinkProperties.class);
4098 callback.onLinkPropertiesChanged(network, lp);
4099 break;
4100 }
4101 case CALLBACK_SUSPENDED: {
4102 callback.onNetworkSuspended(network);
4103 break;
4104 }
4105 case CALLBACK_RESUMED: {
4106 callback.onNetworkResumed(network);
4107 break;
4108 }
4109 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004110 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004111 }
4112 }
4113 }
4114
4115 private <T> T getObject(Message msg, Class<T> c) {
4116 return (T) msg.getData().getParcelable(c.getSimpleName());
4117 }
4118 }
4119
4120 private CallbackHandler getDefaultHandler() {
4121 synchronized (sCallbacks) {
4122 if (sCallbackHandler == null) {
4123 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4124 }
4125 return sCallbackHandler;
4126 }
4127 }
4128
4129 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4130 private static CallbackHandler sCallbackHandler;
4131
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004132 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4133 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4134 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004135 printStackTrace();
4136 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004137 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4138 throw new IllegalArgumentException("null NetworkCapabilities");
4139 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004140 final NetworkRequest request;
4141 final String callingPackageName = mContext.getOpPackageName();
4142 try {
4143 synchronized(sCallbacks) {
4144 if (callback.networkRequest != null
4145 && callback.networkRequest != ALREADY_UNREGISTERED) {
4146 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4147 // and requests (http://b/20701525).
4148 Log.e(TAG, "NetworkCallback was already registered");
4149 }
4150 Messenger messenger = new Messenger(handler);
4151 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004152 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004153 if (reqType == LISTEN) {
4154 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004155 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004156 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004157 } else {
4158 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004159 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4160 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004161 }
4162 if (request != null) {
4163 sCallbacks.put(request, callback);
4164 }
4165 callback.networkRequest = request;
4166 }
4167 } catch (RemoteException e) {
4168 throw e.rethrowFromSystemServer();
4169 } catch (ServiceSpecificException e) {
4170 throw convertServiceException(e);
4171 }
4172 return request;
4173 }
4174
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004175 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4176 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4177 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4178 legacyType, handler);
4179 }
4180
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004181 /**
4182 * Helper function to request a network with a particular legacy type.
4183 *
4184 * This API is only for use in internal system code that requests networks with legacy type and
4185 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4186 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4187 *
4188 * @param request {@link NetworkRequest} describing this request.
4189 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4190 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4191 * be a positive value (i.e. >0).
4192 * @param legacyType to specify the network type(#TYPE_*).
4193 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4194 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4195 * the callback must not be shared - it uniquely specifies this request.
4196 *
4197 * @hide
4198 */
4199 @SystemApi
4200 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4201 public void requestNetwork(@NonNull NetworkRequest request,
4202 int timeoutMs, int legacyType, @NonNull Handler handler,
4203 @NonNull NetworkCallback networkCallback) {
4204 if (legacyType == TYPE_NONE) {
4205 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4206 }
4207 CallbackHandler cbHandler = new CallbackHandler(handler);
4208 NetworkCapabilities nc = request.networkCapabilities;
4209 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4210 }
4211
4212 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004213 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004214 *
4215 * <p>This method will attempt to find the best network that matches the passed
4216 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4217 * criteria. The platform will evaluate which network is the best at its own discretion.
4218 * Throughput, latency, cost per byte, policy, user preference and other considerations
4219 * may be factored in the decision of what is considered the best network.
4220 *
4221 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4222 * matching this request, while always attempting to match the request to a better network if
4223 * possible. If a better match is found, the platform will switch this request to the now-best
4224 * network and inform the app of the newly best network by invoking
4225 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4226 * will not try to maintain any other network than the best one currently matching the request:
4227 * a network not matching any network request may be disconnected at any time.
4228 *
4229 * <p>For example, an application could use this method to obtain a connected cellular network
4230 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4231 * radio to consume additional power. Or, an application could inform the system that it wants
4232 * a network supporting sending MMSes and have the system let it know about the currently best
4233 * MMS-supporting network through the provided {@link NetworkCallback}.
4234 *
4235 * <p>The status of the request can be followed by listening to the various callbacks described
4236 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4237 * used to direct traffic to the network (although accessing some networks may be subject to
4238 * holding specific permissions). Callers will learn about the specific characteristics of the
4239 * network through
4240 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4241 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4242 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4243 * matching the request at any given time; therefore when a better network matching the request
4244 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4245 * with the new network after which no further updates are given about the previously-best
4246 * network, unless it becomes the best again at some later time. All callbacks are invoked
4247 * in order on the same thread, which by default is a thread created by the framework running
4248 * in the app.
4249 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4250 * callbacks are invoked.
4251 *
4252 * <p>This{@link NetworkRequest} will live until released via
4253 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4254 * which point the system may let go of the network at any time.
4255 *
4256 * <p>A version of this method which takes a timeout is
4257 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4258 * wait for a limited amount of time for the network to become unavailable.
4259 *
4260 * <p>It is presently unsupported to request a network with mutable
4261 * {@link NetworkCapabilities} such as
4262 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4263 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4264 * as these {@code NetworkCapabilities} represent states that a particular
4265 * network may never attain, and whether a network will attain these states
4266 * is unknown prior to bringing up the network so the framework does not
4267 * know how to go about satisfying a request with these capabilities.
4268 *
4269 * <p>This method requires the caller to hold either the
4270 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4271 * or the ability to modify system settings as determined by
4272 * {@link android.provider.Settings.System#canWrite}.</p>
4273 *
4274 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4275 * number of outstanding requests to 100 per app (identified by their UID), shared with
4276 * all variants of this method, of {@link #registerNetworkCallback} as well as
4277 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4278 * Requesting a network with this method will count toward this limit. If this limit is
4279 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4280 * make sure to unregister the callbacks with
4281 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4282 *
4283 * @param request {@link NetworkRequest} describing this request.
4284 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4285 * the callback must not be shared - it uniquely specifies this request.
4286 * The callback is invoked on the default internal Handler.
4287 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4288 * @throws SecurityException if missing the appropriate permissions.
4289 * @throws RuntimeException if the app already has too many callbacks registered.
4290 */
4291 public void requestNetwork(@NonNull NetworkRequest request,
4292 @NonNull NetworkCallback networkCallback) {
4293 requestNetwork(request, networkCallback, getDefaultHandler());
4294 }
4295
4296 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004297 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004298 *
4299 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4300 * but runs all the callbacks on the passed Handler.
4301 *
4302 * <p>This method has the same permission requirements as
4303 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4304 * and throws the same exceptions in the same conditions.
4305 *
4306 * @param request {@link NetworkRequest} describing this request.
4307 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4308 * the callback must not be shared - it uniquely specifies this request.
4309 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4310 */
4311 public void requestNetwork(@NonNull NetworkRequest request,
4312 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4313 CallbackHandler cbHandler = new CallbackHandler(handler);
4314 NetworkCapabilities nc = request.networkCapabilities;
4315 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4316 }
4317
4318 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004319 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004320 * by a timeout.
4321 *
4322 * This function behaves identically to the non-timed-out version
4323 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4324 * is not found within the given time (in milliseconds) the
4325 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4326 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4327 * not have to be released if timed-out (it is automatically released). Unregistering a
4328 * request that timed out is not an error.
4329 *
4330 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4331 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4332 * for that purpose. Calling this method will attempt to bring up the requested network.
4333 *
4334 * <p>This method has the same permission requirements as
4335 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4336 * and throws the same exceptions in the same conditions.
4337 *
4338 * @param request {@link NetworkRequest} describing this request.
4339 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4340 * the callback must not be shared - it uniquely specifies this request.
4341 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4342 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4343 * be a positive value (i.e. >0).
4344 */
4345 public void requestNetwork(@NonNull NetworkRequest request,
4346 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4347 checkTimeout(timeoutMs);
4348 NetworkCapabilities nc = request.networkCapabilities;
4349 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4350 getDefaultHandler());
4351 }
4352
4353 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004354 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004355 * by a timeout.
4356 *
4357 * This method behaves identically to
4358 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4359 * on the passed Handler.
4360 *
4361 * <p>This method has the same permission requirements as
4362 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4363 * and throws the same exceptions in the same conditions.
4364 *
4365 * @param request {@link NetworkRequest} describing this request.
4366 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4367 * the callback must not be shared - it uniquely specifies this request.
4368 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4369 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4370 * before {@link NetworkCallback#onUnavailable} is called.
4371 */
4372 public void requestNetwork(@NonNull NetworkRequest request,
4373 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4374 checkTimeout(timeoutMs);
4375 CallbackHandler cbHandler = new CallbackHandler(handler);
4376 NetworkCapabilities nc = request.networkCapabilities;
4377 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4378 }
4379
4380 /**
4381 * The lookup key for a {@link Network} object included with the intent after
4382 * successfully finding a network for the applications request. Retrieve it with
4383 * {@link android.content.Intent#getParcelableExtra(String)}.
4384 * <p>
4385 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4386 * then you must get a ConnectivityManager instance before doing so.
4387 */
4388 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4389
4390 /**
4391 * The lookup key for a {@link NetworkRequest} object included with the intent after
4392 * successfully finding a network for the applications request. Retrieve it with
4393 * {@link android.content.Intent#getParcelableExtra(String)}.
4394 */
4395 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4396
4397
4398 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004399 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004400 *
4401 * This function behaves identically to the version that takes a NetworkCallback, but instead
4402 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4403 * the request may outlive the calling application and get called back when a suitable
4404 * network is found.
4405 * <p>
4406 * The operation is an Intent broadcast that goes to a broadcast receiver that
4407 * you registered with {@link Context#registerReceiver} or through the
4408 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4409 * <p>
4410 * The operation Intent is delivered with two extras, a {@link Network} typed
4411 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4412 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4413 * the original requests parameters. It is important to create a new,
4414 * {@link NetworkCallback} based request before completing the processing of the
4415 * Intent to reserve the network or it will be released shortly after the Intent
4416 * is processed.
4417 * <p>
4418 * If there is already a request for this Intent registered (with the equality of
4419 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4420 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4421 * <p>
4422 * The request may be released normally by calling
4423 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4424 * <p>It is presently unsupported to request a network with either
4425 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4426 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4427 * as these {@code NetworkCapabilities} represent states that a particular
4428 * network may never attain, and whether a network will attain these states
4429 * is unknown prior to bringing up the network so the framework does not
4430 * know how to go about satisfying a request with these capabilities.
4431 *
4432 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4433 * number of outstanding requests to 100 per app (identified by their UID), shared with
4434 * all variants of this method, of {@link #registerNetworkCallback} as well as
4435 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4436 * Requesting a network with this method will count toward this limit. If this limit is
4437 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4438 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4439 * or {@link #releaseNetworkRequest(PendingIntent)}.
4440 *
4441 * <p>This method requires the caller to hold either the
4442 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4443 * or the ability to modify system settings as determined by
4444 * {@link android.provider.Settings.System#canWrite}.</p>
4445 *
4446 * @param request {@link NetworkRequest} describing this request.
4447 * @param operation Action to perform when the network is available (corresponds
4448 * to the {@link NetworkCallback#onAvailable} call. Typically
4449 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4450 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4451 * @throws SecurityException if missing the appropriate permissions.
4452 * @throws RuntimeException if the app already has too many callbacks registered.
4453 */
4454 public void requestNetwork(@NonNull NetworkRequest request,
4455 @NonNull PendingIntent operation) {
4456 printStackTrace();
4457 checkPendingIntentNotNull(operation);
4458 try {
4459 mService.pendingRequestForNetwork(
4460 request.networkCapabilities, operation, mContext.getOpPackageName(),
4461 getAttributionTag());
4462 } catch (RemoteException e) {
4463 throw e.rethrowFromSystemServer();
4464 } catch (ServiceSpecificException e) {
4465 throw convertServiceException(e);
4466 }
4467 }
4468
4469 /**
4470 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4471 * <p>
4472 * This method has the same behavior as
4473 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4474 * releasing network resources and disconnecting.
4475 *
4476 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4477 * PendingIntent passed to
4478 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4479 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4480 */
4481 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4482 printStackTrace();
4483 checkPendingIntentNotNull(operation);
4484 try {
4485 mService.releasePendingNetworkRequest(operation);
4486 } catch (RemoteException e) {
4487 throw e.rethrowFromSystemServer();
4488 }
4489 }
4490
4491 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004492 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004493 }
4494
4495 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004496 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004497 }
4498
4499 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004500 if (timeoutMs <= 0) {
4501 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4502 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004503 }
4504
4505 /**
4506 * Registers to receive notifications about all networks which satisfy the given
4507 * {@link NetworkRequest}. The callbacks will continue to be called until
4508 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4509 * called.
4510 *
4511 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4512 * number of outstanding requests to 100 per app (identified by their UID), shared with
4513 * all variants of this method, of {@link #requestNetwork} as well as
4514 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4515 * Requesting a network with this method will count toward this limit. If this limit is
4516 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4517 * make sure to unregister the callbacks with
4518 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4519 *
4520 * @param request {@link NetworkRequest} describing this request.
4521 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4522 * networks change state.
4523 * The callback is invoked on the default internal Handler.
4524 * @throws RuntimeException if the app already has too many callbacks registered.
4525 */
4526 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4527 public void registerNetworkCallback(@NonNull NetworkRequest request,
4528 @NonNull NetworkCallback networkCallback) {
4529 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4530 }
4531
4532 /**
4533 * Registers to receive notifications about all networks which satisfy the given
4534 * {@link NetworkRequest}. The callbacks will continue to be called until
4535 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4536 * called.
4537 *
4538 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4539 * number of outstanding requests to 100 per app (identified by their UID), shared with
4540 * all variants of this method, of {@link #requestNetwork} as well as
4541 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4542 * Requesting a network with this method will count toward this limit. If this limit is
4543 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4544 * make sure to unregister the callbacks with
4545 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4546 *
4547 *
4548 * @param request {@link NetworkRequest} describing this request.
4549 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4550 * networks change state.
4551 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4552 * @throws RuntimeException if the app already has too many callbacks registered.
4553 */
4554 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4555 public void registerNetworkCallback(@NonNull NetworkRequest request,
4556 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4557 CallbackHandler cbHandler = new CallbackHandler(handler);
4558 NetworkCapabilities nc = request.networkCapabilities;
4559 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4560 }
4561
4562 /**
4563 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4564 * {@link NetworkRequest}.
4565 *
4566 * This function behaves identically to the version that takes a NetworkCallback, but instead
4567 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4568 * the request may outlive the calling application and get called back when a suitable
4569 * network is found.
4570 * <p>
4571 * The operation is an Intent broadcast that goes to a broadcast receiver that
4572 * you registered with {@link Context#registerReceiver} or through the
4573 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4574 * <p>
4575 * The operation Intent is delivered with two extras, a {@link Network} typed
4576 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4577 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4578 * the original requests parameters.
4579 * <p>
4580 * If there is already a request for this Intent registered (with the equality of
4581 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4582 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4583 * <p>
4584 * The request may be released normally by calling
4585 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4586 *
4587 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4588 * number of outstanding requests to 100 per app (identified by their UID), shared with
4589 * all variants of this method, of {@link #requestNetwork} as well as
4590 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4591 * Requesting a network with this method will count toward this limit. If this limit is
4592 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4593 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4594 * or {@link #releaseNetworkRequest(PendingIntent)}.
4595 *
4596 * @param request {@link NetworkRequest} describing this request.
4597 * @param operation Action to perform when the network is available (corresponds
4598 * to the {@link NetworkCallback#onAvailable} call. Typically
4599 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4600 * @throws RuntimeException if the app already has too many callbacks registered.
4601 */
4602 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4603 public void registerNetworkCallback(@NonNull NetworkRequest request,
4604 @NonNull PendingIntent operation) {
4605 printStackTrace();
4606 checkPendingIntentNotNull(operation);
4607 try {
4608 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004609 request.networkCapabilities, operation, mContext.getOpPackageName(),
4610 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004611 } catch (RemoteException e) {
4612 throw e.rethrowFromSystemServer();
4613 } catch (ServiceSpecificException e) {
4614 throw convertServiceException(e);
4615 }
4616 }
4617
4618 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004619 * Registers to receive notifications about changes in the application's default network. This
4620 * may be a physical network or a virtual network, such as a VPN that applies to the
4621 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004622 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4623 *
4624 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4625 * number of outstanding requests to 100 per app (identified by their UID), shared with
4626 * all variants of this method, of {@link #requestNetwork} as well as
4627 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4628 * Requesting a network with this method will count toward this limit. If this limit is
4629 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4630 * make sure to unregister the callbacks with
4631 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4632 *
4633 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004634 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004635 * The callback is invoked on the default internal Handler.
4636 * @throws RuntimeException if the app already has too many callbacks registered.
4637 */
4638 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4639 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4640 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4641 }
4642
4643 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004644 * Registers to receive notifications about changes in the application's default network. This
4645 * may be a physical network or a virtual network, such as a VPN that applies to the
4646 * application. The callbacks will continue to be called until either the application exits or
4647 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4648 *
4649 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4650 * number of outstanding requests to 100 per app (identified by their UID), shared with
4651 * all variants of this method, of {@link #requestNetwork} as well as
4652 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4653 * Requesting a network with this method will count toward this limit. If this limit is
4654 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4655 * make sure to unregister the callbacks with
4656 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4657 *
4658 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4659 * application's default network changes.
4660 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4661 * @throws RuntimeException if the app already has too many callbacks registered.
4662 */
4663 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4664 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4665 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004666 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004667 }
4668
4669 /**
4670 * Registers to receive notifications about changes in the default network for the specified
4671 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4672 * UID. The callbacks will continue to be called until either the application exits or
4673 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4674 *
4675 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4676 * number of outstanding requests to 100 per app (identified by their UID), shared with
4677 * all variants of this method, of {@link #requestNetwork} as well as
4678 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4679 * Requesting a network with this method will count toward this limit. If this limit is
4680 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4681 * make sure to unregister the callbacks with
4682 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4683 *
4684 * @param uid the UID for which to track default network changes.
4685 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4686 * UID's default network changes.
4687 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4688 * @throws RuntimeException if the app already has too many callbacks registered.
4689 * @hide
4690 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004691 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004692 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4693 @RequiresPermission(anyOf = {
4694 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4695 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004696 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004697 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004698 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004699 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004700 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4701 }
4702
4703 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004704 * Registers to receive notifications about changes in the system default network. The callbacks
4705 * will continue to be called until either the application exits or
4706 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4707 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004708 * This method should not be used to determine networking state seen by applications, because in
4709 * many cases, most or even all application traffic may not use the default network directly,
4710 * and traffic from different applications may go on different networks by default. As an
4711 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4712 * and not onto the system default network. Applications or system components desiring to do
4713 * determine network state as seen by applications should use other methods such as
4714 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4715 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004716 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4717 * number of outstanding requests to 100 per app (identified by their UID), shared with
4718 * all variants of this method, of {@link #requestNetwork} as well as
4719 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4720 * Requesting a network with this method will count toward this limit. If this limit is
4721 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4722 * make sure to unregister the callbacks with
4723 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4724 *
4725 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4726 * system default network changes.
4727 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4728 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004729 *
4730 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004731 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004732 @SystemApi(client = MODULE_LIBRARIES)
4733 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4734 @RequiresPermission(anyOf = {
4735 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4736 android.Manifest.permission.NETWORK_SETTINGS})
4737 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004738 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004739 CallbackHandler cbHandler = new CallbackHandler(handler);
4740 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004741 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004742 }
4743
4744 /**
junyulaibd123062021-03-15 11:48:48 +08004745 * Registers to receive notifications about the best matching network which satisfy the given
4746 * {@link NetworkRequest}. The callbacks will continue to be called until
4747 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4748 * called.
4749 *
4750 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4751 * number of outstanding requests to 100 per app (identified by their UID), shared with
4752 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4753 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4754 * Requesting a network with this method will count toward this limit. If this limit is
4755 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4756 * make sure to unregister the callbacks with
4757 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4758 *
4759 *
4760 * @param request {@link NetworkRequest} describing this request.
4761 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4762 * networks change state.
4763 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4764 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004765 */
junyulai5a5c99b2021-03-05 15:51:17 +08004766 @SuppressLint("ExecutorRegistration")
4767 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4768 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4769 final NetworkCapabilities nc = request.networkCapabilities;
4770 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004771 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004772 }
4773
4774 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004775 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4776 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4777 * network connection for updated bandwidth information. The caller will be notified via
4778 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4779 * method assumes that the caller has previously called
4780 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4781 * changes.
4782 *
4783 * @param network {@link Network} specifying which network you're interested.
4784 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4785 */
4786 public boolean requestBandwidthUpdate(@NonNull Network network) {
4787 try {
4788 return mService.requestBandwidthUpdate(network);
4789 } catch (RemoteException e) {
4790 throw e.rethrowFromSystemServer();
4791 }
4792 }
4793
4794 /**
4795 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4796 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4797 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4798 * If the given {@code NetworkCallback} had previously been used with
4799 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4800 * will be disconnected.
4801 *
4802 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4803 * triggering it as soon as this call returns.
4804 *
4805 * @param networkCallback The {@link NetworkCallback} used when making the request.
4806 */
4807 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4808 printStackTrace();
4809 checkCallbackNotNull(networkCallback);
4810 final List<NetworkRequest> reqs = new ArrayList<>();
4811 // Find all requests associated to this callback and stop callback triggers immediately.
4812 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4813 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004814 if (networkCallback.networkRequest == null) {
4815 throw new IllegalArgumentException("NetworkCallback was not registered");
4816 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004817 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4818 Log.d(TAG, "NetworkCallback was already unregistered");
4819 return;
4820 }
4821 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4822 if (e.getValue() == networkCallback) {
4823 reqs.add(e.getKey());
4824 }
4825 }
4826 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4827 for (NetworkRequest r : reqs) {
4828 try {
4829 mService.releaseNetworkRequest(r);
4830 } catch (RemoteException e) {
4831 throw e.rethrowFromSystemServer();
4832 }
4833 // Only remove mapping if rpc was successful.
4834 sCallbacks.remove(r);
4835 }
4836 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4837 }
4838 }
4839
4840 /**
4841 * Unregisters a callback previously registered via
4842 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4843 *
4844 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4845 * PendingIntent passed to
4846 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4847 * Cannot be null.
4848 */
4849 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4850 releaseNetworkRequest(operation);
4851 }
4852
4853 /**
4854 * Informs the system whether it should switch to {@code network} regardless of whether it is
4855 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4856 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4857 * the system default network regardless of any other network that's currently connected. If
4858 * {@code always} is true, then the choice is remembered, so that the next time the user
4859 * connects to this network, the system will switch to it.
4860 *
4861 * @param network The network to accept.
4862 * @param accept Whether to accept the network even if unvalidated.
4863 * @param always Whether to remember this choice in the future.
4864 *
4865 * @hide
4866 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004867 @SystemApi(client = MODULE_LIBRARIES)
4868 @RequiresPermission(anyOf = {
4869 android.Manifest.permission.NETWORK_SETTINGS,
4870 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4871 android.Manifest.permission.NETWORK_STACK,
4872 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4873 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004874 try {
4875 mService.setAcceptUnvalidated(network, accept, always);
4876 } catch (RemoteException e) {
4877 throw e.rethrowFromSystemServer();
4878 }
4879 }
4880
4881 /**
4882 * Informs the system whether it should consider the network as validated even if it only has
4883 * partial connectivity. If {@code accept} is true, then the network will be considered as
4884 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4885 * is remembered, so that the next time the user connects to this network, the system will
4886 * switch to it.
4887 *
4888 * @param network The network to accept.
4889 * @param accept Whether to consider the network as validated even if it has partial
4890 * connectivity.
4891 * @param always Whether to remember this choice in the future.
4892 *
4893 * @hide
4894 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004895 @SystemApi(client = MODULE_LIBRARIES)
4896 @RequiresPermission(anyOf = {
4897 android.Manifest.permission.NETWORK_SETTINGS,
4898 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4899 android.Manifest.permission.NETWORK_STACK,
4900 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4901 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4902 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004903 try {
4904 mService.setAcceptPartialConnectivity(network, accept, always);
4905 } catch (RemoteException e) {
4906 throw e.rethrowFromSystemServer();
4907 }
4908 }
4909
4910 /**
4911 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4912 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4913 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4914 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4915 *
4916 * @param network The network to accept.
4917 *
4918 * @hide
4919 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004920 @SystemApi(client = MODULE_LIBRARIES)
4921 @RequiresPermission(anyOf = {
4922 android.Manifest.permission.NETWORK_SETTINGS,
4923 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4924 android.Manifest.permission.NETWORK_STACK,
4925 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4926 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004927 try {
4928 mService.setAvoidUnvalidated(network);
4929 } catch (RemoteException e) {
4930 throw e.rethrowFromSystemServer();
4931 }
4932 }
4933
4934 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004935 * Temporarily allow bad wifi to override {@code config_networkAvoidBadWifi} configuration.
4936 *
4937 * @param timeMs The expired current time. The value should be set within a limited time from
4938 * now.
4939 *
4940 * @hide
4941 */
4942 public void setTestAllowBadWifiUntil(long timeMs) {
4943 try {
4944 mService.setTestAllowBadWifiUntil(timeMs);
4945 } catch (RemoteException e) {
4946 throw e.rethrowFromSystemServer();
4947 }
4948 }
4949
4950 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004951 * Requests that the system open the captive portal app on the specified network.
4952 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004953 * <p>This is to be used on networks where a captive portal was detected, as per
4954 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4955 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004956 * @param network The network to log into.
4957 *
4958 * @hide
4959 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004960 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4961 @RequiresPermission(anyOf = {
4962 android.Manifest.permission.NETWORK_SETTINGS,
4963 android.Manifest.permission.NETWORK_STACK,
4964 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4965 })
4966 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004967 try {
4968 mService.startCaptivePortalApp(network);
4969 } catch (RemoteException e) {
4970 throw e.rethrowFromSystemServer();
4971 }
4972 }
4973
4974 /**
4975 * Requests that the system open the captive portal app with the specified extras.
4976 *
4977 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4978 * corresponding permission.
4979 * @param network Network on which the captive portal was detected.
4980 * @param appExtras Extras to include in the app start intent.
4981 * @hide
4982 */
4983 @SystemApi
4984 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4985 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4986 try {
4987 mService.startCaptivePortalAppInternal(network, appExtras);
4988 } catch (RemoteException e) {
4989 throw e.rethrowFromSystemServer();
4990 }
4991 }
4992
4993 /**
4994 * Determine whether the device is configured to avoid bad wifi.
4995 * @hide
4996 */
4997 @SystemApi
4998 @RequiresPermission(anyOf = {
4999 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5000 android.Manifest.permission.NETWORK_STACK})
5001 public boolean shouldAvoidBadWifi() {
5002 try {
5003 return mService.shouldAvoidBadWifi();
5004 } catch (RemoteException e) {
5005 throw e.rethrowFromSystemServer();
5006 }
5007 }
5008
5009 /**
5010 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5011 * time-sensitive user-facing operations when the system default network is temporarily
5012 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5013 * this method), and the operation should be infrequent to ensure that data usage is limited.
5014 *
5015 * An example of such an operation might be a time-sensitive foreground activity, such as a
5016 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5017 */
5018 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5019
5020 /**
5021 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5022 * a backup channel for traffic that is primarily going over another network.
5023 *
5024 * An example might be maintaining backup connections to peers or servers for the purpose of
5025 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5026 * on backup paths should be negligible compared to the traffic on the main path.
5027 */
5028 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5029
5030 /**
5031 * It is acceptable to use metered data to improve network latency and performance.
5032 */
5033 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5034
5035 /**
5036 * Return value to use for unmetered networks. On such networks we currently set all the flags
5037 * to true.
5038 * @hide
5039 */
5040 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5041 MULTIPATH_PREFERENCE_HANDOVER |
5042 MULTIPATH_PREFERENCE_RELIABILITY |
5043 MULTIPATH_PREFERENCE_PERFORMANCE;
5044
Aaron Huangcff22942021-05-27 16:31:26 +08005045 /** @hide */
5046 @Retention(RetentionPolicy.SOURCE)
5047 @IntDef(flag = true, value = {
5048 MULTIPATH_PREFERENCE_HANDOVER,
5049 MULTIPATH_PREFERENCE_RELIABILITY,
5050 MULTIPATH_PREFERENCE_PERFORMANCE,
5051 })
5052 public @interface MultipathPreference {
5053 }
5054
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005055 /**
5056 * Provides a hint to the calling application on whether it is desirable to use the
5057 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5058 * for multipath data transfer on this network when it is not the system default network.
5059 * Applications desiring to use multipath network protocols should call this method before
5060 * each such operation.
5061 *
5062 * @param network The network on which the application desires to use multipath data.
5063 * If {@code null}, this method will return the a preference that will generally
5064 * apply to metered networks.
5065 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
5066 */
5067 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5068 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5069 try {
5070 return mService.getMultipathPreference(network);
5071 } catch (RemoteException e) {
5072 throw e.rethrowFromSystemServer();
5073 }
5074 }
5075
5076 /**
5077 * Resets all connectivity manager settings back to factory defaults.
5078 * @hide
5079 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005080 @SystemApi(client = MODULE_LIBRARIES)
5081 @RequiresPermission(anyOf = {
5082 android.Manifest.permission.NETWORK_SETTINGS,
5083 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005084 public void factoryReset() {
5085 try {
5086 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005087 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005088 } catch (RemoteException e) {
5089 throw e.rethrowFromSystemServer();
5090 }
5091 }
5092
5093 /**
5094 * Binds the current process to {@code network}. All Sockets created in the future
5095 * (and not explicitly bound via a bound SocketFactory from
5096 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5097 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5098 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5099 * work and all host name resolutions will fail. This is by design so an application doesn't
5100 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5101 * To clear binding pass {@code null} for {@code network}. Using individually bound
5102 * Sockets created by Network.getSocketFactory().createSocket() and
5103 * performing network-specific host name resolutions via
5104 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5105 * {@code bindProcessToNetwork}.
5106 *
5107 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5108 * the current binding.
5109 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5110 */
5111 public boolean bindProcessToNetwork(@Nullable Network network) {
5112 // Forcing callers to call through non-static function ensures ConnectivityManager
5113 // instantiated.
5114 return setProcessDefaultNetwork(network);
5115 }
5116
5117 /**
5118 * Binds the current process to {@code network}. All Sockets created in the future
5119 * (and not explicitly bound via a bound SocketFactory from
5120 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5121 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5122 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5123 * work and all host name resolutions will fail. This is by design so an application doesn't
5124 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5125 * To clear binding pass {@code null} for {@code network}. Using individually bound
5126 * Sockets created by Network.getSocketFactory().createSocket() and
5127 * performing network-specific host name resolutions via
5128 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5129 * {@code setProcessDefaultNetwork}.
5130 *
5131 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5132 * the current binding.
5133 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5134 * @deprecated This function can throw {@link IllegalStateException}. Use
5135 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5136 * is a direct replacement.
5137 */
5138 @Deprecated
5139 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5140 int netId = (network == null) ? NETID_UNSET : network.netId;
5141 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5142
5143 if (netId != NETID_UNSET) {
5144 netId = network.getNetIdForResolv();
5145 }
5146
5147 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5148 return false;
5149 }
5150
5151 if (!isSameNetId) {
5152 // Set HTTP proxy system properties to match network.
5153 // TODO: Deprecate this static method and replace it with a non-static version.
5154 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005155 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005156 } catch (SecurityException e) {
5157 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5158 Log.e(TAG, "Can't set proxy properties", e);
5159 }
5160 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005161 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005162 // Must flush socket pool as idle sockets will be bound to previous network and may
5163 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005164 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005165 }
5166
5167 return true;
5168 }
5169
5170 /**
5171 * Returns the {@link Network} currently bound to this process via
5172 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5173 *
5174 * @return {@code Network} to which this process is bound, or {@code null}.
5175 */
5176 @Nullable
5177 public Network getBoundNetworkForProcess() {
5178 // Forcing callers to call thru non-static function ensures ConnectivityManager
5179 // instantiated.
5180 return getProcessDefaultNetwork();
5181 }
5182
5183 /**
5184 * Returns the {@link Network} currently bound to this process via
5185 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5186 *
5187 * @return {@code Network} to which this process is bound, or {@code null}.
5188 * @deprecated Using this function can lead to other functions throwing
5189 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5190 * {@code getBoundNetworkForProcess} is a direct replacement.
5191 */
5192 @Deprecated
5193 @Nullable
5194 public static Network getProcessDefaultNetwork() {
5195 int netId = NetworkUtils.getBoundNetworkForProcess();
5196 if (netId == NETID_UNSET) return null;
5197 return new Network(netId);
5198 }
5199
5200 private void unsupportedStartingFrom(int version) {
5201 if (Process.myUid() == Process.SYSTEM_UID) {
5202 // The getApplicationInfo() call we make below is not supported in system context. Let
5203 // the call through here, and rely on the fact that ConnectivityService will refuse to
5204 // allow the system to use these APIs anyway.
5205 return;
5206 }
5207
5208 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5209 throw new UnsupportedOperationException(
5210 "This method is not supported in target SDK version " + version + " and above");
5211 }
5212 }
5213
5214 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5215 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5216 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5217 // remove these exemptions. Note that this check is not secure, and apps can still access these
5218 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5219 // so is unsupported and may break in the future. http://b/22728205
5220 private void checkLegacyRoutingApiAccess() {
5221 unsupportedStartingFrom(VERSION_CODES.M);
5222 }
5223
5224 /**
5225 * Binds host resolutions performed by this process to {@code network}.
5226 * {@link #bindProcessToNetwork} takes precedence over this setting.
5227 *
5228 * @param network The {@link Network} to bind host resolutions from the current process to, or
5229 * {@code null} to clear the current binding.
5230 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5231 * @hide
5232 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5233 */
5234 @Deprecated
5235 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5236 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5237 return NetworkUtils.bindProcessToNetworkForHostResolution(
5238 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5239 }
5240
5241 /**
5242 * Device is not restricting metered network activity while application is running on
5243 * background.
5244 */
5245 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5246
5247 /**
5248 * Device is restricting metered network activity while application is running on background,
5249 * but application is allowed to bypass it.
5250 * <p>
5251 * In this state, application should take action to mitigate metered network access.
5252 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5253 */
5254 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5255
5256 /**
5257 * Device is restricting metered network activity while application is running on background.
5258 * <p>
5259 * In this state, application should not try to use the network while running on background,
5260 * because it would be denied.
5261 */
5262 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5263
5264 /**
5265 * A change in the background metered network activity restriction has occurred.
5266 * <p>
5267 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5268 * applies to them.
5269 * <p>
5270 * This is only sent to registered receivers, not manifest receivers.
5271 */
5272 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5273 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5274 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5275
Aaron Huangcff22942021-05-27 16:31:26 +08005276 /** @hide */
5277 @Retention(RetentionPolicy.SOURCE)
5278 @IntDef(flag = false, value = {
5279 RESTRICT_BACKGROUND_STATUS_DISABLED,
5280 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5281 RESTRICT_BACKGROUND_STATUS_ENABLED,
5282 })
5283 public @interface RestrictBackgroundStatus {
5284 }
5285
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005286 /**
5287 * Determines if the calling application is subject to metered network restrictions while
5288 * running on background.
5289 *
5290 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5291 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5292 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5293 */
5294 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5295 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005296 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005297 } catch (RemoteException e) {
5298 throw e.rethrowFromSystemServer();
5299 }
5300 }
5301
5302 /**
5303 * The network watchlist is a list of domains and IP addresses that are associated with
5304 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5305 * currently used by the system for validation purposes.
5306 *
5307 * @return Hash of network watchlist config file. Null if config does not exist.
5308 */
5309 @Nullable
5310 public byte[] getNetworkWatchlistConfigHash() {
5311 try {
5312 return mService.getNetworkWatchlistConfigHash();
5313 } catch (RemoteException e) {
5314 Log.e(TAG, "Unable to get watchlist config hash");
5315 throw e.rethrowFromSystemServer();
5316 }
5317 }
5318
5319 /**
5320 * Returns the {@code uid} of the owner of a network connection.
5321 *
5322 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5323 * IPPROTO_UDP} currently supported.
5324 * @param local The local {@link InetSocketAddress} of a connection.
5325 * @param remote The remote {@link InetSocketAddress} of a connection.
5326 * @return {@code uid} if the connection is found and the app has permission to observe it
5327 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5328 * android.os.Process#INVALID_UID} if the connection is not found.
5329 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5330 * user.
5331 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5332 */
5333 public int getConnectionOwnerUid(
5334 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5335 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5336 try {
5337 return mService.getConnectionOwnerUid(connectionInfo);
5338 } catch (RemoteException e) {
5339 throw e.rethrowFromSystemServer();
5340 }
5341 }
5342
5343 private void printStackTrace() {
5344 if (DEBUG) {
5345 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5346 final StringBuffer sb = new StringBuffer();
5347 for (int i = 3; i < callStack.length; i++) {
5348 final String stackTrace = callStack[i].toString();
5349 if (stackTrace == null || stackTrace.contains("android.os")) {
5350 break;
5351 }
5352 sb.append(" [").append(stackTrace).append("]");
5353 }
5354 Log.d(TAG, "StackLog:" + sb.toString());
5355 }
5356 }
5357
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005358 /** @hide */
5359 public TestNetworkManager startOrGetTestNetworkManager() {
5360 final IBinder tnBinder;
5361 try {
5362 tnBinder = mService.startOrGetTestNetworkService();
5363 } catch (RemoteException e) {
5364 throw e.rethrowFromSystemServer();
5365 }
5366
5367 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5368 }
5369
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005370 /** @hide */
5371 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5372 return new ConnectivityDiagnosticsManager(mContext, mService);
5373 }
5374
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005375 /**
5376 * Simulates a Data Stall for the specified Network.
5377 *
5378 * <p>This method should only be used for tests.
5379 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005380 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5381 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005382 *
5383 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005384 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5385 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5386 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005387 * @param network The Network for which a Data Stall is being simluated.
5388 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5389 * @throws SecurityException if the caller is not the owner of the given network.
5390 * @hide
5391 */
5392 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5393 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5394 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005395 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005396 @NonNull Network network, @NonNull PersistableBundle extras) {
5397 try {
5398 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5399 } catch (RemoteException e) {
5400 e.rethrowFromSystemServer();
5401 }
5402 }
5403
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005404 @NonNull
5405 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5406
5407 /**
5408 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5409 * receive available QoS events related to the {@link Network} and local ip + port
5410 * specified within socketInfo.
5411 * <p/>
5412 * The same {@link QosCallback} must be unregistered before being registered a second time,
5413 * otherwise {@link QosCallbackRegistrationException} is thrown.
5414 * <p/>
5415 * This API does not, in itself, require any permission if called with a network that is not
5416 * restricted. However, the underlying implementation currently only supports the IMS network,
5417 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5418 * useful, because they'd never be called back on networks that they would have access to.
5419 *
5420 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5421 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5422 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5423 * @throws RuntimeException if the app already has too many callbacks registered.
5424 *
5425 * Exceptions after the time of registration is passed through
5426 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5427 *
5428 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005429 * @param executor The executor on which the callback will be invoked. The provided
5430 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005431 * callbacks cannot be guaranteed.onQosCallbackRegistered
5432 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005433 *
5434 * @hide
5435 */
5436 @SystemApi
5437 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005438 @CallbackExecutor @NonNull final Executor executor,
5439 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005440 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005441 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005442 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005443
5444 try {
5445 synchronized (mQosCallbackConnections) {
5446 if (getQosCallbackConnection(callback) == null) {
5447 final QosCallbackConnection connection =
5448 new QosCallbackConnection(this, callback, executor);
5449 mQosCallbackConnections.add(connection);
5450 mService.registerQosSocketCallback(socketInfo, connection);
5451 } else {
5452 Log.e(TAG, "registerQosCallback: Callback already registered");
5453 throw new QosCallbackRegistrationException();
5454 }
5455 }
5456 } catch (final RemoteException e) {
5457 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5458
5459 // The same unregister method method is called for consistency even though nothing
5460 // will be sent to the ConnectivityService since the callback was never successfully
5461 // registered.
5462 unregisterQosCallback(callback);
5463 e.rethrowFromSystemServer();
5464 } catch (final ServiceSpecificException e) {
5465 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5466 unregisterQosCallback(callback);
5467 throw convertServiceException(e);
5468 }
5469 }
5470
5471 /**
5472 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5473 * events once unregistered and can be registered a second time.
5474 * <p/>
5475 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5476 *
5477 * @param callback the callback being unregistered
5478 *
5479 * @hide
5480 */
5481 @SystemApi
5482 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5483 Objects.requireNonNull(callback, "The callback must be non-null");
5484 try {
5485 synchronized (mQosCallbackConnections) {
5486 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5487 if (connection != null) {
5488 connection.stopReceivingMessages();
5489 mService.unregisterQosCallback(connection);
5490 mQosCallbackConnections.remove(connection);
5491 } else {
5492 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5493 }
5494 }
5495 } catch (final RemoteException e) {
5496 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5497 e.rethrowFromSystemServer();
5498 }
5499 }
5500
5501 /**
5502 * Gets the connection related to the callback.
5503 *
5504 * @param callback the callback to look up
5505 * @return the related connection
5506 */
5507 @Nullable
5508 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5509 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5510 // Checking by reference here is intentional
5511 if (connection.getCallback() == callback) {
5512 return connection;
5513 }
5514 }
5515 return null;
5516 }
5517
5518 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005519 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005520 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5521 * be used to request that the system provide a network without causing the network to be
5522 * in the foreground.
5523 *
5524 * <p>This method will attempt to find the best network that matches the passed
5525 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5526 * criteria. The platform will evaluate which network is the best at its own discretion.
5527 * Throughput, latency, cost per byte, policy, user preference and other considerations
5528 * may be factored in the decision of what is considered the best network.
5529 *
5530 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5531 * matching this request, while always attempting to match the request to a better network if
5532 * possible. If a better match is found, the platform will switch this request to the now-best
5533 * network and inform the app of the newly best network by invoking
5534 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5535 * will not try to maintain any other network than the best one currently matching the request:
5536 * a network not matching any network request may be disconnected at any time.
5537 *
5538 * <p>For example, an application could use this method to obtain a connected cellular network
5539 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5540 * radio to consume additional power. Or, an application could inform the system that it wants
5541 * a network supporting sending MMSes and have the system let it know about the currently best
5542 * MMS-supporting network through the provided {@link NetworkCallback}.
5543 *
5544 * <p>The status of the request can be followed by listening to the various callbacks described
5545 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5546 * used to direct traffic to the network (although accessing some networks may be subject to
5547 * holding specific permissions). Callers will learn about the specific characteristics of the
5548 * network through
5549 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5550 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5551 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5552 * matching the request at any given time; therefore when a better network matching the request
5553 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5554 * with the new network after which no further updates are given about the previously-best
5555 * network, unless it becomes the best again at some later time. All callbacks are invoked
5556 * in order on the same thread, which by default is a thread created by the framework running
5557 * in the app.
5558 *
5559 * <p>This{@link NetworkRequest} will live until released via
5560 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5561 * which point the system may let go of the network at any time.
5562 *
5563 * <p>It is presently unsupported to request a network with mutable
5564 * {@link NetworkCapabilities} such as
5565 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5566 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5567 * as these {@code NetworkCapabilities} represent states that a particular
5568 * network may never attain, and whether a network will attain these states
5569 * is unknown prior to bringing up the network so the framework does not
5570 * know how to go about satisfying a request with these capabilities.
5571 *
5572 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5573 * number of outstanding requests to 100 per app (identified by their UID), shared with
5574 * all variants of this method, of {@link #registerNetworkCallback} as well as
5575 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5576 * Requesting a network with this method will count toward this limit. If this limit is
5577 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5578 * make sure to unregister the callbacks with
5579 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5580 *
5581 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005582 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5583 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005584 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5585 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005586 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5587 * @throws SecurityException if missing the appropriate permissions.
5588 * @throws RuntimeException if the app already has too many callbacks registered.
5589 *
5590 * @hide
5591 */
5592 @SystemApi(client = MODULE_LIBRARIES)
5593 @SuppressLint("ExecutorRegistration")
5594 @RequiresPermission(anyOf = {
5595 android.Manifest.permission.NETWORK_SETTINGS,
5596 android.Manifest.permission.NETWORK_STACK,
5597 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5598 })
5599 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005600 @NonNull NetworkCallback networkCallback,
5601 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005602 final NetworkCapabilities nc = request.networkCapabilities;
5603 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005604 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005605 }
James Mattis12aeab82021-01-10 14:24:24 -08005606
5607 /**
James Mattis12aeab82021-01-10 14:24:24 -08005608 * Used by automotive devices to set the network preferences used to direct traffic at an
5609 * application level as per the given OemNetworkPreferences. An example use-case would be an
5610 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5611 * vehicle via a particular network.
5612 *
5613 * Calling this will overwrite the existing preference.
5614 *
5615 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5616 * @param executor the executor on which listener will be invoked.
5617 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5618 * communicate completion of setOemNetworkPreference(). This will only be
5619 * called once upon successful completion of setOemNetworkPreference().
5620 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5621 * @throws SecurityException if missing the appropriate permissions.
5622 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005623 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005624 */
James Mattis6e2d7022021-01-26 16:23:52 -08005625 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005626 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005627 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005628 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005629 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005630 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5631 if (null != listener) {
5632 Objects.requireNonNull(executor, "Executor must be non-null");
5633 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005634 final IOnCompleteListener listenerInternal = listener == null ? null :
5635 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005636 @Override
5637 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005638 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005639 }
5640 };
5641
5642 try {
5643 mService.setOemNetworkPreference(preference, listenerInternal);
5644 } catch (RemoteException e) {
5645 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5646 throw e.rethrowFromSystemServer();
5647 }
5648 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005649
Chalard Jeanad565e22021-02-25 17:23:40 +09005650 /**
5651 * Request that a user profile is put by default on a network matching a given preference.
5652 *
5653 * See the documentation for the individual preferences for a description of the supported
5654 * behaviors.
5655 *
5656 * @param profile the profile concerned.
5657 * @param preference the preference for this profile.
5658 * @param executor an executor to execute the listener on. Optional if listener is null.
5659 * @param listener an optional listener to listen for completion of the operation.
5660 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5661 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005662 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5663 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005664 * @hide
5665 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005666 // This function is for establishing per-profile default networking and can only be called by
5667 // the device policy manager, running as the system server. It would make no sense to call it
5668 // on a context for a user because it does not establish a setting on behalf of a user, rather
5669 // it establishes a setting for a user on behalf of the DPM.
5670 @SuppressLint({"UserHandle"})
5671 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005672 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005673 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005674 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005675 @ProfileNetworkPreferencePolicy final int preference,
5676 @Nullable @CallbackExecutor final Executor executor,
5677 @Nullable final Runnable listener) {
5678
5679 ProfileNetworkPreference.Builder preferenceBuilder =
5680 new ProfileNetworkPreference.Builder();
5681 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005682 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5683 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5684 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005685 setProfileNetworkPreferences(profile,
5686 List.of(preferenceBuilder.build()), executor, listener);
5687 }
5688
5689 /**
5690 * Set a list of default network selection policies for a user profile.
5691 *
5692 * Calling this API with a user handle defines the entire policy for that user handle.
5693 * It will overwrite any setting previously set for the same user profile,
5694 * and not affect previously set settings for other handles.
5695 *
5696 * Call this API with an empty list to remove settings for this user profile.
5697 *
5698 * See {@link ProfileNetworkPreference} for more details on each preference
5699 * parameter.
5700 *
5701 * @param profile the user profile for which the preference is being set.
5702 * @param profileNetworkPreferences the list of profile network preferences for the
5703 * provided profile.
5704 * @param executor an executor to execute the listener on. Optional if listener is null.
5705 * @param listener an optional listener to listen for completion of the operation.
5706 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5707 * @throws SecurityException if missing the appropriate permissions.
5708 * @hide
5709 */
5710 @SystemApi(client = MODULE_LIBRARIES)
5711 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5712 public void setProfileNetworkPreferences(
5713 @NonNull final UserHandle profile,
5714 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005715 @Nullable @CallbackExecutor final Executor executor,
5716 @Nullable final Runnable listener) {
5717 if (null != listener) {
5718 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5719 }
5720 final IOnCompleteListener proxy;
5721 if (null == listener) {
5722 proxy = null;
5723 } else {
5724 proxy = new IOnCompleteListener.Stub() {
5725 @Override
5726 public void onComplete() {
5727 executor.execute(listener::run);
5728 }
5729 };
5730 }
5731 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005732 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005733 } catch (RemoteException e) {
5734 throw e.rethrowFromSystemServer();
5735 }
5736 }
5737
lucaslin5cdbcfb2021-03-12 00:46:33 +08005738 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005739 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005740 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005741 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005742
5743 /**
5744 * Get the network ID range reserved for IPSec tunnel interfaces.
5745 *
5746 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5747 * @hide
5748 */
5749 @SystemApi(client = MODULE_LIBRARIES)
5750 @NonNull
5751 public static Range<Integer> getIpSecNetIdRange() {
5752 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5753 }
markchien738ad912021-12-09 18:15:45 +08005754
5755 /**
markchiene46042b2022-03-02 18:07:35 +08005756 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5757 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005758 *
5759 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005760 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005761 * @hide
5762 */
5763 @SystemApi(client = MODULE_LIBRARIES)
5764 @RequiresPermission(anyOf = {
5765 android.Manifest.permission.NETWORK_SETTINGS,
5766 android.Manifest.permission.NETWORK_STACK,
5767 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5768 })
markchiene46042b2022-03-02 18:07:35 +08005769 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005770 try {
markchiene46042b2022-03-02 18:07:35 +08005771 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08005772 } catch (RemoteException e) {
5773 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005774 }
5775 }
5776
5777 /**
markchiene46042b2022-03-02 18:07:35 +08005778 * Removes the specified UID from the list of UIDs that are allowed to use background data on
5779 * metered networks when background data is restricted. The deny list takes precedence over
5780 * the allow list.
5781 *
5782 * @param uid uid of target app
5783 * @throws IllegalStateException if updating allow list failed.
5784 * @hide
5785 */
5786 @SystemApi(client = MODULE_LIBRARIES)
5787 @RequiresPermission(anyOf = {
5788 android.Manifest.permission.NETWORK_SETTINGS,
5789 android.Manifest.permission.NETWORK_STACK,
5790 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5791 })
5792 public void removeUidFromMeteredNetworkAllowList(final int uid) {
5793 try {
5794 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
5795 } catch (RemoteException e) {
5796 throw e.rethrowFromSystemServer();
5797 }
5798 }
5799
5800 /**
5801 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
5802 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08005803 *
5804 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005805 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08005806 * @hide
5807 */
5808 @SystemApi(client = MODULE_LIBRARIES)
5809 @RequiresPermission(anyOf = {
5810 android.Manifest.permission.NETWORK_SETTINGS,
5811 android.Manifest.permission.NETWORK_STACK,
5812 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5813 })
markchiene46042b2022-03-02 18:07:35 +08005814 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005815 try {
markchiene46042b2022-03-02 18:07:35 +08005816 mService.updateMeteredNetworkDenyList(uid, true /* add */);
5817 } catch (RemoteException e) {
5818 throw e.rethrowFromSystemServer();
5819 }
5820 }
5821
5822 /**
5823 * Removes the specified UID from the list of UIds that can use use background data on metered
5824 * networks if background data is not restricted. The deny list takes precedence over the
5825 * allow list.
5826 *
5827 * @param uid uid of target app
5828 * @throws IllegalStateException if updating deny list failed.
5829 * @hide
5830 */
5831 @SystemApi(client = MODULE_LIBRARIES)
5832 @RequiresPermission(anyOf = {
5833 android.Manifest.permission.NETWORK_SETTINGS,
5834 android.Manifest.permission.NETWORK_STACK,
5835 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5836 })
5837 public void removeUidFromMeteredNetworkDenyList(final int uid) {
5838 try {
5839 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08005840 } catch (RemoteException e) {
5841 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08005842 }
5843 }
5844
5845 /**
5846 * Sets a firewall rule for the specified UID on the specified chain.
5847 *
5848 * @param chain target chain.
5849 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08005850 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08005851 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08005852 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08005853 * @hide
5854 */
5855 @SystemApi(client = MODULE_LIBRARIES)
5856 @RequiresPermission(anyOf = {
5857 android.Manifest.permission.NETWORK_SETTINGS,
5858 android.Manifest.permission.NETWORK_STACK,
5859 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5860 })
markchien3c04e662022-03-22 16:29:56 +08005861 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
5862 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08005863 try {
markchien3c04e662022-03-22 16:29:56 +08005864 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08005865 } catch (RemoteException e) {
5866 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005867 }
5868 }
markchien98a6f952022-01-13 23:43:53 +08005869
5870 /**
5871 * Enables or disables the specified firewall chain.
5872 *
5873 * @param chain target chain.
5874 * @param enable whether the chain should be enabled.
markchien68cfadc2022-01-14 13:39:54 +08005875 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08005876 * @hide
5877 */
5878 @SystemApi(client = MODULE_LIBRARIES)
5879 @RequiresPermission(anyOf = {
5880 android.Manifest.permission.NETWORK_SETTINGS,
5881 android.Manifest.permission.NETWORK_STACK,
5882 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5883 })
5884 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
5885 try {
5886 mService.setFirewallChainEnabled(chain, enable);
5887 } catch (RemoteException e) {
5888 throw e.rethrowFromSystemServer();
5889 }
5890 }
markchien00a0bed2022-01-13 23:46:13 +08005891
5892 /**
5893 * Replaces the contents of the specified UID-based firewall chain.
5894 *
5895 * @param chain target chain to replace.
5896 * @param uids The list of UIDs to be placed into chain.
markchien68cfadc2022-01-14 13:39:54 +08005897 * @throws IllegalStateException if replacing the firewall chain failed.
markchien00a0bed2022-01-13 23:46:13 +08005898 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
5899 * @hide
5900 */
5901 @SystemApi(client = MODULE_LIBRARIES)
5902 @RequiresPermission(anyOf = {
5903 android.Manifest.permission.NETWORK_SETTINGS,
5904 android.Manifest.permission.NETWORK_STACK,
5905 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5906 })
5907 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
5908 Objects.requireNonNull(uids);
5909 try {
5910 mService.replaceFirewallChain(chain, uids);
5911 } catch (RemoteException e) {
5912 throw e.rethrowFromSystemServer();
5913 }
5914 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005915}