blob: 9e879c25a2531ac22392d1510735c454faec58f6 [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;
Junyu Laic279f182023-09-07 15:25:52 +080029import android.annotation.FlaggedApi;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090030import android.annotation.IntDef;
31import android.annotation.NonNull;
32import android.annotation.Nullable;
33import android.annotation.RequiresPermission;
34import android.annotation.SdkConstant;
35import android.annotation.SdkConstant.SdkConstantType;
36import android.annotation.SuppressLint;
37import android.annotation.SystemApi;
38import android.annotation.SystemService;
39import android.app.PendingIntent;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090040import android.app.admin.DevicePolicyManager;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090041import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090042import android.content.ComponentName;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090043import android.content.Context;
44import android.content.Intent;
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +090045import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090046import android.net.IpSecManager.UdpEncapsulationSocket;
47import android.net.SocketKeepalive.Callback;
48import android.net.TetheringManager.StartTetheringCallback;
49import android.net.TetheringManager.TetheringEventCallback;
50import android.net.TetheringManager.TetheringRequest;
51import android.os.Binder;
52import android.os.Build;
53import android.os.Build.VERSION_CODES;
54import android.os.Bundle;
55import android.os.Handler;
56import android.os.IBinder;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090057import android.os.Looper;
58import android.os.Message;
59import android.os.Messenger;
60import android.os.ParcelFileDescriptor;
61import android.os.PersistableBundle;
62import android.os.Process;
63import android.os.RemoteException;
64import android.os.ResultReceiver;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090065import android.os.ServiceSpecificException;
Chalard Jeanad565e22021-02-25 17:23:40 +090066import android.os.UserHandle;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090067import android.provider.Settings;
68import android.telephony.SubscriptionManager;
69import android.telephony.TelephonyManager;
70import android.util.ArrayMap;
71import android.util.Log;
72import android.util.Range;
73import android.util.SparseIntArray;
74
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090075import com.android.internal.annotations.GuardedBy;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090076
77import libcore.net.event.NetworkEventDispatcher;
78
79import java.io.IOException;
80import java.io.UncheckedIOException;
81import java.lang.annotation.Retention;
82import java.lang.annotation.RetentionPolicy;
83import java.net.DatagramSocket;
84import java.net.InetAddress;
85import java.net.InetSocketAddress;
86import java.net.Socket;
87import java.util.ArrayList;
88import java.util.Collection;
89import java.util.HashMap;
90import java.util.List;
91import java.util.Map;
92import java.util.Objects;
93import java.util.concurrent.Executor;
94import java.util.concurrent.ExecutorService;
95import java.util.concurrent.Executors;
96import java.util.concurrent.RejectedExecutionException;
97
98/**
99 * Class that answers queries about the state of network connectivity. It also
100 * notifies applications when network connectivity changes.
101 * <p>
102 * The primary responsibilities of this class are to:
103 * <ol>
104 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
105 * <li>Send broadcast intents when network connectivity changes</li>
106 * <li>Attempt to "fail over" to another network when connectivity to a network
107 * is lost</li>
108 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
109 * state of the available networks</li>
110 * <li>Provide an API that allows applications to request and select networks for their data
111 * traffic</li>
112 * </ol>
113 */
114@SystemService(Context.CONNECTIVITY_SERVICE)
115public class ConnectivityManager {
116 private static final String TAG = "ConnectivityManager";
117 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
118
Junyu Laic279f182023-09-07 15:25:52 +0800119 // TODO : remove this class when udc-mainline-prod is abandoned and android.net.flags.Flags is
120 // available here
121 /** @hide */
122 public static class Flags {
123 static final String SET_DATA_SAVER_VIA_CM =
124 "com.android.net.flags.set_data_saver_via_cm";
125 }
126
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900127 /**
128 * A change in network connectivity has occurred. A default connection has either
129 * been established or lost. The NetworkInfo for the affected network is
130 * sent as an extra; it should be consulted to see what kind of
131 * connectivity event occurred.
132 * <p/>
133 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
134 * broadcast if they declare the broadcast receiver in their manifest. Apps
135 * will still receive broadcasts if they register their
136 * {@link android.content.BroadcastReceiver} with
137 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
138 * and that context is still valid.
139 * <p/>
140 * If this is a connection that was the result of failing over from a
141 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
142 * set to true.
143 * <p/>
144 * For a loss of connectivity, if the connectivity manager is attempting
145 * to connect (or has already connected) to another network, the
146 * NetworkInfo for the new network is also passed as an extra. This lets
147 * any receivers of the broadcast know that they should not necessarily
148 * tell the user that no data traffic will be possible. Instead, the
149 * receiver should expect another broadcast soon, indicating either that
150 * the failover attempt succeeded (and so there is still overall data
151 * connectivity), or that the failover attempt failed, meaning that all
152 * connectivity has been lost.
153 * <p/>
154 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
155 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900156 * <p />
157 * Note that this broadcast is deprecated and generally tries to implement backwards
158 * compatibility with older versions of Android. As such, it may not reflect new
159 * capabilities of the system, like multiple networks being connected at the same
160 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900161 *
162 * @deprecated apps should use the more versatile {@link #requestNetwork},
163 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
164 * functions instead for faster and more detailed updates about the network
165 * changes they care about.
166 */
167 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
168 @Deprecated
169 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
170
171 /**
172 * The device has connected to a network that has presented a captive
173 * portal, which is blocking Internet connectivity. The user was presented
174 * with a notification that network sign in is required,
175 * and the user invoked the notification's action indicating they
176 * desire to sign in to the network. Apps handling this activity should
177 * facilitate signing in to the network. This action includes a
178 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
179 * the network presenting the captive portal; all communication with the
180 * captive portal must be done using this {@code Network} object.
181 * <p/>
182 * This activity includes a {@link CaptivePortal} extra named
183 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
184 * outcomes of the captive portal sign in to the system:
185 * <ul>
186 * <li> When the app handling this action believes the user has signed in to
187 * the network and the captive portal has been dismissed, the app should
188 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
189 * reevaluate the network. If reevaluation finds the network no longer
190 * subject to a captive portal, the network may become the default active
191 * data network.</li>
192 * <li> When the app handling this action believes the user explicitly wants
193 * to ignore the captive portal and the network, the app should call
194 * {@link CaptivePortal#ignoreNetwork}. </li>
195 * </ul>
196 */
197 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
198 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
199
200 /**
201 * The lookup key for a {@link NetworkInfo} object. Retrieve with
202 * {@link android.content.Intent#getParcelableExtra(String)}.
203 *
204 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
205 * can't accurately represent modern network characteristics.
206 * Please obtain information about networks from the {@link NetworkCapabilities}
207 * or {@link LinkProperties} objects instead.
208 */
209 @Deprecated
210 public static final String EXTRA_NETWORK_INFO = "networkInfo";
211
212 /**
213 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
214 *
215 * @see android.content.Intent#getIntExtra(String, int)
216 * @deprecated The network type is not rich enough to represent the characteristics
217 * of modern networks. Please use {@link NetworkCapabilities} instead,
218 * in particular the transports.
219 */
220 @Deprecated
221 public static final String EXTRA_NETWORK_TYPE = "networkType";
222
223 /**
224 * The lookup key for a boolean that indicates whether a connect event
225 * is for a network to which the connectivity manager was failing over
226 * following a disconnect on another network.
227 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
228 *
229 * @deprecated See {@link NetworkInfo}.
230 */
231 @Deprecated
232 public static final String EXTRA_IS_FAILOVER = "isFailover";
233 /**
234 * The lookup key for a {@link NetworkInfo} object. This is supplied when
235 * there is another network that it may be possible to connect to. Retrieve with
236 * {@link android.content.Intent#getParcelableExtra(String)}.
237 *
238 * @deprecated See {@link NetworkInfo}.
239 */
240 @Deprecated
241 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
242 /**
243 * The lookup key for a boolean that indicates whether there is a
244 * complete lack of connectivity, i.e., no network is available.
245 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
246 */
247 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
248 /**
249 * The lookup key for a string that indicates why an attempt to connect
250 * to a network failed. The string has no particular structure. It is
251 * intended to be used in notifications presented to users. Retrieve
252 * it with {@link android.content.Intent#getStringExtra(String)}.
253 */
254 public static final String EXTRA_REASON = "reason";
255 /**
256 * The lookup key for a string that provides optionally supplied
257 * extra information about the network state. The information
258 * may be passed up from the lower networking layers, and its
259 * meaning may be specific to a particular network type. Retrieve
260 * it with {@link android.content.Intent#getStringExtra(String)}.
261 *
262 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
263 */
264 @Deprecated
265 public static final String EXTRA_EXTRA_INFO = "extraInfo";
266 /**
267 * The lookup key for an int that provides information about
268 * our connection to the internet at large. 0 indicates no connection,
269 * 100 indicates a great connection. Retrieve it with
270 * {@link android.content.Intent#getIntExtra(String, int)}.
271 * {@hide}
272 */
273 public static final String EXTRA_INET_CONDITION = "inetCondition";
274 /**
275 * The lookup key for a {@link CaptivePortal} object included with the
276 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
277 * object can be used to either indicate to the system that the captive
278 * portal has been dismissed or that the user does not want to pursue
279 * signing in to captive portal. Retrieve it with
280 * {@link android.content.Intent#getParcelableExtra(String)}.
281 */
282 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
283
284 /**
285 * Key for passing a URL to the captive portal login activity.
286 */
287 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
288
289 /**
290 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
291 * portal login activity.
292 * {@hide}
293 */
294 @SystemApi
295 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
296 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
297
298 /**
299 * Key for passing a user agent string to the captive portal login activity.
300 * {@hide}
301 */
302 @SystemApi
303 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
304 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
305
306 /**
307 * Broadcast action to indicate the change of data activity status
308 * (idle or active) on a network in a recent period.
309 * The network becomes active when data transmission is started, or
310 * idle if there is no data transmission for a period of time.
311 * {@hide}
312 */
313 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
314 public static final String ACTION_DATA_ACTIVITY_CHANGE =
315 "android.net.conn.DATA_ACTIVITY_CHANGE";
316 /**
317 * The lookup key for an enum that indicates the network device type on which this data activity
318 * change happens.
319 * {@hide}
320 */
321 public static final String EXTRA_DEVICE_TYPE = "deviceType";
322 /**
323 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
324 * it is actively sending or receiving data and {@code false} means it is idle.
325 * {@hide}
326 */
327 public static final String EXTRA_IS_ACTIVE = "isActive";
328 /**
329 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
330 * {@hide}
331 */
332 public static final String EXTRA_REALTIME_NS = "tsNanos";
333
334 /**
335 * Broadcast Action: The setting for background data usage has changed
336 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
337 * <p>
338 * If an application uses the network in the background, it should listen
339 * for this broadcast and stop using the background data if the value is
340 * {@code false}.
341 * <p>
342 *
343 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
344 * of background data depends on several combined factors, and
345 * this broadcast is no longer sent. Instead, when background
346 * data is unavailable, {@link #getActiveNetworkInfo()} will now
347 * appear disconnected. During first boot after a platform
348 * upgrade, this broadcast will be sent once if
349 * {@link #getBackgroundDataSetting()} was {@code false} before
350 * the upgrade.
351 */
352 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
353 @Deprecated
354 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
355 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
356
357 /**
358 * Broadcast Action: The network connection may not be good
359 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
360 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
361 * the network and it's condition.
362 * @hide
363 */
364 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
365 @UnsupportedAppUsage
366 public static final String INET_CONDITION_ACTION =
367 "android.net.conn.INET_CONDITION_ACTION";
368
369 /**
370 * Broadcast Action: A tetherable connection has come or gone.
371 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
372 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
373 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
374 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
375 * the current state of tethering. Each include a list of
376 * interface names in that state (may be empty).
377 * @hide
378 */
379 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
380 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
381 public static final String ACTION_TETHER_STATE_CHANGED =
382 TetheringManager.ACTION_TETHER_STATE_CHANGED;
383
384 /**
385 * @hide
386 * gives a String[] listing all the interfaces configured for
387 * tethering and currently available for tethering.
388 */
389 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
390 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
391
392 /**
393 * @hide
394 * gives a String[] listing all the interfaces currently in local-only
395 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
396 */
397 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
398
399 /**
400 * @hide
401 * gives a String[] listing all the interfaces currently tethered
402 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
403 */
404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
405 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
406
407 /**
408 * @hide
409 * gives a String[] listing all the interfaces we tried to tether and
410 * failed. Use {@link #getLastTetherError} to find the error code
411 * for any interfaces listed here.
412 */
413 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
414 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
415
416 /**
417 * Broadcast Action: The captive portal tracker has finished its test.
418 * Sent only while running Setup Wizard, in lieu of showing a user
419 * notification.
420 * @hide
421 */
422 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
423 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
424 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
425 /**
426 * The lookup key for a boolean that indicates whether a captive portal was detected.
427 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
428 * @hide
429 */
430 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
431
432 /**
433 * Action used to display a dialog that asks the user whether to connect to a network that is
434 * not validated. This intent is used to start the dialog in settings via startActivity.
435 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800436 * This action includes a {@link Network} typed extra which is called
437 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
438 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900439 * @hide
440 */
lucaslincf6d4502021-03-04 17:09:51 +0800441 @SystemApi(client = MODULE_LIBRARIES)
442 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900443
444 /**
445 * Action used to display a dialog that asks the user whether to avoid a network that is no
446 * longer validated. This intent is used to start the dialog in settings via startActivity.
447 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800448 * This action includes a {@link Network} typed extra which is called
449 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
450 * validated.
451 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900452 * @hide
453 */
lucaslincf6d4502021-03-04 17:09:51 +0800454 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900455 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800456 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900457
458 /**
459 * Action used to display a dialog that asks the user whether to stay connected to a network
460 * that has not validated. This intent is used to start the dialog in settings via
461 * startActivity.
462 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800463 * This action includes a {@link Network} typed extra which is called
464 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
465 * connectivity.
466 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900467 * @hide
468 */
lucaslincf6d4502021-03-04 17:09:51 +0800469 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900470 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800471 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900472
473 /**
paulhub49c8422021-04-07 16:18:13 +0800474 * Clear DNS Cache Action: This is broadcast when networks have changed and old
475 * DNS entries should be cleared.
476 * @hide
477 */
478 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
479 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
480 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
481
482 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900483 * Invalid tethering type.
484 * @see #startTethering(int, boolean, OnStartTetheringCallback)
485 * @hide
486 */
487 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
488
489 /**
490 * Wifi tethering type.
491 * @see #startTethering(int, boolean, OnStartTetheringCallback)
492 * @hide
493 */
494 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900495 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900496
497 /**
498 * USB tethering type.
499 * @see #startTethering(int, boolean, OnStartTetheringCallback)
500 * @hide
501 */
502 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900503 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900504
505 /**
506 * Bluetooth tethering type.
507 * @see #startTethering(int, boolean, OnStartTetheringCallback)
508 * @hide
509 */
510 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900511 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900512
513 /**
514 * Wifi P2p tethering type.
515 * Wifi P2p tethering is set through events automatically, and don't
516 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
517 * @hide
518 */
519 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
520
521 /**
522 * Extra used for communicating with the TetherService. Includes the type of tethering to
523 * enable if any.
524 * @hide
525 */
526 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
527
528 /**
529 * Extra used for communicating with the TetherService. Includes the type of tethering for
530 * which to cancel provisioning.
531 * @hide
532 */
533 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
534
535 /**
536 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
537 * provisioning.
538 * @hide
539 */
540 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
541
542 /**
543 * Tells the TetherService to run a provision check now.
544 * @hide
545 */
546 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
547
548 /**
549 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
550 * which will receive provisioning results. Can be left empty.
551 * @hide
552 */
553 public static final String EXTRA_PROVISION_CALLBACK =
554 TetheringConstants.EXTRA_PROVISION_CALLBACK;
555
556 /**
557 * The absence of a connection type.
558 * @hide
559 */
560 @SystemApi
561 public static final int TYPE_NONE = -1;
562
563 /**
564 * A Mobile data connection. Devices may support more than one.
565 *
566 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
567 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000568 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900569 */
570 @Deprecated
571 public static final int TYPE_MOBILE = 0;
572
573 /**
574 * A WIFI data connection. Devices may support more than one.
575 *
576 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
577 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000578 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900579 */
580 @Deprecated
581 public static final int TYPE_WIFI = 1;
582
583 /**
584 * An MMS-specific Mobile data connection. This network type may use the
585 * same network interface as {@link #TYPE_MOBILE} or it may use a different
586 * one. This is used by applications needing to talk to the carrier's
587 * Multimedia Messaging Service servers.
588 *
589 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
590 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
591 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
592 */
593 @Deprecated
594 public static final int TYPE_MOBILE_MMS = 2;
595
596 /**
597 * A SUPL-specific Mobile data connection. This network type may use the
598 * same network interface as {@link #TYPE_MOBILE} or it may use a different
599 * one. This is used by applications needing to talk to the carrier's
600 * Secure User Plane Location servers for help locating the device.
601 *
602 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
603 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
604 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
605 */
606 @Deprecated
607 public static final int TYPE_MOBILE_SUPL = 3;
608
609 /**
610 * A DUN-specific Mobile data connection. This network type may use the
611 * same network interface as {@link #TYPE_MOBILE} or it may use a different
612 * one. This is sometimes by the system when setting up an upstream connection
613 * for tethering so that the carrier is aware of DUN traffic.
614 *
615 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
616 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
617 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
618 */
619 @Deprecated
620 public static final int TYPE_MOBILE_DUN = 4;
621
622 /**
623 * A High Priority Mobile data connection. This network type uses the
624 * same network interface as {@link #TYPE_MOBILE} but the routing setup
625 * is different.
626 *
627 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
628 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000629 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900630 */
631 @Deprecated
632 public static final int TYPE_MOBILE_HIPRI = 5;
633
634 /**
635 * A WiMAX data connection.
636 *
637 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
638 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000639 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900640 */
641 @Deprecated
642 public static final int TYPE_WIMAX = 6;
643
644 /**
645 * A Bluetooth data connection.
646 *
647 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
648 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000649 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900650 */
651 @Deprecated
652 public static final int TYPE_BLUETOOTH = 7;
653
654 /**
655 * Fake data connection. This should not be used on shipping devices.
656 * @deprecated This is not used any more.
657 */
658 @Deprecated
659 public static final int TYPE_DUMMY = 8;
660
661 /**
662 * An Ethernet data connection.
663 *
664 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
665 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000666 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900667 */
668 @Deprecated
669 public static final int TYPE_ETHERNET = 9;
670
671 /**
672 * Over the air Administration.
673 * @deprecated Use {@link NetworkCapabilities} instead.
674 * {@hide}
675 */
676 @Deprecated
677 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
678 public static final int TYPE_MOBILE_FOTA = 10;
679
680 /**
681 * IP Multimedia Subsystem.
682 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
683 * {@hide}
684 */
685 @Deprecated
686 @UnsupportedAppUsage
687 public static final int TYPE_MOBILE_IMS = 11;
688
689 /**
690 * Carrier Branded Services.
691 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
692 * {@hide}
693 */
694 @Deprecated
695 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
696 public static final int TYPE_MOBILE_CBS = 12;
697
698 /**
699 * A Wi-Fi p2p connection. Only requesting processes will have access to
700 * the peers connected.
701 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
702 * {@hide}
703 */
704 @Deprecated
705 @SystemApi
706 public static final int TYPE_WIFI_P2P = 13;
707
708 /**
709 * The network to use for initially attaching to the network
710 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
711 * {@hide}
712 */
713 @Deprecated
714 @UnsupportedAppUsage
715 public static final int TYPE_MOBILE_IA = 14;
716
717 /**
718 * Emergency PDN connection for emergency services. This
719 * may include IMS and MMS in emergency situations.
720 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
721 * {@hide}
722 */
723 @Deprecated
724 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
725 public static final int TYPE_MOBILE_EMERGENCY = 15;
726
727 /**
728 * The network that uses proxy to achieve connectivity.
729 * @deprecated Use {@link NetworkCapabilities} instead.
730 * {@hide}
731 */
732 @Deprecated
733 @SystemApi
734 public static final int TYPE_PROXY = 16;
735
736 /**
737 * A virtual network using one or more native bearers.
738 * It may or may not be providing security services.
739 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
740 */
741 @Deprecated
742 public static final int TYPE_VPN = 17;
743
744 /**
745 * A network that is exclusively meant to be used for testing
746 *
747 * @deprecated Use {@link NetworkCapabilities} instead.
748 * @hide
749 */
750 @Deprecated
751 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
752
753 /**
754 * @deprecated Use {@link NetworkCapabilities} instead.
755 * @hide
756 */
757 @Deprecated
758 @Retention(RetentionPolicy.SOURCE)
759 @IntDef(prefix = { "TYPE_" }, value = {
760 TYPE_NONE,
761 TYPE_MOBILE,
762 TYPE_WIFI,
763 TYPE_MOBILE_MMS,
764 TYPE_MOBILE_SUPL,
765 TYPE_MOBILE_DUN,
766 TYPE_MOBILE_HIPRI,
767 TYPE_WIMAX,
768 TYPE_BLUETOOTH,
769 TYPE_DUMMY,
770 TYPE_ETHERNET,
771 TYPE_MOBILE_FOTA,
772 TYPE_MOBILE_IMS,
773 TYPE_MOBILE_CBS,
774 TYPE_WIFI_P2P,
775 TYPE_MOBILE_IA,
776 TYPE_MOBILE_EMERGENCY,
777 TYPE_PROXY,
778 TYPE_VPN,
779 TYPE_TEST
780 })
781 public @interface LegacyNetworkType {}
782
783 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
784 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
785 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
786 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
787 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
788
789 /** {@hide} */
790 public static final int MAX_RADIO_TYPE = TYPE_TEST;
791
792 /** {@hide} */
793 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
794
795 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
796
797 /**
798 * If you want to set the default network preference,you can directly
799 * change the networkAttributes array in framework's config.xml.
800 *
801 * @deprecated Since we support so many more networks now, the single
802 * network default network preference can't really express
803 * the hierarchy. Instead, the default is defined by the
804 * networkAttributes in config.xml. You can determine
805 * the current value by calling {@link #getNetworkPreference()}
806 * from an App.
807 */
808 @Deprecated
809 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
810
811 /**
812 * @hide
813 */
814 public static final int REQUEST_ID_UNSET = 0;
815
816 /**
817 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
818 * This allows to distinguish when unregistering NetworkCallbacks those that were never
819 * registered from those that were already unregistered.
820 * @hide
821 */
822 private static final NetworkRequest ALREADY_UNREGISTERED =
823 new NetworkRequest.Builder().clearCapabilities().build();
824
825 /**
826 * A NetID indicating no Network is selected.
827 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
828 * @hide
829 */
830 public static final int NETID_UNSET = 0;
831
832 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000833 * Flag to indicate that an app is not subject to any restrictions that could result in its
834 * network access blocked.
835 *
836 * @hide
837 */
838 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
839 public static final int BLOCKED_REASON_NONE = 0;
840
841 /**
842 * Flag to indicate that an app is subject to Battery saver 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_BATTERY_SAVER = 1 << 0;
849
850 /**
851 * Flag to indicate that an app is subject to Doze 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_DOZE = 1 << 1;
858
859 /**
860 * Flag to indicate that an app is subject to App Standby 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_APP_STANDBY = 1 << 2;
867
868 /**
869 * Flag to indicate that an app is subject to Restricted mode restrictions that would
870 * result in its network access being blocked.
871 *
872 * @hide
873 */
874 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
875 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
876
877 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900878 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
879 * is not currently connected.
880 *
881 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
882 *
883 * @hide
884 */
885 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
886 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
887
888 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100889 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
890 * result in its network access being blocked.
891 *
892 * @hide
893 */
894 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
895 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
896
897 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000898 * Flag to indicate that an app is subject to Data saver 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_DATA_SAVER = 1 << 16;
905
906 /**
907 * Flag to indicate that an app is subject to user 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_USER_RESTRICTED = 1 << 17;
914
915 /**
916 * Flag to indicate that an app is subject to Device admin restrictions that would
917 * result in its metered network access being blocked.
918 *
919 * @hide
920 */
921 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
922 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
923
924 /**
925 * @hide
926 */
927 @Retention(RetentionPolicy.SOURCE)
928 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
929 BLOCKED_REASON_NONE,
930 BLOCKED_REASON_BATTERY_SAVER,
931 BLOCKED_REASON_DOZE,
932 BLOCKED_REASON_APP_STANDBY,
933 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900934 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100935 BLOCKED_REASON_LOW_POWER_STANDBY,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000936 BLOCKED_METERED_REASON_DATA_SAVER,
937 BLOCKED_METERED_REASON_USER_RESTRICTED,
938 BLOCKED_METERED_REASON_ADMIN_DISABLED,
939 })
940 public @interface BlockedReason {}
941
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900942 /**
943 * Set of blocked reasons that are only applicable on metered networks.
944 *
945 * @hide
946 */
947 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
948 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
949
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900950 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
951 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900952
Robert Horvathd945bf02022-01-27 19:55:16 +0100953 // LINT.IfChange(firewall_chain)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900954 /**
markchiene1561fa2021-12-09 22:00:56 +0800955 * Firewall chain for device idle (doze mode).
956 * Allowlist of apps that have network access in device idle.
957 * @hide
958 */
959 @SystemApi(client = MODULE_LIBRARIES)
960 public static final int FIREWALL_CHAIN_DOZABLE = 1;
961
962 /**
963 * Firewall chain used for app standby.
964 * Denylist of apps that do not have network access.
965 * @hide
966 */
967 @SystemApi(client = MODULE_LIBRARIES)
968 public static final int FIREWALL_CHAIN_STANDBY = 2;
969
970 /**
971 * Firewall chain used for battery saver.
972 * Allowlist of apps that have network access when battery saver is on.
973 * @hide
974 */
975 @SystemApi(client = MODULE_LIBRARIES)
976 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
977
978 /**
979 * Firewall chain used for restricted networking mode.
980 * Allowlist of apps that have access in restricted networking mode.
981 * @hide
982 */
983 @SystemApi(client = MODULE_LIBRARIES)
984 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
985
Robert Horvath34cba142022-01-27 19:52:43 +0100986 /**
987 * Firewall chain used for low power standby.
988 * Allowlist of apps that have access in low power standby.
989 * @hide
990 */
991 @SystemApi(client = MODULE_LIBRARIES)
992 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
993
Motomu Utsumib08654c2022-05-11 05:56:26 +0000994 /**
Motomu Utsumid9801492022-06-01 13:57:27 +0000995 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +0900996 *
997 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
998 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
999 *
1000 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1001 * independent of the others. The chains can be enabled and disabled independently, and apps can
1002 * be added and removed from each chain independently.
1003 *
1004 * @see #FIREWALL_CHAIN_OEM_DENY_2
1005 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001006 * @hide
1007 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001008 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001009 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1010
1011 /**
1012 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001013 *
1014 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1015 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1016 *
1017 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1018 * independent of the others. The chains can be enabled and disabled independently, and apps can
1019 * be added and removed from each chain independently.
1020 *
1021 * @see #FIREWALL_CHAIN_OEM_DENY_1
1022 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001023 * @hide
1024 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001025 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001026 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1027
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001028 /**
1029 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001030 *
1031 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1032 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1033 *
1034 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1035 * independent of the others. The chains can be enabled and disabled independently, and apps can
1036 * be added and removed from each chain independently.
1037 *
1038 * @see #FIREWALL_CHAIN_OEM_DENY_1
1039 * @see #FIREWALL_CHAIN_OEM_DENY_2
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001040 * @hide
1041 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001042 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001043 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1044
markchiene1561fa2021-12-09 22:00:56 +08001045 /** @hide */
1046 @Retention(RetentionPolicy.SOURCE)
1047 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1048 FIREWALL_CHAIN_DOZABLE,
1049 FIREWALL_CHAIN_STANDBY,
1050 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001051 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001052 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Motomu Utsumid9801492022-06-01 13:57:27 +00001053 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001054 FIREWALL_CHAIN_OEM_DENY_2,
1055 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001056 })
1057 public @interface FirewallChain {}
Robert Horvathd945bf02022-01-27 19:55:16 +01001058 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
markchiene1561fa2021-12-09 22:00:56 +08001059
1060 /**
markchien011a7f52022-03-29 01:07:22 +08001061 * A firewall rule which allows or drops packets depending on existing policy.
1062 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1063 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001064 * @hide
1065 */
1066 @SystemApi(client = MODULE_LIBRARIES)
1067 public static final int FIREWALL_RULE_DEFAULT = 0;
1068
1069 /**
markchien011a7f52022-03-29 01:07:22 +08001070 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1071 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001072 * @hide
1073 */
1074 @SystemApi(client = MODULE_LIBRARIES)
1075 public static final int FIREWALL_RULE_ALLOW = 1;
1076
1077 /**
markchien011a7f52022-03-29 01:07:22 +08001078 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1079 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001080 * @hide
1081 */
1082 @SystemApi(client = MODULE_LIBRARIES)
1083 public static final int FIREWALL_RULE_DENY = 2;
1084
1085 /** @hide */
1086 @Retention(RetentionPolicy.SOURCE)
1087 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1088 FIREWALL_RULE_DEFAULT,
1089 FIREWALL_RULE_ALLOW,
1090 FIREWALL_RULE_DENY
1091 })
1092 public @interface FirewallRule {}
1093
1094 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001095 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1096 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1097 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1098 * methods that take a Context argument.
1099 */
1100 private static ConnectivityManager sInstance;
1101
1102 private final Context mContext;
1103
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001104 @GuardedBy("mTetheringEventCallbacks")
1105 private TetheringManager mTetheringManager;
1106
1107 private TetheringManager getTetheringManager() {
1108 synchronized (mTetheringEventCallbacks) {
1109 if (mTetheringManager == null) {
1110 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1111 }
1112 return mTetheringManager;
1113 }
1114 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001115
1116 /**
1117 * Tests if a given integer represents a valid network type.
1118 * @param networkType the type to be tested
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001119 * @return {@code true} if the type is valid, else {@code false}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001120 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1121 * validate a network type.
1122 */
1123 @Deprecated
1124 public static boolean isNetworkTypeValid(int networkType) {
1125 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1126 }
1127
1128 /**
1129 * Returns a non-localized string representing a given network type.
1130 * ONLY used for debugging output.
1131 * @param type the type needing naming
1132 * @return a String for the given type, or a string version of the type ("87")
1133 * if no name is known.
1134 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1135 * {@hide}
1136 */
1137 @Deprecated
1138 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1139 public static String getNetworkTypeName(int type) {
1140 switch (type) {
1141 case TYPE_NONE:
1142 return "NONE";
1143 case TYPE_MOBILE:
1144 return "MOBILE";
1145 case TYPE_WIFI:
1146 return "WIFI";
1147 case TYPE_MOBILE_MMS:
1148 return "MOBILE_MMS";
1149 case TYPE_MOBILE_SUPL:
1150 return "MOBILE_SUPL";
1151 case TYPE_MOBILE_DUN:
1152 return "MOBILE_DUN";
1153 case TYPE_MOBILE_HIPRI:
1154 return "MOBILE_HIPRI";
1155 case TYPE_WIMAX:
1156 return "WIMAX";
1157 case TYPE_BLUETOOTH:
1158 return "BLUETOOTH";
1159 case TYPE_DUMMY:
1160 return "DUMMY";
1161 case TYPE_ETHERNET:
1162 return "ETHERNET";
1163 case TYPE_MOBILE_FOTA:
1164 return "MOBILE_FOTA";
1165 case TYPE_MOBILE_IMS:
1166 return "MOBILE_IMS";
1167 case TYPE_MOBILE_CBS:
1168 return "MOBILE_CBS";
1169 case TYPE_WIFI_P2P:
1170 return "WIFI_P2P";
1171 case TYPE_MOBILE_IA:
1172 return "MOBILE_IA";
1173 case TYPE_MOBILE_EMERGENCY:
1174 return "MOBILE_EMERGENCY";
1175 case TYPE_PROXY:
1176 return "PROXY";
1177 case TYPE_VPN:
1178 return "VPN";
Junyu Laic9f1ca62022-07-25 16:31:59 +08001179 case TYPE_TEST:
1180 return "TEST";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001181 default:
1182 return Integer.toString(type);
1183 }
1184 }
1185
1186 /**
1187 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001188 */
lucaslin10774b72021-03-17 14:16:01 +08001189 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001190 public void systemReady() {
1191 try {
1192 mService.systemReady();
1193 } catch (RemoteException e) {
1194 throw e.rethrowFromSystemServer();
1195 }
1196 }
1197
1198 /**
1199 * Checks if a given type uses the cellular data connection.
1200 * This should be replaced in the future by a network property.
1201 * @param networkType the type to check
1202 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1203 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1204 * {@hide}
1205 */
1206 @Deprecated
1207 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1208 public static boolean isNetworkTypeMobile(int networkType) {
1209 switch (networkType) {
1210 case TYPE_MOBILE:
1211 case TYPE_MOBILE_MMS:
1212 case TYPE_MOBILE_SUPL:
1213 case TYPE_MOBILE_DUN:
1214 case TYPE_MOBILE_HIPRI:
1215 case TYPE_MOBILE_FOTA:
1216 case TYPE_MOBILE_IMS:
1217 case TYPE_MOBILE_CBS:
1218 case TYPE_MOBILE_IA:
1219 case TYPE_MOBILE_EMERGENCY:
1220 return true;
1221 default:
1222 return false;
1223 }
1224 }
1225
1226 /**
1227 * Checks if the given network type is backed by a Wi-Fi radio.
1228 *
1229 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1230 * @hide
1231 */
1232 @Deprecated
1233 public static boolean isNetworkTypeWifi(int networkType) {
1234 switch (networkType) {
1235 case TYPE_WIFI:
1236 case TYPE_WIFI_P2P:
1237 return true;
1238 default:
1239 return false;
1240 }
1241 }
1242
1243 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001244 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001245 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Junyu Lai35665cc2022-12-19 17:37:48 +08001246 * Specify that the traffic for this user should by follow the default rules:
1247 * applications in the profile designated by the UserHandle behave like any
1248 * other application and use the system default network as their default
1249 * network. Compare other PROFILE_NETWORK_PREFERENCE_* settings.
Chalard Jeanad565e22021-02-25 17:23:40 +09001250 * @hide
1251 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001252 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001253 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1254
1255 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001256 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001257 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001258 * Specify that the traffic for this user should by default go on a network with
1259 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1260 * if no such network is available.
1261 * @hide
1262 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001263 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001264 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1265
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001266 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001267 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001268 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001269 * Specify that the traffic for this user should by default go on a network with
1270 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
Junyu Lai35665cc2022-12-19 17:37:48 +08001271 * should not have a default network at all (that is, network accesses that
1272 * do not specify a network explicitly terminate with an error), even if there
1273 * is a system default network available to apps outside this preference.
1274 * The apps can still use a non-enterprise network if they request it explicitly
1275 * provided that specific network doesn't require any specific permission they
1276 * do not hold.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001277 * @hide
1278 */
1279 @SystemApi(client = MODULE_LIBRARIES)
1280 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1281
Junyu Lai35665cc2022-12-19 17:37:48 +08001282 /**
1283 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
1284 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1285 * Specify that the traffic for this user should by default go on a network with
1286 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}.
1287 * If there is no such network, the apps will have no default
1288 * network at all, even if there are available non-enterprise networks on the
1289 * device (that is, network accesses that do not specify a network explicitly
1290 * terminate with an error). Additionally, the designated apps should be
1291 * blocked from using any non-enterprise network even if they specify it
1292 * explicitly, unless they hold specific privilege overriding this (see
1293 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS}).
1294 * @hide
1295 */
1296 @SystemApi(client = MODULE_LIBRARIES)
1297 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING = 3;
1298
Chalard Jeanad565e22021-02-25 17:23:40 +09001299 /** @hide */
1300 @Retention(RetentionPolicy.SOURCE)
1301 @IntDef(value = {
1302 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001303 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1304 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001305 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001306 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001307 }
1308
1309 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001310 * Specifies the preferred network type. When the device has more
1311 * than one type available the preferred network type will be used.
1312 *
1313 * @param preference the network type to prefer over all others. It is
1314 * unspecified what happens to the old preferred network in the
1315 * overall ordering.
1316 * @deprecated Functionality has been removed as it no longer makes sense,
1317 * with many more than two networks - we'd need an array to express
1318 * preference. Instead we use dynamic network properties of
1319 * the networks to describe their precedence.
1320 */
1321 @Deprecated
1322 public void setNetworkPreference(int preference) {
1323 }
1324
1325 /**
1326 * Retrieves the current preferred network type.
1327 *
1328 * @return an integer representing the preferred network type
1329 *
1330 * @deprecated Functionality has been removed as it no longer makes sense,
1331 * with many more than two networks - we'd need an array to express
1332 * preference. Instead we use dynamic network properties of
1333 * the networks to describe their precedence.
1334 */
1335 @Deprecated
1336 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1337 public int getNetworkPreference() {
1338 return TYPE_NONE;
1339 }
1340
1341 /**
1342 * Returns details about the currently active default data network. When
1343 * connected, this network is the default route for outgoing connections.
1344 * You should always check {@link NetworkInfo#isConnected()} before initiating
1345 * network traffic. This may return {@code null} when there is no default
1346 * network.
1347 * Note that if the default network is a VPN, this method will return the
1348 * NetworkInfo for one of its underlying networks instead, or null if the
1349 * VPN agent did not specify any. Apps interested in learning about VPNs
1350 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1351 *
1352 * @return a {@link NetworkInfo} object for the current default network
1353 * or {@code null} if no default network is currently active
1354 * @deprecated See {@link NetworkInfo}.
1355 */
1356 @Deprecated
1357 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1358 @Nullable
1359 public NetworkInfo getActiveNetworkInfo() {
1360 try {
1361 return mService.getActiveNetworkInfo();
1362 } catch (RemoteException e) {
1363 throw e.rethrowFromSystemServer();
1364 }
1365 }
1366
1367 /**
1368 * Returns a {@link Network} object corresponding to the currently active
1369 * default data network. In the event that the current active default data
1370 * network disconnects, the returned {@code Network} object will no longer
1371 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001372 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001373 *
1374 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001375 * {@code null} if no default network is currently active or if
1376 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001377 */
1378 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1379 @Nullable
1380 public Network getActiveNetwork() {
1381 try {
1382 return mService.getActiveNetwork();
1383 } catch (RemoteException e) {
1384 throw e.rethrowFromSystemServer();
1385 }
1386 }
1387
1388 /**
1389 * Returns a {@link Network} object corresponding to the currently active
1390 * default data network for a specific UID. In the event that the default data
1391 * network disconnects, the returned {@code Network} object will no longer
1392 * be usable. This will return {@code null} when there is no default
1393 * network for the UID.
1394 *
1395 * @return a {@link Network} object for the current default network for the
1396 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001397 *
1398 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001399 */
1400 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1401 @Nullable
1402 public Network getActiveNetworkForUid(int uid) {
1403 return getActiveNetworkForUid(uid, false);
1404 }
1405
1406 /** {@hide} */
1407 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1408 try {
1409 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1410 } catch (RemoteException e) {
1411 throw e.rethrowFromSystemServer();
1412 }
1413 }
1414
lucaslin3ba7cc22022-12-19 02:35:33 +00001415 private static UidRange[] getUidRangeArray(@NonNull Collection<Range<Integer>> ranges) {
1416 Objects.requireNonNull(ranges);
1417 final UidRange[] rangesArray = new UidRange[ranges.size()];
1418 int index = 0;
1419 for (Range<Integer> range : ranges) {
1420 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1421 }
1422
1423 return rangesArray;
1424 }
1425
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001426 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001427 * Adds or removes a requirement for given UID ranges to use the VPN.
1428 *
1429 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1430 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1431 * otherwise have permission to bypass the VPN (e.g., because they have the
1432 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1433 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1434 * set to {@code false}, a previously-added restriction is removed.
1435 * <p>
1436 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1437 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1438 * remove a previously-added range, the exact range must be removed as is.
1439 * <p>
1440 * The changes are applied asynchronously and may not have been applied by the time the method
1441 * returns. Apps will be notified about any changes that apply to them via
1442 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1443 * effect.
1444 * <p>
lucaslin3ba7cc22022-12-19 02:35:33 +00001445 * This method will block the specified UIDs from accessing non-VPN networks, but does not
1446 * affect what the UIDs get as their default network.
1447 * Compare {@link #setVpnDefaultForUids(String, Collection)}, which declares that the UIDs
1448 * should only have a VPN as their default network, but does not block them from accessing other
1449 * networks if they request them explicitly with the {@link Network} API.
1450 * <p>
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001451 * This method should be called only by the VPN code.
1452 *
1453 * @param ranges the UID ranges to restrict
1454 * @param requireVpn whether the specified UID ranges must use a VPN
1455 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001456 * @hide
1457 */
1458 @RequiresPermission(anyOf = {
1459 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001460 android.Manifest.permission.NETWORK_STACK,
1461 android.Manifest.permission.NETWORK_SETTINGS})
1462 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001463 public void setRequireVpnForUids(boolean requireVpn,
1464 @NonNull Collection<Range<Integer>> ranges) {
1465 Objects.requireNonNull(ranges);
1466 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1467 // This method is not necessarily expected to be used outside the system server, so
1468 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1469 // stack process, or by tests.
lucaslin3ba7cc22022-12-19 02:35:33 +00001470 final UidRange[] rangesArray = getUidRangeArray(ranges);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001471 try {
1472 mService.setRequireVpnForUids(requireVpn, rangesArray);
1473 } catch (RemoteException e) {
1474 throw e.rethrowFromSystemServer();
1475 }
1476 }
1477
1478 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001479 * Inform the system that this VPN session should manage the passed UIDs.
1480 *
1481 * A VPN with the specified session ID may call this method to inform the system that the UIDs
1482 * in the specified range are subject to a VPN.
1483 * When this is called, the system will only choose a VPN for the default network of the UIDs in
1484 * the specified ranges.
1485 *
1486 * This method declares that the UIDs in the range will only have a VPN for their default
1487 * network, but does not block the UIDs from accessing other networks (permissions allowing) by
1488 * explicitly requesting it with the {@link Network} API.
1489 * Compare {@link #setRequireVpnForUids(boolean, Collection)}, which does not affect what
1490 * network the UIDs get as default, but will block them from accessing non-VPN networks.
1491 *
1492 * @param session The VPN session which manages the passed UIDs.
1493 * @param ranges The uid ranges which will treat VPN as their only default network.
1494 *
1495 * @hide
1496 */
1497 @RequiresPermission(anyOf = {
1498 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1499 android.Manifest.permission.NETWORK_STACK,
1500 android.Manifest.permission.NETWORK_SETTINGS})
1501 @SystemApi(client = MODULE_LIBRARIES)
1502 public void setVpnDefaultForUids(@NonNull String session,
1503 @NonNull Collection<Range<Integer>> ranges) {
1504 Objects.requireNonNull(ranges);
1505 final UidRange[] rangesArray = getUidRangeArray(ranges);
1506 try {
1507 mService.setVpnNetworkPreference(session, rangesArray);
1508 } catch (RemoteException e) {
1509 throw e.rethrowFromSystemServer();
1510 }
1511 }
1512
1513 /**
chiachangwange0192a72023-02-06 13:25:01 +00001514 * Temporarily set automaticOnOff keeplaive TCP polling alarm timer to 1 second.
1515 *
1516 * TODO: Remove this when the TCP polling design is replaced with callback.
Jean Chalard17cbf062023-02-13 05:07:48 +00001517 * @param timeMs The time of expiry, with System.currentTimeMillis() base. The value should be
1518 * set no more than 5 minutes in the future.
chiachangwange0192a72023-02-06 13:25:01 +00001519 * @hide
1520 */
1521 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
1522 try {
1523 mService.setTestLowTcpPollingTimerForKeepalive(timeMs);
1524 } catch (RemoteException e) {
1525 throw e.rethrowFromSystemServer();
1526 }
1527 }
1528
1529 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001530 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1531 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1532 * but is still supported for backwards compatibility.
1533 * <p>
1534 * This type of VPN is assumed always to use the system default network, and must always declare
1535 * exactly one underlying network, which is the network that was the default when the VPN
1536 * connected.
1537 * <p>
1538 * Calling this method with {@code true} enables legacy behaviour, specifically:
1539 * <ul>
1540 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1541 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1542 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1543 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1544 * underlying the VPN.</li>
1545 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1546 * similarly replaced by the VPN network state.</li>
1547 * <li>Information on current network interfaces passed to NetworkStatsService will not
1548 * include any VPN interfaces.</li>
1549 * </ul>
1550 *
1551 * @param enabled whether legacy lockdown VPN is enabled or disabled
1552 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001553 * @hide
1554 */
1555 @RequiresPermission(anyOf = {
1556 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001557 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001558 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001559 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001560 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1561 try {
1562 mService.setLegacyLockdownVpnEnabled(enabled);
1563 } catch (RemoteException e) {
1564 throw e.rethrowFromSystemServer();
1565 }
1566 }
1567
1568 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001569 * Returns details about the currently active default data network for a given uid.
1570 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001571 *
1572 * @return a {@link NetworkInfo} object for the current default network
1573 * for the given uid or {@code null} if no default network is
1574 * available for the specified uid.
1575 *
1576 * {@hide}
1577 */
1578 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1579 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1580 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1581 return getActiveNetworkInfoForUid(uid, false);
1582 }
1583
1584 /** {@hide} */
1585 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1586 try {
1587 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1588 } catch (RemoteException e) {
1589 throw e.rethrowFromSystemServer();
1590 }
1591 }
1592
1593 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001594 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001595 *
1596 * @param networkType integer specifying which networkType in
1597 * which you're interested.
1598 * @return a {@link NetworkInfo} object for the requested
1599 * network type or {@code null} if the type is not
1600 * supported by the device. If {@code networkType} is
1601 * TYPE_VPN and a VPN is active for the calling app,
1602 * then this method will try to return one of the
1603 * underlying networks for the VPN or null if the
1604 * VPN agent didn't specify any.
1605 *
1606 * @deprecated This method does not support multiple connected networks
1607 * of the same type. Use {@link #getAllNetworks} and
1608 * {@link #getNetworkInfo(android.net.Network)} instead.
1609 */
1610 @Deprecated
1611 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1612 @Nullable
1613 public NetworkInfo getNetworkInfo(int networkType) {
1614 try {
1615 return mService.getNetworkInfo(networkType);
1616 } catch (RemoteException e) {
1617 throw e.rethrowFromSystemServer();
1618 }
1619 }
1620
1621 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001622 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001623 *
1624 * @param network {@link Network} specifying which network
1625 * in which you're interested.
1626 * @return a {@link NetworkInfo} object for the requested
1627 * network or {@code null} if the {@code Network}
1628 * is not valid.
1629 * @deprecated See {@link NetworkInfo}.
1630 */
1631 @Deprecated
1632 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1633 @Nullable
1634 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1635 return getNetworkInfoForUid(network, Process.myUid(), false);
1636 }
1637
1638 /** {@hide} */
1639 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1640 try {
1641 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1642 } catch (RemoteException e) {
1643 throw e.rethrowFromSystemServer();
1644 }
1645 }
1646
1647 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001648 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001649 *
1650 * @return an array of {@link NetworkInfo} objects. Check each
1651 * {@link NetworkInfo#getType} for which type each applies.
1652 *
1653 * @deprecated This method does not support multiple connected networks
1654 * of the same type. Use {@link #getAllNetworks} and
1655 * {@link #getNetworkInfo(android.net.Network)} instead.
1656 */
1657 @Deprecated
1658 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1659 @NonNull
1660 public NetworkInfo[] getAllNetworkInfo() {
1661 try {
1662 return mService.getAllNetworkInfo();
1663 } catch (RemoteException e) {
1664 throw e.rethrowFromSystemServer();
1665 }
1666 }
1667
1668 /**
junyulaib1211372021-03-03 12:09:05 +08001669 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1670 * connected.
1671 * @hide
1672 */
1673 @SystemApi(client = MODULE_LIBRARIES)
1674 @RequiresPermission(anyOf = {
1675 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1676 android.Manifest.permission.NETWORK_STACK,
1677 android.Manifest.permission.NETWORK_SETTINGS})
1678 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001679 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001680 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001681 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001682 } catch (RemoteException e) {
1683 throw e.rethrowFromSystemServer();
1684 }
1685 }
1686
1687 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001688 * Returns the {@link Network} object currently serving a given type, or
1689 * null if the given type is not connected.
1690 *
1691 * @hide
1692 * @deprecated This method does not support multiple connected networks
1693 * of the same type. Use {@link #getAllNetworks} and
1694 * {@link #getNetworkInfo(android.net.Network)} instead.
1695 */
1696 @Deprecated
1697 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1698 @UnsupportedAppUsage
1699 public Network getNetworkForType(int networkType) {
1700 try {
1701 return mService.getNetworkForType(networkType);
1702 } catch (RemoteException e) {
1703 throw e.rethrowFromSystemServer();
1704 }
1705 }
1706
1707 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001708 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001709 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001710 * @deprecated This method does not provide any notification of network state changes, forcing
1711 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1712 * Apps should use methods such as
1713 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1714 * Apps that desire to obtain information about networks that do not apply to them
1715 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1716 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001717 * @return an array of {@link Network} objects.
1718 */
1719 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1720 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001721 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001722 public Network[] getAllNetworks() {
1723 try {
1724 return mService.getAllNetworks();
1725 } catch (RemoteException e) {
1726 throw e.rethrowFromSystemServer();
1727 }
1728 }
1729
1730 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001731 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001732 * the Networks that applications run by the given user will use by default.
1733 * @hide
1734 */
1735 @UnsupportedAppUsage
1736 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1737 try {
1738 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001739 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001740 } catch (RemoteException e) {
1741 throw e.rethrowFromSystemServer();
1742 }
1743 }
1744
1745 /**
1746 * Returns the IP information for the current default network.
1747 *
1748 * @return a {@link LinkProperties} object describing the IP info
1749 * for the current default network, or {@code null} if there
1750 * is no current default network.
1751 *
1752 * {@hide}
1753 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1754 * value of {@link #getActiveNetwork()} instead. In particular,
1755 * this method will return non-null LinkProperties even if the
1756 * app is blocked by policy from using this network.
1757 */
1758 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1759 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1760 public LinkProperties getActiveLinkProperties() {
1761 try {
1762 return mService.getActiveLinkProperties();
1763 } catch (RemoteException e) {
1764 throw e.rethrowFromSystemServer();
1765 }
1766 }
1767
1768 /**
1769 * Returns the IP information for a given network type.
1770 *
1771 * @param networkType the network type of interest.
1772 * @return a {@link LinkProperties} object describing the IP info
1773 * for the given networkType, or {@code null} if there is
1774 * no current default network.
1775 *
1776 * {@hide}
1777 * @deprecated This method does not support multiple connected networks
1778 * of the same type. Use {@link #getAllNetworks},
1779 * {@link #getNetworkInfo(android.net.Network)}, and
1780 * {@link #getLinkProperties(android.net.Network)} instead.
1781 */
1782 @Deprecated
1783 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1784 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1785 public LinkProperties getLinkProperties(int networkType) {
1786 try {
1787 return mService.getLinkPropertiesForType(networkType);
1788 } catch (RemoteException e) {
1789 throw e.rethrowFromSystemServer();
1790 }
1791 }
1792
1793 /**
1794 * Get the {@link LinkProperties} for the given {@link Network}. This
1795 * will return {@code null} if the network is unknown.
1796 *
1797 * @param network The {@link Network} object identifying the network in question.
1798 * @return The {@link LinkProperties} for the network, or {@code null}.
1799 */
1800 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1801 @Nullable
1802 public LinkProperties getLinkProperties(@Nullable Network network) {
1803 try {
1804 return mService.getLinkProperties(network);
1805 } catch (RemoteException e) {
1806 throw e.rethrowFromSystemServer();
1807 }
1808 }
1809
1810 /**
lucaslinc582d502022-01-27 09:07:00 +08001811 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001812 *
lucaslinc582d502022-01-27 09:07:00 +08001813 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1814 * given package, considering its permissions.
1815 *
1816 * @param lp A {@link LinkProperties} which will be redacted.
1817 * @param uid The target uid.
1818 * @param packageName The name of the package, for appops logging.
1819 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1820 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1821 * @hide
1822 */
1823 @RequiresPermission(anyOf = {
1824 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1825 android.Manifest.permission.NETWORK_STACK,
1826 android.Manifest.permission.NETWORK_SETTINGS})
1827 @SystemApi(client = MODULE_LIBRARIES)
1828 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001829 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001830 @NonNull String packageName) {
1831 try {
lucaslind2b06132022-03-02 10:56:57 +08001832 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001833 lp, uid, packageName, getAttributionTag());
1834 } catch (RemoteException e) {
1835 throw e.rethrowFromSystemServer();
1836 }
1837 }
1838
1839 /**
1840 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1841 *
1842 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1843 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1844 * sensitive information. To retrieve this location sensitive information (subject to
1845 * the caller's location permissions), use a {@link NetworkCallback} with the
1846 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1847 *
1848 * This method returns {@code null} if the network is unknown or if the |network| argument
1849 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001850 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001851 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001852 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001853 */
1854 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1855 @Nullable
1856 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1857 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001858 return mService.getNetworkCapabilities(
1859 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001860 } catch (RemoteException e) {
1861 throw e.rethrowFromSystemServer();
1862 }
1863 }
1864
1865 /**
lucaslinc582d502022-01-27 09:07:00 +08001866 * Redact {@link NetworkCapabilities} for a given package.
1867 *
1868 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001869 * to the given package, considering its permissions. If the passed capabilities contain
1870 * location-sensitive information, they will be redacted to the correct degree for the location
1871 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1872 * that level of location. If the UID holds no location permission, the returned object will
1873 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001874 *
1875 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1876 * @param uid The target uid.
1877 * @param packageName The name of the package, for appops logging.
1878 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1879 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1880 * @hide
1881 */
1882 @RequiresPermission(anyOf = {
1883 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1884 android.Manifest.permission.NETWORK_STACK,
1885 android.Manifest.permission.NETWORK_SETTINGS})
1886 @SystemApi(client = MODULE_LIBRARIES)
1887 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001888 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001889 @NonNull NetworkCapabilities nc,
1890 int uid, @NonNull String packageName) {
1891 try {
lucaslind2b06132022-03-02 10:56:57 +08001892 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001893 getAttributionTag());
1894 } catch (RemoteException e) {
1895 throw e.rethrowFromSystemServer();
1896 }
1897 }
1898
1899 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001900 * Gets a URL that can be used for resolving whether a captive portal is present.
1901 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1902 * portal is present.
1903 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1904 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1905 *
1906 * The system network validation may be using different strategies to detect captive portals,
1907 * so this method does not necessarily return a URL used by the system. It only returns a URL
1908 * that may be relevant for other components trying to detect captive portals.
1909 *
1910 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001911 * @deprecated This API returns a URL which is not guaranteed to be one of the URLs used by the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001912 * system.
1913 */
1914 @Deprecated
1915 @SystemApi
1916 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1917 public String getCaptivePortalServerUrl() {
1918 try {
1919 return mService.getCaptivePortalServerUrl();
1920 } catch (RemoteException e) {
1921 throw e.rethrowFromSystemServer();
1922 }
1923 }
1924
1925 /**
1926 * Tells the underlying networking system that the caller wants to
1927 * begin using the named feature. The interpretation of {@code feature}
1928 * is completely up to each networking implementation.
1929 *
1930 * <p>This method requires the caller to hold either the
1931 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1932 * or the ability to modify system settings as determined by
1933 * {@link android.provider.Settings.System#canWrite}.</p>
1934 *
1935 * @param networkType specifies which network the request pertains to
1936 * @param feature the name of the feature to be used
1937 * @return an integer value representing the outcome of the request.
1938 * The interpretation of this value is specific to each networking
1939 * implementation+feature combination, except that the value {@code -1}
1940 * always indicates failure.
1941 *
1942 * @deprecated Deprecated in favor of the cleaner
1943 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1944 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1945 * throw {@code UnsupportedOperationException} if called.
1946 * @removed
1947 */
1948 @Deprecated
1949 public int startUsingNetworkFeature(int networkType, String feature) {
1950 checkLegacyRoutingApiAccess();
1951 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1952 if (netCap == null) {
1953 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1954 feature);
1955 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1956 }
1957
1958 NetworkRequest request = null;
1959 synchronized (sLegacyRequests) {
1960 LegacyRequest l = sLegacyRequests.get(netCap);
1961 if (l != null) {
1962 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1963 renewRequestLocked(l);
1964 if (l.currentNetwork != null) {
1965 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1966 } else {
1967 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1968 }
1969 }
1970
1971 request = requestNetworkForFeatureLocked(netCap);
1972 }
1973 if (request != null) {
1974 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1975 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1976 } else {
1977 Log.d(TAG, " request Failed");
1978 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1979 }
1980 }
1981
1982 /**
1983 * Tells the underlying networking system that the caller is finished
1984 * using the named feature. The interpretation of {@code feature}
1985 * is completely up to each networking implementation.
1986 *
1987 * <p>This method requires the caller to hold either the
1988 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1989 * or the ability to modify system settings as determined by
1990 * {@link android.provider.Settings.System#canWrite}.</p>
1991 *
1992 * @param networkType specifies which network the request pertains to
1993 * @param feature the name of the feature that is no longer needed
1994 * @return an integer value representing the outcome of the request.
1995 * The interpretation of this value is specific to each networking
1996 * implementation+feature combination, except that the value {@code -1}
1997 * always indicates failure.
1998 *
1999 * @deprecated Deprecated in favor of the cleaner
2000 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
2001 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2002 * throw {@code UnsupportedOperationException} if called.
2003 * @removed
2004 */
2005 @Deprecated
2006 public int stopUsingNetworkFeature(int networkType, String feature) {
2007 checkLegacyRoutingApiAccess();
2008 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
2009 if (netCap == null) {
2010 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
2011 feature);
2012 return -1;
2013 }
2014
2015 if (removeRequestForFeature(netCap)) {
2016 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
2017 }
2018 return 1;
2019 }
2020
2021 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2022 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
2023 if (networkType == TYPE_MOBILE) {
2024 switch (feature) {
2025 case "enableCBS":
2026 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
2027 case "enableDUN":
2028 case "enableDUNAlways":
2029 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
2030 case "enableFOTA":
2031 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
2032 case "enableHIPRI":
2033 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
2034 case "enableIMS":
2035 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
2036 case "enableMMS":
2037 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
2038 case "enableSUPL":
2039 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
2040 default:
2041 return null;
2042 }
2043 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
2044 return networkCapabilitiesForType(TYPE_WIFI_P2P);
2045 }
2046 return null;
2047 }
2048
2049 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
2050 if (netCap == null) return TYPE_NONE;
2051 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
2052 return TYPE_MOBILE_CBS;
2053 }
2054 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2055 return TYPE_MOBILE_IMS;
2056 }
2057 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
2058 return TYPE_MOBILE_FOTA;
2059 }
2060 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
2061 return TYPE_MOBILE_DUN;
2062 }
2063 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
2064 return TYPE_MOBILE_SUPL;
2065 }
2066 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2067 return TYPE_MOBILE_MMS;
2068 }
2069 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
2070 return TYPE_MOBILE_HIPRI;
2071 }
2072 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
2073 return TYPE_WIFI_P2P;
2074 }
2075 return TYPE_NONE;
2076 }
2077
2078 private static class LegacyRequest {
2079 NetworkCapabilities networkCapabilities;
2080 NetworkRequest networkRequest;
2081 int expireSequenceNumber;
2082 Network currentNetwork;
2083 int delay = -1;
2084
2085 private void clearDnsBinding() {
2086 if (currentNetwork != null) {
2087 currentNetwork = null;
2088 setProcessDefaultNetworkForHostResolution(null);
2089 }
2090 }
2091
2092 NetworkCallback networkCallback = new NetworkCallback() {
2093 @Override
2094 public void onAvailable(Network network) {
2095 currentNetwork = network;
2096 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
2097 setProcessDefaultNetworkForHostResolution(network);
2098 }
2099 @Override
2100 public void onLost(Network network) {
2101 if (network.equals(currentNetwork)) clearDnsBinding();
2102 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2103 }
2104 };
2105 }
2106
2107 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2108 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2109 new HashMap<>();
2110
2111 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2112 synchronized (sLegacyRequests) {
2113 LegacyRequest l = sLegacyRequests.get(netCap);
2114 if (l != null) return l.networkRequest;
2115 }
2116 return null;
2117 }
2118
2119 private void renewRequestLocked(LegacyRequest l) {
2120 l.expireSequenceNumber++;
2121 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2122 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2123 }
2124
2125 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2126 int ourSeqNum = -1;
2127 synchronized (sLegacyRequests) {
2128 LegacyRequest l = sLegacyRequests.get(netCap);
2129 if (l == null) return;
2130 ourSeqNum = l.expireSequenceNumber;
2131 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2132 }
2133 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2134 }
2135
2136 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2137 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2138 int delay = -1;
2139 int type = legacyTypeForNetworkCapabilities(netCap);
2140 try {
2141 delay = mService.getRestoreDefaultNetworkDelay(type);
2142 } catch (RemoteException e) {
2143 throw e.rethrowFromSystemServer();
2144 }
2145 LegacyRequest l = new LegacyRequest();
2146 l.networkCapabilities = netCap;
2147 l.delay = delay;
2148 l.expireSequenceNumber = 0;
2149 l.networkRequest = sendRequestForNetwork(
2150 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2151 if (l.networkRequest == null) return null;
2152 sLegacyRequests.put(netCap, l);
2153 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2154 return l.networkRequest;
2155 }
2156
2157 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2158 if (delay >= 0) {
2159 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2160 CallbackHandler handler = getDefaultHandler();
2161 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2162 handler.sendMessageDelayed(msg, delay);
2163 }
2164 }
2165
2166 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2167 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2168 final LegacyRequest l;
2169 synchronized (sLegacyRequests) {
2170 l = sLegacyRequests.remove(netCap);
2171 }
2172 if (l == null) return false;
2173 unregisterNetworkCallback(l.networkCallback);
2174 l.clearDnsBinding();
2175 return true;
2176 }
2177
2178 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2179 static {
2180 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2181 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2182 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2183 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2184 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2185 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2186 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2187 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2188 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2189 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2190 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2191 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2192 }
2193
2194 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2195 static {
2196 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2197 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2198 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2199 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2200 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2201 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2202 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2203 }
2204
2205 /**
2206 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2207 * instance suitable for registering a request or callback. Throws an
2208 * IllegalArgumentException if no mapping from the legacy type to
2209 * NetworkCapabilities is known.
2210 *
2211 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2212 * to find the network instead.
2213 * @hide
2214 */
2215 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2216 final NetworkCapabilities nc = new NetworkCapabilities();
2217
2218 // Map from type to transports.
2219 final int NOT_FOUND = -1;
2220 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002221 if (transport == NOT_FOUND) {
2222 throw new IllegalArgumentException("unknown legacy type: " + type);
2223 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002224 nc.addTransportType(transport);
2225
2226 // Map from type to capabilities.
2227 nc.addCapability(sLegacyTypeToCapability.get(
2228 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2229 nc.maybeMarkCapabilitiesRestricted();
2230 return nc;
2231 }
2232
2233 /** @hide */
2234 public static class PacketKeepaliveCallback {
2235 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2236 public PacketKeepaliveCallback() {
2237 }
2238 /** The requested keepalive was successfully started. */
2239 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2240 public void onStarted() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002241 /** The keepalive was resumed after being paused by the system. */
2242 public void onResumed() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002243 /** The keepalive was successfully stopped. */
2244 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2245 public void onStopped() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002246 /** The keepalive was paused automatically by the system. */
2247 public void onPaused() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002248 /** An error occurred. */
2249 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2250 public void onError(int error) {}
2251 }
2252
2253 /**
2254 * Allows applications to request that the system periodically send specific packets on their
2255 * behalf, using hardware offload to save battery power.
2256 *
2257 * To request that the system send keepalives, call one of the methods that return a
2258 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2259 * passing in a non-null callback. If the callback is successfully started, the callback's
2260 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2261 * specifying one of the {@code ERROR_*} constants in this class.
2262 *
2263 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2264 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2265 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2266 *
2267 * @deprecated Use {@link SocketKeepalive} instead.
2268 *
2269 * @hide
2270 */
2271 public class PacketKeepalive {
2272
2273 private static final String TAG = "PacketKeepalive";
2274
2275 /** @hide */
2276 public static final int SUCCESS = 0;
2277
2278 /** @hide */
2279 public static final int NO_KEEPALIVE = -1;
2280
2281 /** @hide */
2282 public static final int BINDER_DIED = -10;
2283
2284 /** The specified {@code Network} is not connected. */
2285 public static final int ERROR_INVALID_NETWORK = -20;
2286 /** The specified IP addresses are invalid. For example, the specified source IP address is
2287 * not configured on the specified {@code Network}. */
2288 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2289 /** The requested port is invalid. */
2290 public static final int ERROR_INVALID_PORT = -22;
2291 /** The packet length is invalid (e.g., too long). */
2292 public static final int ERROR_INVALID_LENGTH = -23;
2293 /** The packet transmission interval is invalid (e.g., too short). */
2294 public static final int ERROR_INVALID_INTERVAL = -24;
2295
2296 /** The hardware does not support this request. */
2297 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2298 /** The hardware returned an error. */
2299 public static final int ERROR_HARDWARE_ERROR = -31;
2300
2301 /** The NAT-T destination port for IPsec */
2302 public static final int NATT_PORT = 4500;
2303
2304 /** The minimum interval in seconds between keepalive packet transmissions */
2305 public static final int MIN_INTERVAL = 10;
2306
2307 private final Network mNetwork;
2308 private final ISocketKeepaliveCallback mCallback;
2309 private final ExecutorService mExecutor;
2310
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002311 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2312 public void stop() {
2313 try {
2314 mExecutor.execute(() -> {
2315 try {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002316 mService.stopKeepalive(mCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002317 } catch (RemoteException e) {
2318 Log.e(TAG, "Error stopping packet keepalive: ", e);
2319 throw e.rethrowFromSystemServer();
2320 }
2321 });
2322 } catch (RejectedExecutionException e) {
2323 // The internal executor has already stopped due to previous event.
2324 }
2325 }
2326
2327 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002328 Objects.requireNonNull(network, "network cannot be null");
2329 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002330 mNetwork = network;
2331 mExecutor = Executors.newSingleThreadExecutor();
2332 mCallback = new ISocketKeepaliveCallback.Stub() {
2333 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002334 public void onStarted() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002335 final long token = Binder.clearCallingIdentity();
2336 try {
2337 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002338 callback.onStarted();
2339 });
2340 } finally {
2341 Binder.restoreCallingIdentity(token);
2342 }
2343 }
2344
2345 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002346 public void onResumed() {
2347 final long token = Binder.clearCallingIdentity();
2348 try {
2349 mExecutor.execute(() -> {
2350 callback.onResumed();
2351 });
2352 } finally {
2353 Binder.restoreCallingIdentity(token);
2354 }
2355 }
2356
2357 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002358 public void onStopped() {
2359 final long token = Binder.clearCallingIdentity();
2360 try {
2361 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002362 callback.onStopped();
2363 });
2364 } finally {
2365 Binder.restoreCallingIdentity(token);
2366 }
2367 mExecutor.shutdown();
2368 }
2369
2370 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002371 public void onPaused() {
2372 final long token = Binder.clearCallingIdentity();
2373 try {
2374 mExecutor.execute(() -> {
2375 callback.onPaused();
2376 });
2377 } finally {
2378 Binder.restoreCallingIdentity(token);
2379 }
2380 mExecutor.shutdown();
2381 }
2382
2383 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002384 public void onError(int error) {
2385 final long token = Binder.clearCallingIdentity();
2386 try {
2387 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002388 callback.onError(error);
2389 });
2390 } finally {
2391 Binder.restoreCallingIdentity(token);
2392 }
2393 mExecutor.shutdown();
2394 }
2395
2396 @Override
2397 public void onDataReceived() {
2398 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2399 // this callback when data is received.
2400 }
2401 };
2402 }
2403 }
2404
2405 /**
2406 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2407 *
2408 * @deprecated Use {@link #createSocketKeepalive} instead.
2409 *
2410 * @hide
2411 */
2412 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2413 public PacketKeepalive startNattKeepalive(
2414 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2415 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2416 final PacketKeepalive k = new PacketKeepalive(network, callback);
2417 try {
2418 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2419 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2420 } catch (RemoteException e) {
2421 Log.e(TAG, "Error starting packet keepalive: ", e);
2422 throw e.rethrowFromSystemServer();
2423 }
2424 return k;
2425 }
2426
2427 // Construct an invalid fd.
2428 private ParcelFileDescriptor createInvalidFd() {
2429 final int invalidFd = -1;
2430 return ParcelFileDescriptor.adoptFd(invalidFd);
2431 }
2432
2433 /**
2434 * Request that keepalives be started on a IPsec NAT-T socket.
2435 *
2436 * @param network The {@link Network} the socket is on.
2437 * @param socket The socket that needs to be kept alive.
2438 * @param source The source address of the {@link UdpEncapsulationSocket}.
2439 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2440 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2441 * must run callback sequentially, otherwise the order of callbacks cannot be
2442 * guaranteed.
2443 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2444 * changes. Must be extended by applications that use this API.
2445 *
2446 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2447 * given socket.
2448 **/
2449 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2450 @NonNull UdpEncapsulationSocket socket,
2451 @NonNull InetAddress source,
2452 @NonNull InetAddress destination,
2453 @NonNull @CallbackExecutor Executor executor,
2454 @NonNull Callback callback) {
2455 ParcelFileDescriptor dup;
2456 try {
2457 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2458 // which cannot be obtained by the app process.
2459 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2460 } catch (IOException ignored) {
2461 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2462 // ERROR_INVALID_SOCKET.
2463 dup = createInvalidFd();
2464 }
2465 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2466 destination, executor, callback);
2467 }
2468
2469 /**
2470 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2471 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2472 *
2473 * @param network The {@link Network} the socket is on.
2474 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2475 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2476 * from that port.
2477 * @param source The source address of the {@link UdpEncapsulationSocket}.
2478 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2479 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2480 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2481 * must run callback sequentially, otherwise the order of callbacks cannot be
2482 * guaranteed.
2483 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2484 * changes. Must be extended by applications that use this API.
2485 *
2486 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2487 * given socket.
2488 * @hide
2489 */
2490 @SystemApi
2491 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2492 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2493 @NonNull ParcelFileDescriptor pfd,
2494 @NonNull InetAddress source,
2495 @NonNull InetAddress destination,
2496 @NonNull @CallbackExecutor Executor executor,
2497 @NonNull Callback callback) {
2498 ParcelFileDescriptor dup;
2499 try {
2500 // TODO: Consider remove unnecessary dup.
2501 dup = pfd.dup();
2502 } catch (IOException ignored) {
2503 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2504 // ERROR_INVALID_SOCKET.
2505 dup = createInvalidFd();
2506 }
2507 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002508 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002509 }
2510
2511 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002512 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002513 *
2514 * @param network The {@link Network} the socket is on.
2515 * @param socket The socket that needs to be kept alive.
2516 * @param executor The executor on which callback will be invoked. This implementation assumes
2517 * the provided {@link Executor} runs the callbacks in sequence with no
2518 * concurrency. Failing this, no guarantee of correctness can be made. It is
2519 * the responsibility of the caller to ensure the executor provides this
2520 * guarantee. A simple way of creating such an executor is with the standard
2521 * tool {@code Executors.newSingleThreadExecutor}.
2522 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2523 * changes. Must be extended by applications that use this API.
2524 *
2525 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2526 * given socket.
2527 * @hide
2528 */
2529 @SystemApi
2530 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2531 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2532 @NonNull Socket socket,
Sherri Lin443b7182023-02-08 04:49:29 +01002533 @NonNull @CallbackExecutor Executor executor,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002534 @NonNull Callback callback) {
2535 ParcelFileDescriptor dup;
2536 try {
2537 dup = ParcelFileDescriptor.fromSocket(socket);
2538 } catch (UncheckedIOException ignored) {
2539 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2540 // ERROR_INVALID_SOCKET.
2541 dup = createInvalidFd();
2542 }
2543 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2544 }
2545
2546 /**
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +09002547 * Get the supported keepalive count for each transport configured in resource overlays.
2548 *
2549 * @return An array of supported keepalive count for each transport type.
2550 * @hide
2551 */
2552 @RequiresPermission(anyOf = { android.Manifest.permission.NETWORK_SETTINGS,
2553 // CTS 13 used QUERY_ALL_PACKAGES to get the resource value, which was implemented
2554 // as below in KeepaliveUtils. Also allow that permission so that KeepaliveUtils can
2555 // use this method and avoid breaking released CTS. Apps that have this permission
2556 // can query the resource themselves anyway.
2557 android.Manifest.permission.QUERY_ALL_PACKAGES })
2558 public int[] getSupportedKeepalives() {
2559 try {
2560 return mService.getSupportedKeepalives();
2561 } catch (RemoteException e) {
2562 throw e.rethrowFromSystemServer();
2563 }
2564 }
2565
2566 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002567 * Ensure that a network route exists to deliver traffic to the specified
2568 * host via the specified network interface. An attempt to add a route that
2569 * already exists is ignored, but treated as successful.
2570 *
2571 * <p>This method requires the caller to hold either the
2572 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2573 * or the ability to modify system settings as determined by
2574 * {@link android.provider.Settings.System#canWrite}.</p>
2575 *
2576 * @param networkType the type of the network over which traffic to the specified
2577 * host is to be routed
2578 * @param hostAddress the IP address of the host to which the route is desired
2579 * @return {@code true} on success, {@code false} on failure
2580 *
2581 * @deprecated Deprecated in favor of the
2582 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2583 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2584 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2585 * throw {@code UnsupportedOperationException} if called.
2586 * @removed
2587 */
2588 @Deprecated
2589 public boolean requestRouteToHost(int networkType, int hostAddress) {
2590 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2591 }
2592
2593 /**
2594 * Ensure that a network route exists to deliver traffic to the specified
2595 * host via the specified network interface. An attempt to add a route that
2596 * already exists is ignored, but treated as successful.
2597 *
2598 * <p>This method requires the caller to hold either the
2599 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2600 * or the ability to modify system settings as determined by
2601 * {@link android.provider.Settings.System#canWrite}.</p>
2602 *
2603 * @param networkType the type of the network over which traffic to the specified
2604 * host is to be routed
2605 * @param hostAddress the IP address of the host to which the route is desired
2606 * @return {@code true} on success, {@code false} on failure
2607 * @hide
2608 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2609 * {@link #bindProcessToNetwork} API.
2610 */
2611 @Deprecated
2612 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002613 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002614 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2615 checkLegacyRoutingApiAccess();
2616 try {
2617 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2618 mContext.getOpPackageName(), getAttributionTag());
2619 } catch (RemoteException e) {
2620 throw e.rethrowFromSystemServer();
2621 }
2622 }
2623
2624 /**
2625 * @return the context's attribution tag
2626 */
2627 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2628 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002629 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002630 }
2631
2632 /**
2633 * Returns the value of the setting for background data usage. If false,
2634 * applications should not use the network if the application is not in the
2635 * foreground. Developers should respect this setting, and check the value
2636 * of this before performing any background data operations.
2637 * <p>
2638 * All applications that have background services that use the network
2639 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2640 * <p>
2641 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2642 * background data depends on several combined factors, and this method will
2643 * always return {@code true}. Instead, when background data is unavailable,
2644 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2645 *
2646 * @return Whether background data usage is allowed.
2647 */
2648 @Deprecated
2649 public boolean getBackgroundDataSetting() {
2650 // assume that background data is allowed; final authority is
2651 // NetworkInfo which may be blocked.
2652 return true;
2653 }
2654
2655 /**
2656 * Sets the value of the setting for background data usage.
2657 *
2658 * @param allowBackgroundData Whether an application should use data while
2659 * it is in the background.
2660 *
2661 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2662 * @see #getBackgroundDataSetting()
2663 * @hide
2664 */
2665 @Deprecated
2666 @UnsupportedAppUsage
2667 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2668 // ignored
2669 }
2670
2671 /**
2672 * @hide
2673 * @deprecated Talk to TelephonyManager directly
2674 */
2675 @Deprecated
2676 @UnsupportedAppUsage
2677 public boolean getMobileDataEnabled() {
2678 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2679 if (tm != null) {
2680 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2681 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2682 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2683 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2684 + " retVal=" + retVal);
2685 return retVal;
2686 }
2687 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2688 return false;
2689 }
2690
2691 /**
2692 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2693 * to find out when the system default network has gone in to a high power state.
2694 */
2695 public interface OnNetworkActiveListener {
2696 /**
2697 * Called on the main thread of the process to report that the current data network
2698 * has become active, and it is now a good time to perform any pending network
2699 * operations. Note that this listener only tells you when the network becomes
2700 * active; if at any other time you want to know whether it is active (and thus okay
2701 * to initiate network traffic), you can retrieve its instantaneous state with
2702 * {@link ConnectivityManager#isDefaultNetworkActive}.
2703 */
2704 void onNetworkActive();
2705 }
2706
Chiachang Wang2de41682021-09-23 10:46:03 +08002707 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002708 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2709 mNetworkActivityListeners = new ArrayMap<>();
2710
2711 /**
2712 * Start listening to reports when the system's default data network is active, meaning it is
2713 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2714 * to determine the current state of the system's default network after registering the
2715 * listener.
2716 * <p>
2717 * If the process default network has been set with
2718 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2719 * reflect the process's default, but the system default.
2720 *
2721 * @param l The listener to be told when the network is active.
2722 */
2723 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002724 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002725 @Override
2726 public void onNetworkActive() throws RemoteException {
2727 l.onNetworkActive();
2728 }
2729 };
2730
Chiachang Wang2de41682021-09-23 10:46:03 +08002731 synchronized (mNetworkActivityListeners) {
2732 try {
2733 mService.registerNetworkActivityListener(rl);
2734 mNetworkActivityListeners.put(l, rl);
2735 } catch (RemoteException e) {
2736 throw e.rethrowFromSystemServer();
2737 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002738 }
2739 }
2740
2741 /**
2742 * Remove network active listener previously registered with
2743 * {@link #addDefaultNetworkActiveListener}.
2744 *
2745 * @param l Previously registered listener.
2746 */
2747 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002748 synchronized (mNetworkActivityListeners) {
2749 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2750 if (rl == null) {
2751 throw new IllegalArgumentException("Listener was not registered.");
2752 }
2753 try {
2754 mService.unregisterNetworkActivityListener(rl);
2755 mNetworkActivityListeners.remove(l);
2756 } catch (RemoteException e) {
2757 throw e.rethrowFromSystemServer();
2758 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002759 }
2760 }
2761
2762 /**
2763 * Return whether the data network is currently active. An active network means that
2764 * it is currently in a high power state for performing data transmission. On some
2765 * types of networks, it may be expensive to move and stay in such a state, so it is
2766 * more power efficient to batch network traffic together when the radio is already in
2767 * this state. This method tells you whether right now is currently a good time to
2768 * initiate network traffic, as the network is already active.
2769 */
2770 public boolean isDefaultNetworkActive() {
2771 try {
lucaslin709eb842021-01-21 02:04:15 +08002772 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002773 } catch (RemoteException e) {
2774 throw e.rethrowFromSystemServer();
2775 }
2776 }
2777
2778 /**
2779 * {@hide}
2780 */
2781 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002782 this(context, service, true /* newStatic */);
2783 }
2784
2785 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002786 mContext = Objects.requireNonNull(context, "missing context");
2787 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002788 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2789 // different ConnectivityManager, but that's still OK considering its usage.
2790 if (sInstance == null && newStatic) {
2791 final Context appContext = mContext.getApplicationContext();
2792 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2793 // If the application context is null, we're either in the system process or
2794 // it's the application context very early in app initialization. In both these
2795 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2796 // service. http://b/27532714 .
2797 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2798 false /* newStatic */);
2799 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002800 }
2801
2802 /** {@hide} */
2803 @UnsupportedAppUsage
2804 public static ConnectivityManager from(Context context) {
2805 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2806 }
2807
2808 /** @hide */
2809 public NetworkRequest getDefaultRequest() {
2810 try {
2811 // This is not racy as the default request is final in ConnectivityService.
2812 return mService.getDefaultRequest();
2813 } catch (RemoteException e) {
2814 throw e.rethrowFromSystemServer();
2815 }
2816 }
2817
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002818 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002819 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002820 * happened.
2821 *
2822 * @return {@code true} iff the package is allowed to write settings.
2823 */
2824 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2825 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2826 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2827 boolean throwException) {
2828 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002829 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002830 }
2831
2832 /**
2833 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2834 * situations where a Context pointer is unavailable.
2835 * @hide
2836 */
2837 @Deprecated
2838 static ConnectivityManager getInstanceOrNull() {
2839 return sInstance;
2840 }
2841
2842 /**
2843 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2844 * situations where a Context pointer is unavailable.
2845 * @hide
2846 */
2847 @Deprecated
2848 @UnsupportedAppUsage
2849 private static ConnectivityManager getInstance() {
2850 if (getInstanceOrNull() == null) {
2851 throw new IllegalStateException("No ConnectivityManager yet constructed");
2852 }
2853 return getInstanceOrNull();
2854 }
2855
2856 /**
2857 * Get the set of tetherable, available interfaces. This list is limited by
2858 * device configuration and current interface existence.
2859 *
2860 * @return an array of 0 or more Strings of tetherable interface names.
2861 *
2862 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2863 * {@hide}
2864 */
2865 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2866 @UnsupportedAppUsage
2867 @Deprecated
2868 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002869 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002870 }
2871
2872 /**
2873 * Get the set of tethered interfaces.
2874 *
2875 * @return an array of 0 or more String of currently tethered interface names.
2876 *
2877 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2878 * {@hide}
2879 */
2880 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2881 @UnsupportedAppUsage
2882 @Deprecated
2883 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002884 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002885 }
2886
2887 /**
2888 * Get the set of interface names which attempted to tether but
2889 * failed. Re-attempting to tether may cause them to reset to the Tethered
2890 * state. Alternatively, causing the interface to be destroyed and recreated
2891 * may cause them to reset to the available state.
2892 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2893 * information on the cause of the errors.
2894 *
2895 * @return an array of 0 or more String indicating the interface names
2896 * which failed to tether.
2897 *
2898 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2899 * {@hide}
2900 */
2901 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2902 @UnsupportedAppUsage
2903 @Deprecated
2904 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002905 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002906 }
2907
2908 /**
2909 * Get the set of tethered dhcp ranges.
2910 *
2911 * @deprecated This method is not supported.
2912 * TODO: remove this function when all of clients are removed.
2913 * {@hide}
2914 */
2915 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2916 @Deprecated
2917 public String[] getTetheredDhcpRanges() {
2918 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2919 }
2920
2921 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002922 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002923 * on the interface, forward and NAT IP packets and forward DNS requests
2924 * to the best active upstream network interface. Note that if no upstream
2925 * IP network interface is available, dhcp will still run and traffic will be
2926 * allowed between the tethered devices and this device, though upstream net
2927 * access will of course fail until an upstream network interface becomes
2928 * active.
2929 *
2930 * <p>This method requires the caller to hold either the
2931 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2932 * or the ability to modify system settings as determined by
2933 * {@link android.provider.Settings.System#canWrite}.</p>
2934 *
2935 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2936 * and WifiStateMachine which need direct access. All other clients should use
2937 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2938 * logic.</p>
2939 *
2940 * @param iface the interface name to tether.
2941 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2942 * @deprecated Use {@link TetheringManager#startTethering} instead
2943 *
2944 * {@hide}
2945 */
2946 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2947 @Deprecated
2948 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002949 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002950 }
2951
2952 /**
2953 * Stop tethering the named interface.
2954 *
2955 * <p>This method requires the caller to hold either the
2956 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2957 * or the ability to modify system settings as determined by
2958 * {@link android.provider.Settings.System#canWrite}.</p>
2959 *
2960 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2961 * and WifiStateMachine which need direct access. All other clients should use
2962 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2963 * logic.</p>
2964 *
2965 * @param iface the interface name to untether.
2966 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2967 *
2968 * {@hide}
2969 */
2970 @UnsupportedAppUsage
2971 @Deprecated
2972 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002973 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002974 }
2975
2976 /**
2977 * Check if the device allows for tethering. It may be disabled via
2978 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2979 * due to device configuration.
2980 *
2981 * <p>If this app does not have permission to use this API, it will always
2982 * return false rather than throw an exception.</p>
2983 *
2984 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2985 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2986 *
2987 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2988 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2989 *
2990 * @return a boolean - {@code true} indicating Tethering is supported.
2991 *
2992 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2993 * {@hide}
2994 */
2995 @SystemApi
2996 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2997 android.Manifest.permission.WRITE_SETTINGS})
2998 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002999 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003000 }
3001
3002 /**
3003 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
3004 *
3005 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
3006 * @hide
3007 */
3008 @SystemApi
3009 @Deprecated
3010 public static abstract class OnStartTetheringCallback {
3011 /**
3012 * Called when tethering has been successfully started.
3013 */
3014 public void onTetheringStarted() {}
3015
3016 /**
3017 * Called when starting tethering failed.
3018 */
3019 public void onTetheringFailed() {}
3020 }
3021
3022 /**
3023 * Convenient overload for
3024 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
3025 * handler to run on the current thread's {@link Looper}.
3026 *
3027 * @deprecated Use {@link TetheringManager#startTethering} instead.
3028 * @hide
3029 */
3030 @SystemApi
3031 @Deprecated
3032 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3033 public void startTethering(int type, boolean showProvisioningUi,
3034 final OnStartTetheringCallback callback) {
3035 startTethering(type, showProvisioningUi, callback, null);
3036 }
3037
3038 /**
3039 * Runs tether provisioning for the given type if needed and then starts tethering if
3040 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
3041 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
3042 * schedules tether provisioning re-checks if appropriate.
3043 *
3044 * @param type The type of tethering to start. Must be one of
3045 * {@link ConnectivityManager.TETHERING_WIFI},
3046 * {@link ConnectivityManager.TETHERING_USB}, or
3047 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3048 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
3049 * is one. This should be true the first time this function is called and also any time
3050 * the user can see this UI. It gives users information from their carrier about the
3051 * check failing and how they can sign up for tethering if possible.
3052 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
3053 * of the result of trying to tether.
3054 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3055 *
3056 * @deprecated Use {@link TetheringManager#startTethering} instead.
3057 * @hide
3058 */
3059 @SystemApi
3060 @Deprecated
3061 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3062 public void startTethering(int type, boolean showProvisioningUi,
3063 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003064 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003065
3066 final Executor executor = new Executor() {
3067 @Override
3068 public void execute(Runnable command) {
3069 if (handler == null) {
3070 command.run();
3071 } else {
3072 handler.post(command);
3073 }
3074 }
3075 };
3076
3077 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
3078 @Override
3079 public void onTetheringStarted() {
3080 callback.onTetheringStarted();
3081 }
3082
3083 @Override
3084 public void onTetheringFailed(final int error) {
3085 callback.onTetheringFailed();
3086 }
3087 };
3088
3089 final TetheringRequest request = new TetheringRequest.Builder(type)
3090 .setShouldShowEntitlementUi(showProvisioningUi).build();
3091
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003092 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003093 }
3094
3095 /**
3096 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
3097 * applicable.
3098 *
3099 * @param type The type of tethering to stop. Must be one of
3100 * {@link ConnectivityManager.TETHERING_WIFI},
3101 * {@link ConnectivityManager.TETHERING_USB}, or
3102 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3103 *
3104 * @deprecated Use {@link TetheringManager#stopTethering} instead.
3105 * @hide
3106 */
3107 @SystemApi
3108 @Deprecated
3109 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3110 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003111 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003112 }
3113
3114 /**
3115 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
3116 * upstream status.
3117 *
3118 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
3119 * @hide
3120 */
3121 @SystemApi
3122 @Deprecated
3123 public abstract static class OnTetheringEventCallback {
3124
3125 /**
3126 * Called when tethering upstream changed. This can be called multiple times and can be
3127 * called any time.
3128 *
3129 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
3130 * have any upstream.
3131 */
3132 public void onUpstreamChanged(@Nullable Network network) {}
3133 }
3134
3135 @GuardedBy("mTetheringEventCallbacks")
3136 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
3137 mTetheringEventCallbacks = new ArrayMap<>();
3138
3139 /**
3140 * Start listening to tethering change events. Any new added callback will receive the last
3141 * tethering status right away. If callback is registered when tethering has no upstream or
3142 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3143 * with a null argument. The same callback object cannot be registered twice.
3144 *
3145 * @param executor the executor on which callback will be invoked.
3146 * @param callback the callback to be called when tethering has change events.
3147 *
3148 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3149 * @hide
3150 */
3151 @SystemApi
3152 @Deprecated
3153 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3154 public void registerTetheringEventCallback(
3155 @NonNull @CallbackExecutor Executor executor,
3156 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003157 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003158
3159 final TetheringEventCallback tetherCallback =
3160 new TetheringEventCallback() {
3161 @Override
3162 public void onUpstreamChanged(@Nullable Network network) {
3163 callback.onUpstreamChanged(network);
3164 }
3165 };
3166
3167 synchronized (mTetheringEventCallbacks) {
3168 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003169 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003170 }
3171 }
3172
3173 /**
3174 * Remove tethering event callback previously registered with
3175 * {@link #registerTetheringEventCallback}.
3176 *
3177 * @param callback previously registered callback.
3178 *
3179 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3180 * @hide
3181 */
3182 @SystemApi
3183 @Deprecated
3184 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3185 public void unregisterTetheringEventCallback(
3186 @NonNull final OnTetheringEventCallback callback) {
3187 Objects.requireNonNull(callback, "The callback must be non-null");
3188 synchronized (mTetheringEventCallbacks) {
3189 final TetheringEventCallback tetherCallback =
3190 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003191 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003192 }
3193 }
3194
3195
3196 /**
3197 * Get the list of regular expressions that define any tetherable
3198 * USB network interfaces. If USB tethering is not supported by the
3199 * device, this list should be empty.
3200 *
3201 * @return an array of 0 or more regular expression Strings defining
3202 * what interfaces are considered tetherable usb interfaces.
3203 *
3204 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3205 * {@hide}
3206 */
3207 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3208 @UnsupportedAppUsage
3209 @Deprecated
3210 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003211 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003212 }
3213
3214 /**
3215 * Get the list of regular expressions that define any tetherable
3216 * Wifi network interfaces. If Wifi tethering is not supported by the
3217 * device, this list should be empty.
3218 *
3219 * @return an array of 0 or more regular expression Strings defining
3220 * what interfaces are considered tetherable wifi interfaces.
3221 *
3222 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3223 * {@hide}
3224 */
3225 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3226 @UnsupportedAppUsage
3227 @Deprecated
3228 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003229 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003230 }
3231
3232 /**
3233 * Get the list of regular expressions that define any tetherable
3234 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3235 * device, this list should be empty.
3236 *
3237 * @return an array of 0 or more regular expression Strings defining
3238 * what interfaces are considered tetherable bluetooth interfaces.
3239 *
3240 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3241 *TetheringManager.TetheringInterfaceRegexps)} instead.
3242 * {@hide}
3243 */
3244 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3245 @UnsupportedAppUsage
3246 @Deprecated
3247 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003248 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003249 }
3250
3251 /**
3252 * Attempt to both alter the mode of USB and Tethering of USB. A
3253 * utility method to deal with some of the complexity of USB - will
3254 * attempt to switch to Rndis and subsequently tether the resulting
3255 * interface on {@code true} or turn off tethering and switch off
3256 * Rndis on {@code false}.
3257 *
3258 * <p>This method requires the caller to hold either the
3259 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3260 * or the ability to modify system settings as determined by
3261 * {@link android.provider.Settings.System#canWrite}.</p>
3262 *
3263 * @param enable a boolean - {@code true} to enable tethering
3264 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3265 * @deprecated Use {@link TetheringManager#startTethering} instead
3266 *
3267 * {@hide}
3268 */
3269 @UnsupportedAppUsage
3270 @Deprecated
3271 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003272 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003273 }
3274
3275 /**
3276 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3277 * {@hide}
3278 */
3279 @SystemApi
3280 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003281 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003282 /**
3283 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3284 * {@hide}
3285 */
3286 @Deprecated
3287 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3288 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3289 /**
3290 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3291 * {@hide}
3292 */
3293 @Deprecated
3294 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3295 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3296 /**
3297 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3298 * {@hide}
3299 */
3300 @Deprecated
3301 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3302 /**
3303 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3304 * {@hide}
3305 */
3306 @Deprecated
3307 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3308 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3309 /**
3310 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3311 * {@hide}
3312 */
3313 @Deprecated
3314 public static final int TETHER_ERROR_MASTER_ERROR =
3315 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3316 /**
3317 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3318 * {@hide}
3319 */
3320 @Deprecated
3321 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3322 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3323 /**
3324 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3325 * {@hide}
3326 */
3327 @Deprecated
3328 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3329 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3330 /**
3331 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3332 * {@hide}
3333 */
3334 @Deprecated
3335 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3336 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3337 /**
3338 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3339 * {@hide}
3340 */
3341 @Deprecated
3342 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3343 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3344 /**
3345 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3346 * {@hide}
3347 */
3348 @Deprecated
3349 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3350 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3351 /**
3352 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3353 * {@hide}
3354 */
3355 @SystemApi
3356 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003357 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003358 /**
3359 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3360 * {@hide}
3361 */
3362 @Deprecated
3363 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3364 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3365 /**
3366 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3367 * {@hide}
3368 */
3369 @SystemApi
3370 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003371 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003372
3373 /**
3374 * Get a more detailed error code after a Tethering or Untethering
3375 * request asynchronously failed.
3376 *
3377 * @param iface The name of the interface of interest
3378 * @return error The error code of the last error tethering or untethering the named
3379 * interface
3380 *
3381 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3382 * {@hide}
3383 */
3384 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3385 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3386 @Deprecated
3387 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003388 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003389 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3390 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3391 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3392 // instead.
3393 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3394 }
3395 return error;
3396 }
3397
3398 /** @hide */
3399 @Retention(RetentionPolicy.SOURCE)
3400 @IntDef(value = {
3401 TETHER_ERROR_NO_ERROR,
3402 TETHER_ERROR_PROVISION_FAILED,
3403 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3404 })
3405 public @interface EntitlementResultCode {
3406 }
3407
3408 /**
3409 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3410 * entitlement succeeded.
3411 *
3412 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3413 * @hide
3414 */
3415 @SystemApi
3416 @Deprecated
3417 public interface OnTetheringEntitlementResultListener {
3418 /**
3419 * Called to notify entitlement result.
3420 *
3421 * @param resultCode an int value of entitlement result. It may be one of
3422 * {@link #TETHER_ERROR_NO_ERROR},
3423 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3424 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3425 */
3426 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3427 }
3428
3429 /**
3430 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003431 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3432 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003433 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003434 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003435 * any reason will update the cached value.
3436 *
3437 * @param type the downstream type of tethering. Must be one of
3438 * {@link #TETHERING_WIFI},
3439 * {@link #TETHERING_USB}, or
3440 * {@link #TETHERING_BLUETOOTH}.
3441 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3442 * @param executor the executor on which callback will be invoked.
3443 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3444 * notify the caller of the result of entitlement check. The listener may be called zero
3445 * or one time.
3446 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3447 * {@hide}
3448 */
3449 @SystemApi
3450 @Deprecated
3451 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3452 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3453 @NonNull @CallbackExecutor Executor executor,
3454 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003455 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003456 ResultReceiver wrappedListener = new ResultReceiver(null) {
3457 @Override
3458 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003459 final long token = Binder.clearCallingIdentity();
3460 try {
3461 executor.execute(() -> {
3462 listener.onTetheringEntitlementResult(resultCode);
3463 });
3464 } finally {
3465 Binder.restoreCallingIdentity(token);
3466 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003467 }
3468 };
3469
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003470 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003471 showEntitlementUi);
3472 }
3473
3474 /**
3475 * Report network connectivity status. This is currently used only
3476 * to alter status bar UI.
3477 * <p>This method requires the caller to hold the permission
3478 * {@link android.Manifest.permission#STATUS_BAR}.
3479 *
3480 * @param networkType The type of network you want to report on
3481 * @param percentage The quality of the connection 0 is bad, 100 is good
3482 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3483 * {@hide}
3484 */
3485 public void reportInetCondition(int networkType, int percentage) {
3486 printStackTrace();
3487 try {
3488 mService.reportInetCondition(networkType, percentage);
3489 } catch (RemoteException e) {
3490 throw e.rethrowFromSystemServer();
3491 }
3492 }
3493
3494 /**
3495 * Report a problem network to the framework. This provides a hint to the system
3496 * that there might be connectivity problems on this network and may cause
3497 * the framework to re-evaluate network connectivity and/or switch to another
3498 * network.
3499 *
3500 * @param network The {@link Network} the application was attempting to use
3501 * or {@code null} to indicate the current default network.
3502 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3503 * working and non-working connectivity.
3504 */
3505 @Deprecated
3506 public void reportBadNetwork(@Nullable Network network) {
3507 printStackTrace();
3508 try {
3509 // One of these will be ignored because it matches system's current state.
3510 // The other will trigger the necessary reevaluation.
3511 mService.reportNetworkConnectivity(network, true);
3512 mService.reportNetworkConnectivity(network, false);
3513 } catch (RemoteException e) {
3514 throw e.rethrowFromSystemServer();
3515 }
3516 }
3517
3518 /**
3519 * Report to the framework whether a network has working connectivity.
3520 * This provides a hint to the system that a particular network is providing
3521 * working connectivity or not. In response the framework may re-evaluate
3522 * the network's connectivity and might take further action thereafter.
3523 *
3524 * @param network The {@link Network} the application was attempting to use
3525 * or {@code null} to indicate the current default network.
3526 * @param hasConnectivity {@code true} if the application was able to successfully access the
3527 * Internet using {@code network} or {@code false} if not.
3528 */
3529 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3530 printStackTrace();
3531 try {
3532 mService.reportNetworkConnectivity(network, hasConnectivity);
3533 } catch (RemoteException e) {
3534 throw e.rethrowFromSystemServer();
3535 }
3536 }
3537
3538 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003539 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003540 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003541 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3542 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3543 * accessing any network, regardless of what the settings for that network are.
3544 *
3545 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3546 * proxy is likely to break networking on multiple networks. This method is only meant
3547 * for device policy clients looking to do general internal filtering or similar use cases.
3548 *
chiachangwang9473c592022-07-15 02:25:52 +00003549 * @see #getGlobalProxy
3550 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003551 *
3552 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3553 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003554 * @hide
3555 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003556 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003557 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003558 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003559 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003560 try {
3561 mService.setGlobalProxy(p);
3562 } catch (RemoteException e) {
3563 throw e.rethrowFromSystemServer();
3564 }
3565 }
3566
3567 /**
3568 * Retrieve any network-independent global HTTP proxy.
3569 *
3570 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3571 * if no global HTTP proxy is set.
3572 * @hide
3573 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003574 @SystemApi(client = MODULE_LIBRARIES)
3575 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003576 public ProxyInfo getGlobalProxy() {
3577 try {
3578 return mService.getGlobalProxy();
3579 } catch (RemoteException e) {
3580 throw e.rethrowFromSystemServer();
3581 }
3582 }
3583
3584 /**
3585 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3586 * network-specific HTTP proxy. If {@code network} is null, the
3587 * network-specific proxy returned is the proxy of the default active
3588 * network.
3589 *
3590 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3591 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3592 * or when {@code network} is {@code null},
3593 * the {@code ProxyInfo} for the default active network. Returns
3594 * {@code null} when no proxy applies or the caller doesn't have
3595 * permission to use {@code network}.
3596 * @hide
3597 */
3598 public ProxyInfo getProxyForNetwork(Network network) {
3599 try {
3600 return mService.getProxyForNetwork(network);
3601 } catch (RemoteException e) {
3602 throw e.rethrowFromSystemServer();
3603 }
3604 }
3605
3606 /**
3607 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3608 * otherwise if this process is bound to a {@link Network} using
3609 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3610 * the default network's proxy is returned.
3611 *
3612 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3613 * HTTP proxy is active.
3614 */
3615 @Nullable
3616 public ProxyInfo getDefaultProxy() {
3617 return getProxyForNetwork(getBoundNetworkForProcess());
3618 }
3619
3620 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003621 * Returns whether the hardware supports the given network type.
3622 *
3623 * This doesn't indicate there is coverage or such a network is available, just whether the
3624 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3625 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003626 *
3627 * @param networkType The network type we'd like to check
3628 * @return {@code true} if supported, else {@code false}
3629 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3630 * @hide
3631 */
3632 @Deprecated
3633 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3634 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3635 public boolean isNetworkSupported(int networkType) {
3636 try {
3637 return mService.isNetworkSupported(networkType);
3638 } catch (RemoteException e) {
3639 throw e.rethrowFromSystemServer();
3640 }
3641 }
3642
3643 /**
3644 * Returns if the currently active data network is metered. A network is
3645 * classified as metered when the user is sensitive to heavy data usage on
3646 * that connection due to monetary costs, data limitations or
3647 * battery/performance issues. You should check this before doing large
3648 * data transfers, and warn the user or delay the operation until another
3649 * network is available.
3650 *
3651 * @return {@code true} if large transfers should be avoided, otherwise
3652 * {@code false}.
3653 */
3654 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3655 public boolean isActiveNetworkMetered() {
3656 try {
3657 return mService.isActiveNetworkMetered();
3658 } catch (RemoteException e) {
3659 throw e.rethrowFromSystemServer();
3660 }
3661 }
3662
3663 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003664 * Set sign in error notification to visible or invisible
3665 *
3666 * @hide
3667 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3668 */
3669 @Deprecated
3670 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3671 String action) {
3672 try {
3673 mService.setProvisioningNotificationVisible(visible, networkType, action);
3674 } catch (RemoteException e) {
3675 throw e.rethrowFromSystemServer();
3676 }
3677 }
3678
3679 /**
3680 * Set the value for enabling/disabling airplane mode
3681 *
3682 * @param enable whether to enable airplane mode or not
3683 *
3684 * @hide
3685 */
3686 @RequiresPermission(anyOf = {
3687 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3688 android.Manifest.permission.NETWORK_SETTINGS,
3689 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3690 android.Manifest.permission.NETWORK_STACK})
3691 @SystemApi
3692 public void setAirplaneMode(boolean enable) {
3693 try {
3694 mService.setAirplaneMode(enable);
3695 } catch (RemoteException e) {
3696 throw e.rethrowFromSystemServer();
3697 }
3698 }
3699
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003700 /**
3701 * Registers the specified {@link NetworkProvider}.
3702 * Each listener must only be registered once. The listener can be unregistered with
3703 * {@link #unregisterNetworkProvider}.
3704 *
3705 * @param provider the provider to register
3706 * @return the ID of the provider. This ID must be used by the provider when registering
3707 * {@link android.net.NetworkAgent}s.
3708 * @hide
3709 */
3710 @SystemApi
3711 @RequiresPermission(anyOf = {
3712 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3713 android.Manifest.permission.NETWORK_FACTORY})
3714 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3715 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3716 throw new IllegalStateException("NetworkProviders can only be registered once");
3717 }
3718
3719 try {
3720 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3721 provider.getName());
3722 provider.setProviderId(providerId);
3723 } catch (RemoteException e) {
3724 throw e.rethrowFromSystemServer();
3725 }
3726 return provider.getProviderId();
3727 }
3728
3729 /**
3730 * Unregisters the specified NetworkProvider.
3731 *
3732 * @param provider the provider to unregister
3733 * @hide
3734 */
3735 @SystemApi
3736 @RequiresPermission(anyOf = {
3737 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3738 android.Manifest.permission.NETWORK_FACTORY})
3739 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3740 try {
3741 mService.unregisterNetworkProvider(provider.getMessenger());
3742 } catch (RemoteException e) {
3743 throw e.rethrowFromSystemServer();
3744 }
3745 provider.setProviderId(NetworkProvider.ID_NONE);
3746 }
3747
Chalard Jeand1b498b2021-01-05 08:40:09 +09003748 /**
3749 * Register or update a network offer with ConnectivityService.
3750 *
3751 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003752 * them to networking requests made by apps or the system. A callback identifies an offer
3753 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3754 * score and the capabilities of the network it might be able to bring up ; these act as
3755 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003756 * provider.
3757 *
3758 * The provider is under no obligation to be able to bring up the network it offers at any
3759 * given time. Instead, this mechanism is meant to limit requests received by providers
3760 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3761 * the quality of the network satisfying a given request to their own offer.
3762 *
3763 * An offer can be updated by calling this again with the same callback object. This is
3764 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3765 * provider with the changes caused by the changes in the offer.
3766 *
3767 * @param provider The provider making this offer.
3768 * @param score The prospective score of the network.
3769 * @param caps The prospective capabilities of the network.
3770 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003771 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003772 */
3773 @RequiresPermission(anyOf = {
3774 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3775 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003776 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003777 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3778 @NonNull final INetworkOfferCallback callback) {
3779 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003780 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003781 Objects.requireNonNull(score, "null score"),
3782 Objects.requireNonNull(caps, "null caps"),
3783 Objects.requireNonNull(callback, "null callback"));
3784 } catch (RemoteException e) {
3785 throw e.rethrowFromSystemServer();
3786 }
3787 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003788
Chalard Jeand1b498b2021-01-05 08:40:09 +09003789 /**
3790 * Withdraw a network offer made with {@link #offerNetwork}.
3791 *
3792 * @param callback The callback passed at registration time. This must be the same object
3793 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003794 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003795 */
3796 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3797 try {
3798 mService.unofferNetwork(Objects.requireNonNull(callback));
3799 } catch (RemoteException e) {
3800 throw e.rethrowFromSystemServer();
3801 }
3802 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003803 /** @hide exposed via the NetworkProvider class. */
3804 @RequiresPermission(anyOf = {
3805 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3806 android.Manifest.permission.NETWORK_FACTORY})
3807 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3808 try {
3809 mService.declareNetworkRequestUnfulfillable(request);
3810 } catch (RemoteException e) {
3811 throw e.rethrowFromSystemServer();
3812 }
3813 }
3814
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003815 /**
3816 * @hide
3817 * Register a NetworkAgent with ConnectivityService.
3818 * @return Network corresponding to NetworkAgent.
3819 */
3820 @RequiresPermission(anyOf = {
3821 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3822 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003823 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3824 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3825 @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId) {
3826 return registerNetworkAgent(na, ni, lp, nc, null /* localNetworkConfig */, score, config,
3827 providerId);
3828 }
3829
3830 /**
3831 * @hide
3832 * Register a NetworkAgent with ConnectivityService.
3833 * @return Network corresponding to NetworkAgent.
3834 */
3835 @RequiresPermission(anyOf = {
3836 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3837 android.Manifest.permission.NETWORK_FACTORY})
3838 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3839 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3840 @Nullable LocalNetworkConfig localNetworkConfig, @NonNull NetworkScore score,
3841 @NonNull NetworkAgentConfig config, int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003842 try {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003843 return mService.registerNetworkAgent(na, ni, lp, nc, score, localNetworkConfig, config,
3844 providerId);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003845 } catch (RemoteException e) {
3846 throw e.rethrowFromSystemServer();
3847 }
3848 }
3849
3850 /**
3851 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3852 * changes. Should be extended by applications wanting notifications.
3853 *
3854 * A {@code NetworkCallback} is registered by calling
3855 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3856 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3857 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3858 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3859 * A {@code NetworkCallback} should be registered at most once at any time.
3860 * A {@code NetworkCallback} that has been unregistered can be registered again.
3861 */
3862 public static class NetworkCallback {
3863 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003864 * No flags associated with this callback.
3865 * @hide
3866 */
3867 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003868
Roshan Piuse08bc182020-12-22 15:10:42 -08003869 /**
lucaslinc582d502022-01-27 09:07:00 +08003870 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3871 *
3872 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3873 * Prior to Android 12, this information is always returned to apps holding the appropriate
3874 * permission, possibly noting that the app has used location.
3875 * <p>In Android 12 and above, by default the sent objects do not contain any location
3876 * information, even if the app holds the necessary permissions, and the system does not
3877 * take note of location usage by the app. Apps can request that location information is
3878 * included, in which case the system will check location permission and the location
3879 * toggle state, and take note of location usage by the app if any such information is
3880 * returned.
3881 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003882 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3883 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3884 * <p>
3885 * These include:
3886 * <li> Some transport info instances (retrieved via
3887 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3888 * contain location sensitive information.
3889 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003890 * sensitive for wifi suggestor apps (i.e using
3891 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003892 * </p>
3893 * <p>
3894 * Note:
3895 * <li> Retrieving this location sensitive information (subject to app's location
3896 * permissions) will be noted by system. </li>
3897 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003898 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003899 */
Roshan Pius189d0092021-03-11 21:16:44 -08003900 // Note: Some existing fields which are location sensitive may still be included without
3901 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003902 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3903
3904 /** @hide */
3905 @Retention(RetentionPolicy.SOURCE)
3906 @IntDef(flag = true, prefix = "FLAG_", value = {
3907 FLAG_NONE,
3908 FLAG_INCLUDE_LOCATION_INFO
3909 })
3910 public @interface Flag { }
3911
3912 /**
3913 * All the valid flags for error checking.
3914 */
3915 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3916
3917 public NetworkCallback() {
3918 this(FLAG_NONE);
3919 }
3920
3921 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003922 if ((flags & VALID_FLAGS) != flags) {
3923 throw new IllegalArgumentException("Invalid flags");
3924 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003925 mFlags = flags;
3926 }
3927
3928 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003929 * Called when the framework connects to a new network to evaluate whether it satisfies this
3930 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3931 * callback. There is no guarantee that this new network will satisfy any requests, or that
3932 * the network will stay connected for longer than the time necessary to evaluate it.
3933 * <p>
3934 * Most applications <b>should not</b> act on this callback, and should instead use
3935 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3936 * the framework in properly evaluating the network &mdash; for example, an application that
3937 * can automatically log in to a captive portal without user intervention.
3938 *
3939 * @param network The {@link Network} of the network that is being evaluated.
3940 *
3941 * @hide
3942 */
3943 public void onPreCheck(@NonNull Network network) {}
3944
3945 /**
3946 * Called when the framework connects and has declared a new network ready for use.
3947 * This callback may be called more than once if the {@link Network} that is
3948 * satisfying the request changes.
3949 *
3950 * @param network The {@link Network} of the satisfying network.
3951 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3952 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3953 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3954 * @hide
3955 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003956 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003957 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003958 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003959 // Internally only this method is called when a new network is available, and
3960 // it calls the callback in the same way and order that older versions used
3961 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003962 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3963 onBlockedStatusChanged(network, blocked);
3964 }
3965
3966 /**
3967 * Legacy variant of onAvailable that takes a boolean blocked reason.
3968 *
3969 * This method has never been public API, but it's not final, so there may be apps that
3970 * implemented it and rely on it being called. Do our best not to break them.
3971 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3972 * this method is called. There does not seem to be a way to avoid this.
3973 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3974 *
3975 * @hide
3976 */
3977 public void onAvailable(@NonNull Network network,
3978 @NonNull NetworkCapabilities networkCapabilities,
3979 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003980 onAvailable(network);
3981 if (!networkCapabilities.hasCapability(
3982 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3983 onNetworkSuspended(network);
3984 }
3985 onCapabilitiesChanged(network, networkCapabilities);
3986 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003987 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003988 }
3989
3990 /**
3991 * Called when the framework connects and has declared a new network ready for use.
3992 *
3993 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3994 * be available at the same time, and onAvailable will be called for each of these as they
3995 * appear.
3996 *
3997 * <p>For callbacks registered with {@link #requestNetwork} and
3998 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3999 * is the new best network for this request and is now tracked by this callback ; this
4000 * callback will no longer receive method calls about other networks that may have been
4001 * passed to this method previously. The previously-best network may have disconnected, or
4002 * it may still be around and the newly-best network may simply be better.
4003 *
4004 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
4005 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
4006 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
4007 * to {@link #onBlockedStatusChanged(Network, boolean)}.
4008 *
4009 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4010 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4011 * this callback as this is prone to race conditions (there is no guarantee the objects
4012 * returned by these methods will be current). Instead, wait for a call to
4013 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
4014 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
4015 * to be well-ordered with respect to other callbacks.
4016 *
4017 * @param network The {@link Network} of the satisfying network.
4018 */
4019 public void onAvailable(@NonNull Network network) {}
4020
4021 /**
4022 * Called when the network is about to be lost, typically because there are no outstanding
4023 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
4024 * with the new replacement network for graceful handover. This method is not guaranteed
4025 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
4026 * network is suddenly disconnected.
4027 *
4028 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4029 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4030 * this callback as this is prone to race conditions ; calling these methods while in a
4031 * callback may return an outdated or even a null object.
4032 *
4033 * @param network The {@link Network} that is about to be lost.
4034 * @param maxMsToLive The time in milliseconds the system intends to keep the network
4035 * connected for graceful handover; note that the network may still
4036 * suffer a hard loss at any time.
4037 */
4038 public void onLosing(@NonNull Network network, int maxMsToLive) {}
4039
4040 /**
4041 * Called when a network disconnects or otherwise no longer satisfies this request or
4042 * callback.
4043 *
4044 * <p>If the callback was registered with requestNetwork() or
4045 * registerDefaultNetworkCallback(), it will only be invoked against the last network
4046 * returned by onAvailable() when that network is lost and no other network satisfies
4047 * the criteria of the request.
4048 *
4049 * <p>If the callback was registered with registerNetworkCallback() it will be called for
4050 * each network which no longer satisfies the criteria of the callback.
4051 *
4052 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4053 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4054 * this callback as this is prone to race conditions ; calling these methods while in a
4055 * callback may return an outdated or even a null object.
4056 *
4057 * @param network The {@link Network} lost.
4058 */
4059 public void onLost(@NonNull Network network) {}
4060
4061 /**
4062 * Called if no network is found within the timeout time specified in
4063 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
4064 * requested network request cannot be fulfilled (whether or not a timeout was
4065 * specified). When this callback is invoked the associated
4066 * {@link NetworkRequest} will have already been removed and released, as if
4067 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
4068 */
4069 public void onUnavailable() {}
4070
4071 /**
4072 * Called when the network corresponding to this request changes capabilities but still
4073 * satisfies the requested criteria.
4074 *
4075 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4076 * to be called immediately after {@link #onAvailable}.
4077 *
4078 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
4079 * ConnectivityManager methods in this callback as this is prone to race conditions :
4080 * calling these methods while in a callback may return an outdated or even a null object.
4081 *
4082 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08004083 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004084 * network.
4085 */
4086 public void onCapabilitiesChanged(@NonNull Network network,
4087 @NonNull NetworkCapabilities networkCapabilities) {}
4088
4089 /**
4090 * Called when the network corresponding to this request changes {@link LinkProperties}.
4091 *
4092 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4093 * to be called immediately after {@link #onAvailable}.
4094 *
4095 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
4096 * ConnectivityManager methods in this callback as this is prone to race conditions :
4097 * calling these methods while in a callback may return an outdated or even a null object.
4098 *
4099 * @param network The {@link Network} whose link properties have changed.
4100 * @param linkProperties The new {@link LinkProperties} for this network.
4101 */
4102 public void onLinkPropertiesChanged(@NonNull Network network,
4103 @NonNull LinkProperties linkProperties) {}
4104
4105 /**
4106 * Called when the network the framework connected to for this request suspends data
4107 * transmission temporarily.
4108 *
4109 * <p>This generally means that while the TCP connections are still live temporarily
4110 * network data fails to transfer. To give a specific example, this is used on cellular
4111 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4112 * means read operations on sockets on this network will block once the buffers are
4113 * drained, and write operations will block once the buffers are full.
4114 *
4115 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4116 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4117 * this callback as this is prone to race conditions (there is no guarantee the objects
4118 * returned by these methods will be current).
4119 *
4120 * @hide
4121 */
4122 public void onNetworkSuspended(@NonNull Network network) {}
4123
4124 /**
4125 * Called when the network the framework connected to for this request
4126 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4127 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4128
4129 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4130 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4131 * this callback as this is prone to race conditions : calling these methods while in a
4132 * callback may return an outdated or even a null object.
4133 *
4134 * @hide
4135 */
4136 public void onNetworkResumed(@NonNull Network network) {}
4137
4138 /**
4139 * Called when access to the specified network is blocked or unblocked.
4140 *
4141 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4142 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4143 * this callback as this is prone to race conditions : calling these methods while in a
4144 * callback may return an outdated or even a null object.
4145 *
4146 * @param network The {@link Network} whose blocked status has changed.
4147 * @param blocked The blocked status of this {@link Network}.
4148 */
4149 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4150
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004151 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004152 * Called when access to the specified network is blocked or unblocked, or the reason for
4153 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004154 *
4155 * If a NetworkCallback object implements this method,
4156 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4157 *
4158 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4159 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4160 * this callback as this is prone to race conditions : calling these methods while in a
4161 * callback may return an outdated or even a null object.
4162 *
4163 * @param network The {@link Network} whose blocked status has changed.
4164 * @param blocked The blocked status of this {@link Network}.
4165 * @hide
4166 */
4167 @SystemApi(client = MODULE_LIBRARIES)
4168 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4169 onBlockedStatusChanged(network, blocked != 0);
4170 }
4171
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004172 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004173 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004174 }
4175
4176 /**
4177 * Constant error codes used by ConnectivityService to communicate about failures and errors
4178 * across a Binder boundary.
4179 * @hide
4180 */
4181 public interface Errors {
4182 int TOO_MANY_REQUESTS = 1;
4183 }
4184
4185 /** @hide */
4186 public static class TooManyRequestsException extends RuntimeException {}
4187
4188 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4189 switch (e.errorCode) {
4190 case Errors.TOO_MANY_REQUESTS:
4191 return new TooManyRequestsException();
4192 default:
4193 Log.w(TAG, "Unknown service error code " + e.errorCode);
4194 return new RuntimeException(e);
4195 }
4196 }
4197
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004198 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004199 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004200 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004201 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004202 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004203 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004204 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004205 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004206 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004207 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004208 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004209 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004210 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004211 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004212 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004213 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004214 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004215 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004216 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004217 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004218 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004219 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004220
4221 /** @hide */
4222 public static String getCallbackName(int whichCallback) {
4223 switch (whichCallback) {
4224 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4225 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4226 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4227 case CALLBACK_LOST: return "CALLBACK_LOST";
4228 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4229 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4230 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4231 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4232 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4233 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4234 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4235 default:
4236 return Integer.toString(whichCallback);
4237 }
4238 }
4239
zhujiatai79b0de92022-09-22 15:44:02 +08004240 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004241 private static final String TAG = "ConnectivityManager.CallbackHandler";
4242 private static final boolean DBG = false;
4243
4244 CallbackHandler(Looper looper) {
4245 super(looper);
4246 }
4247
4248 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004249 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004250 }
4251
4252 @Override
4253 public void handleMessage(Message message) {
4254 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004255 // the sInstance can't be null because to send this message a ConnectivityManager
4256 // instance must have been created prior to creating the thread on which this
4257 // Handler is running.
4258 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004259 return;
4260 }
4261
4262 final NetworkRequest request = getObject(message, NetworkRequest.class);
4263 final Network network = getObject(message, Network.class);
4264 final NetworkCallback callback;
4265 synchronized (sCallbacks) {
4266 callback = sCallbacks.get(request);
4267 if (callback == null) {
4268 Log.w(TAG,
4269 "callback not found for " + getCallbackName(message.what) + " message");
4270 return;
4271 }
4272 if (message.what == CALLBACK_UNAVAIL) {
4273 sCallbacks.remove(request);
4274 callback.networkRequest = ALREADY_UNREGISTERED;
4275 }
4276 }
4277 if (DBG) {
4278 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4279 }
4280
4281 switch (message.what) {
4282 case CALLBACK_PRECHECK: {
4283 callback.onPreCheck(network);
4284 break;
4285 }
4286 case CALLBACK_AVAILABLE: {
4287 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4288 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004289 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004290 break;
4291 }
4292 case CALLBACK_LOSING: {
4293 callback.onLosing(network, message.arg1);
4294 break;
4295 }
4296 case CALLBACK_LOST: {
4297 callback.onLost(network);
4298 break;
4299 }
4300 case CALLBACK_UNAVAIL: {
4301 callback.onUnavailable();
4302 break;
4303 }
4304 case CALLBACK_CAP_CHANGED: {
4305 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4306 callback.onCapabilitiesChanged(network, cap);
4307 break;
4308 }
4309 case CALLBACK_IP_CHANGED: {
4310 LinkProperties lp = getObject(message, LinkProperties.class);
4311 callback.onLinkPropertiesChanged(network, lp);
4312 break;
4313 }
4314 case CALLBACK_SUSPENDED: {
4315 callback.onNetworkSuspended(network);
4316 break;
4317 }
4318 case CALLBACK_RESUMED: {
4319 callback.onNetworkResumed(network);
4320 break;
4321 }
4322 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004323 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004324 }
4325 }
4326 }
4327
4328 private <T> T getObject(Message msg, Class<T> c) {
4329 return (T) msg.getData().getParcelable(c.getSimpleName());
4330 }
4331 }
4332
4333 private CallbackHandler getDefaultHandler() {
4334 synchronized (sCallbacks) {
4335 if (sCallbackHandler == null) {
4336 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4337 }
4338 return sCallbackHandler;
4339 }
4340 }
4341
4342 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4343 private static CallbackHandler sCallbackHandler;
4344
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004345 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4346 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4347 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004348 printStackTrace();
4349 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004350 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4351 throw new IllegalArgumentException("null NetworkCapabilities");
4352 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004353 final NetworkRequest request;
4354 final String callingPackageName = mContext.getOpPackageName();
4355 try {
4356 synchronized(sCallbacks) {
4357 if (callback.networkRequest != null
4358 && callback.networkRequest != ALREADY_UNREGISTERED) {
4359 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4360 // and requests (http://b/20701525).
4361 Log.e(TAG, "NetworkCallback was already registered");
4362 }
4363 Messenger messenger = new Messenger(handler);
4364 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004365 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004366 if (reqType == LISTEN) {
4367 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004368 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004369 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004370 } else {
4371 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004372 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4373 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004374 }
4375 if (request != null) {
4376 sCallbacks.put(request, callback);
4377 }
4378 callback.networkRequest = request;
4379 }
4380 } catch (RemoteException e) {
4381 throw e.rethrowFromSystemServer();
4382 } catch (ServiceSpecificException e) {
4383 throw convertServiceException(e);
4384 }
4385 return request;
4386 }
4387
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004388 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4389 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4390 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4391 legacyType, handler);
4392 }
4393
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004394 /**
4395 * Helper function to request a network with a particular legacy type.
4396 *
4397 * This API is only for use in internal system code that requests networks with legacy type and
4398 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4399 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4400 *
4401 * @param request {@link NetworkRequest} describing this request.
4402 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4403 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4404 * be a positive value (i.e. >0).
4405 * @param legacyType to specify the network type(#TYPE_*).
4406 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4407 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4408 * the callback must not be shared - it uniquely specifies this request.
4409 *
4410 * @hide
4411 */
4412 @SystemApi
4413 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4414 public void requestNetwork(@NonNull NetworkRequest request,
4415 int timeoutMs, int legacyType, @NonNull Handler handler,
4416 @NonNull NetworkCallback networkCallback) {
4417 if (legacyType == TYPE_NONE) {
4418 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4419 }
4420 CallbackHandler cbHandler = new CallbackHandler(handler);
4421 NetworkCapabilities nc = request.networkCapabilities;
4422 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4423 }
4424
4425 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004426 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004427 *
4428 * <p>This method will attempt to find the best network that matches the passed
4429 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4430 * criteria. The platform will evaluate which network is the best at its own discretion.
4431 * Throughput, latency, cost per byte, policy, user preference and other considerations
4432 * may be factored in the decision of what is considered the best network.
4433 *
4434 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4435 * matching this request, while always attempting to match the request to a better network if
4436 * possible. If a better match is found, the platform will switch this request to the now-best
4437 * network and inform the app of the newly best network by invoking
4438 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4439 * will not try to maintain any other network than the best one currently matching the request:
4440 * a network not matching any network request may be disconnected at any time.
4441 *
4442 * <p>For example, an application could use this method to obtain a connected cellular network
4443 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4444 * radio to consume additional power. Or, an application could inform the system that it wants
4445 * a network supporting sending MMSes and have the system let it know about the currently best
4446 * MMS-supporting network through the provided {@link NetworkCallback}.
4447 *
4448 * <p>The status of the request can be followed by listening to the various callbacks described
4449 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4450 * used to direct traffic to the network (although accessing some networks may be subject to
4451 * holding specific permissions). Callers will learn about the specific characteristics of the
4452 * network through
4453 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4454 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4455 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4456 * matching the request at any given time; therefore when a better network matching the request
4457 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4458 * with the new network after which no further updates are given about the previously-best
4459 * network, unless it becomes the best again at some later time. All callbacks are invoked
4460 * in order on the same thread, which by default is a thread created by the framework running
4461 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004462 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004463 * callbacks are invoked.
4464 *
4465 * <p>This{@link NetworkRequest} will live until released via
4466 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4467 * which point the system may let go of the network at any time.
4468 *
4469 * <p>A version of this method which takes a timeout is
4470 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4471 * wait for a limited amount of time for the network to become unavailable.
4472 *
4473 * <p>It is presently unsupported to request a network with mutable
4474 * {@link NetworkCapabilities} such as
4475 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4476 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4477 * as these {@code NetworkCapabilities} represent states that a particular
4478 * network may never attain, and whether a network will attain these states
4479 * is unknown prior to bringing up the network so the framework does not
4480 * know how to go about satisfying a request with these capabilities.
4481 *
4482 * <p>This method requires the caller to hold either the
4483 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4484 * or the ability to modify system settings as determined by
4485 * {@link android.provider.Settings.System#canWrite}.</p>
4486 *
4487 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4488 * number of outstanding requests to 100 per app (identified by their UID), shared with
4489 * all variants of this method, of {@link #registerNetworkCallback} as well as
4490 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4491 * Requesting a network with this method will count toward this limit. If this limit is
4492 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4493 * make sure to unregister the callbacks with
4494 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4495 *
4496 * @param request {@link NetworkRequest} describing this request.
4497 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4498 * the callback must not be shared - it uniquely specifies this request.
4499 * The callback is invoked on the default internal Handler.
4500 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4501 * @throws SecurityException if missing the appropriate permissions.
4502 * @throws RuntimeException if the app already has too many callbacks registered.
4503 */
4504 public void requestNetwork(@NonNull NetworkRequest request,
4505 @NonNull NetworkCallback networkCallback) {
4506 requestNetwork(request, networkCallback, getDefaultHandler());
4507 }
4508
4509 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004510 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004511 *
4512 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4513 * but runs all the callbacks on the passed Handler.
4514 *
4515 * <p>This method has the same permission requirements as
4516 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4517 * and throws the same exceptions in the same conditions.
4518 *
4519 * @param request {@link NetworkRequest} describing this request.
4520 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4521 * the callback must not be shared - it uniquely specifies this request.
4522 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4523 */
4524 public void requestNetwork(@NonNull NetworkRequest request,
4525 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4526 CallbackHandler cbHandler = new CallbackHandler(handler);
4527 NetworkCapabilities nc = request.networkCapabilities;
4528 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4529 }
4530
4531 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004532 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004533 * by a timeout.
4534 *
4535 * This function behaves identically to the non-timed-out version
4536 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4537 * is not found within the given time (in milliseconds) the
4538 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4539 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4540 * not have to be released if timed-out (it is automatically released). Unregistering a
4541 * request that timed out is not an error.
4542 *
4543 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4544 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4545 * for that purpose. Calling this method will attempt to bring up the requested network.
4546 *
4547 * <p>This method has the same permission requirements as
4548 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4549 * and throws the same exceptions in the same conditions.
4550 *
4551 * @param request {@link NetworkRequest} describing this request.
4552 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4553 * the callback must not be shared - it uniquely specifies this request.
4554 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4555 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4556 * be a positive value (i.e. >0).
4557 */
4558 public void requestNetwork(@NonNull NetworkRequest request,
4559 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4560 checkTimeout(timeoutMs);
4561 NetworkCapabilities nc = request.networkCapabilities;
4562 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4563 getDefaultHandler());
4564 }
4565
4566 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004567 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004568 * by a timeout.
4569 *
4570 * This method behaves identically to
4571 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4572 * on the passed Handler.
4573 *
4574 * <p>This method has the same permission requirements as
4575 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4576 * and throws the same exceptions in the same conditions.
4577 *
4578 * @param request {@link NetworkRequest} describing this request.
4579 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4580 * the callback must not be shared - it uniquely specifies this request.
4581 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4582 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4583 * before {@link NetworkCallback#onUnavailable} is called.
4584 */
4585 public void requestNetwork(@NonNull NetworkRequest request,
4586 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4587 checkTimeout(timeoutMs);
4588 CallbackHandler cbHandler = new CallbackHandler(handler);
4589 NetworkCapabilities nc = request.networkCapabilities;
4590 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4591 }
4592
4593 /**
4594 * The lookup key for a {@link Network} object included with the intent after
4595 * successfully finding a network for the applications request. Retrieve it with
4596 * {@link android.content.Intent#getParcelableExtra(String)}.
4597 * <p>
4598 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4599 * then you must get a ConnectivityManager instance before doing so.
4600 */
4601 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4602
4603 /**
4604 * The lookup key for a {@link NetworkRequest} object included with the intent after
4605 * successfully finding a network for the applications request. Retrieve it with
4606 * {@link android.content.Intent#getParcelableExtra(String)}.
4607 */
4608 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4609
4610
4611 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004612 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004613 *
4614 * This function behaves identically to the version that takes a NetworkCallback, but instead
4615 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4616 * the request may outlive the calling application and get called back when a suitable
4617 * network is found.
4618 * <p>
4619 * The operation is an Intent broadcast that goes to a broadcast receiver that
4620 * you registered with {@link Context#registerReceiver} or through the
4621 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4622 * <p>
4623 * The operation Intent is delivered with two extras, a {@link Network} typed
4624 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4625 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4626 * the original requests parameters. It is important to create a new,
4627 * {@link NetworkCallback} based request before completing the processing of the
4628 * Intent to reserve the network or it will be released shortly after the Intent
4629 * is processed.
4630 * <p>
4631 * If there is already a request for this Intent registered (with the equality of
4632 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4633 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4634 * <p>
4635 * The request may be released normally by calling
4636 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4637 * <p>It is presently unsupported to request a network with either
4638 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4639 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4640 * as these {@code NetworkCapabilities} represent states that a particular
4641 * network may never attain, and whether a network will attain these states
4642 * is unknown prior to bringing up the network so the framework does not
4643 * know how to go about satisfying a request with these capabilities.
4644 *
4645 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4646 * number of outstanding requests to 100 per app (identified by their UID), shared with
4647 * all variants of this method, of {@link #registerNetworkCallback} as well as
4648 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4649 * Requesting a network with this method will count toward this limit. If this limit is
4650 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4651 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4652 * or {@link #releaseNetworkRequest(PendingIntent)}.
4653 *
4654 * <p>This method requires the caller to hold either the
4655 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4656 * or the ability to modify system settings as determined by
4657 * {@link android.provider.Settings.System#canWrite}.</p>
4658 *
4659 * @param request {@link NetworkRequest} describing this request.
4660 * @param operation Action to perform when the network is available (corresponds
4661 * to the {@link NetworkCallback#onAvailable} call. Typically
4662 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4663 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4664 * @throws SecurityException if missing the appropriate permissions.
4665 * @throws RuntimeException if the app already has too many callbacks registered.
4666 */
4667 public void requestNetwork(@NonNull NetworkRequest request,
4668 @NonNull PendingIntent operation) {
4669 printStackTrace();
4670 checkPendingIntentNotNull(operation);
4671 try {
4672 mService.pendingRequestForNetwork(
4673 request.networkCapabilities, operation, mContext.getOpPackageName(),
4674 getAttributionTag());
4675 } catch (RemoteException e) {
4676 throw e.rethrowFromSystemServer();
4677 } catch (ServiceSpecificException e) {
4678 throw convertServiceException(e);
4679 }
4680 }
4681
4682 /**
4683 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4684 * <p>
4685 * This method has the same behavior as
4686 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4687 * releasing network resources and disconnecting.
4688 *
4689 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4690 * PendingIntent passed to
4691 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4692 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4693 */
4694 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4695 printStackTrace();
4696 checkPendingIntentNotNull(operation);
4697 try {
4698 mService.releasePendingNetworkRequest(operation);
4699 } catch (RemoteException e) {
4700 throw e.rethrowFromSystemServer();
4701 }
4702 }
4703
4704 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004705 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004706 }
4707
4708 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004709 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004710 }
4711
4712 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004713 if (timeoutMs <= 0) {
4714 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4715 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004716 }
4717
4718 /**
4719 * Registers to receive notifications about all networks which satisfy the given
4720 * {@link NetworkRequest}. The callbacks will continue to be called until
4721 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4722 * called.
4723 *
4724 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4725 * number of outstanding requests to 100 per app (identified by their UID), shared with
4726 * all variants of this method, of {@link #requestNetwork} as well as
4727 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4728 * Requesting a network with this method will count toward this limit. If this limit is
4729 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4730 * make sure to unregister the callbacks with
4731 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4732 *
4733 * @param request {@link NetworkRequest} describing this request.
4734 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4735 * networks change state.
4736 * The callback is invoked on the default internal Handler.
4737 * @throws RuntimeException if the app already has too many callbacks registered.
4738 */
4739 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4740 public void registerNetworkCallback(@NonNull NetworkRequest request,
4741 @NonNull NetworkCallback networkCallback) {
4742 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4743 }
4744
4745 /**
4746 * Registers to receive notifications about all networks which satisfy the given
4747 * {@link NetworkRequest}. The callbacks will continue to be called until
4748 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4749 * called.
4750 *
4751 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4752 * number of outstanding requests to 100 per app (identified by their UID), shared with
4753 * all variants of this method, of {@link #requestNetwork} as well as
4754 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4755 * Requesting a network with this method will count toward this limit. If this limit is
4756 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4757 * make sure to unregister the callbacks with
4758 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4759 *
4760 *
4761 * @param request {@link NetworkRequest} describing this request.
4762 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4763 * networks change state.
4764 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4765 * @throws RuntimeException if the app already has too many callbacks registered.
4766 */
4767 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4768 public void registerNetworkCallback(@NonNull NetworkRequest request,
4769 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4770 CallbackHandler cbHandler = new CallbackHandler(handler);
4771 NetworkCapabilities nc = request.networkCapabilities;
4772 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4773 }
4774
4775 /**
4776 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4777 * {@link NetworkRequest}.
4778 *
4779 * This function behaves identically to the version that takes a NetworkCallback, but instead
4780 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4781 * the request may outlive the calling application and get called back when a suitable
4782 * network is found.
4783 * <p>
4784 * The operation is an Intent broadcast that goes to a broadcast receiver that
4785 * you registered with {@link Context#registerReceiver} or through the
4786 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4787 * <p>
4788 * The operation Intent is delivered with two extras, a {@link Network} typed
4789 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4790 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4791 * the original requests parameters.
4792 * <p>
4793 * If there is already a request for this Intent registered (with the equality of
4794 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4795 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4796 * <p>
4797 * The request may be released normally by calling
4798 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4799 *
4800 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4801 * number of outstanding requests to 100 per app (identified by their UID), shared with
4802 * all variants of this method, of {@link #requestNetwork} as well as
4803 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4804 * Requesting a network with this method will count toward this limit. If this limit is
4805 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4806 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4807 * or {@link #releaseNetworkRequest(PendingIntent)}.
4808 *
4809 * @param request {@link NetworkRequest} describing this request.
4810 * @param operation Action to perform when the network is available (corresponds
4811 * to the {@link NetworkCallback#onAvailable} call. Typically
4812 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4813 * @throws RuntimeException if the app already has too many callbacks registered.
4814 */
4815 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4816 public void registerNetworkCallback(@NonNull NetworkRequest request,
4817 @NonNull PendingIntent operation) {
4818 printStackTrace();
4819 checkPendingIntentNotNull(operation);
4820 try {
4821 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004822 request.networkCapabilities, operation, mContext.getOpPackageName(),
4823 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004824 } catch (RemoteException e) {
4825 throw e.rethrowFromSystemServer();
4826 } catch (ServiceSpecificException e) {
4827 throw convertServiceException(e);
4828 }
4829 }
4830
4831 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004832 * Registers to receive notifications about changes in the application's default network. This
4833 * may be a physical network or a virtual network, such as a VPN that applies to the
4834 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004835 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4836 *
4837 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4838 * number of outstanding requests to 100 per app (identified by their UID), shared with
4839 * all variants of this method, of {@link #requestNetwork} as well as
4840 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4841 * Requesting a network with this method will count toward this limit. If this limit is
4842 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4843 * make sure to unregister the callbacks with
4844 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4845 *
4846 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004847 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004848 * The callback is invoked on the default internal Handler.
4849 * @throws RuntimeException if the app already has too many callbacks registered.
4850 */
4851 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4852 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4853 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4854 }
4855
4856 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004857 * Registers to receive notifications about changes in the application's default network. This
4858 * may be a physical network or a virtual network, such as a VPN that applies to the
4859 * application. The callbacks will continue to be called until either the application exits or
4860 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4861 *
4862 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4863 * number of outstanding requests to 100 per app (identified by their UID), shared with
4864 * all variants of this method, of {@link #requestNetwork} as well as
4865 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4866 * Requesting a network with this method will count toward this limit. If this limit is
4867 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4868 * make sure to unregister the callbacks with
4869 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4870 *
4871 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4872 * application's default network changes.
4873 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4874 * @throws RuntimeException if the app already has too many callbacks registered.
4875 */
4876 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4877 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4878 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004879 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004880 }
4881
4882 /**
4883 * Registers to receive notifications about changes in the default network for the specified
4884 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4885 * UID. The callbacks will continue to be called until either the application exits or
4886 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4887 *
4888 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4889 * number of outstanding requests to 100 per app (identified by their UID), shared with
4890 * all variants of this method, of {@link #requestNetwork} as well as
4891 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4892 * Requesting a network with this method will count toward this limit. If this limit is
4893 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4894 * make sure to unregister the callbacks with
4895 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4896 *
4897 * @param uid the UID for which to track default network changes.
4898 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4899 * UID's default network changes.
4900 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4901 * @throws RuntimeException if the app already has too many callbacks registered.
4902 * @hide
4903 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004904 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004905 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4906 @RequiresPermission(anyOf = {
4907 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4908 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004909 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004910 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004911 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004912 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004913 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4914 }
4915
4916 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004917 * Registers to receive notifications about changes in the system default network. The callbacks
4918 * will continue to be called until either the application exits or
4919 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4920 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004921 * This method should not be used to determine networking state seen by applications, because in
4922 * many cases, most or even all application traffic may not use the default network directly,
4923 * and traffic from different applications may go on different networks by default. As an
4924 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4925 * and not onto the system default network. Applications or system components desiring to do
4926 * determine network state as seen by applications should use other methods such as
4927 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4928 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004929 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4930 * number of outstanding requests to 100 per app (identified by their UID), shared with
4931 * all variants of this method, of {@link #requestNetwork} as well as
4932 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4933 * Requesting a network with this method will count toward this limit. If this limit is
4934 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4935 * make sure to unregister the callbacks with
4936 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4937 *
4938 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4939 * system default network changes.
4940 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4941 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004942 *
4943 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004944 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004945 @SystemApi(client = MODULE_LIBRARIES)
4946 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4947 @RequiresPermission(anyOf = {
4948 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004949 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00004950 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004951 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004952 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004953 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004954 CallbackHandler cbHandler = new CallbackHandler(handler);
4955 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004956 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004957 }
4958
4959 /**
junyulaibd123062021-03-15 11:48:48 +08004960 * Registers to receive notifications about the best matching network which satisfy the given
4961 * {@link NetworkRequest}. The callbacks will continue to be called until
4962 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4963 * called.
4964 *
4965 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4966 * number of outstanding requests to 100 per app (identified by their UID), shared with
4967 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4968 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4969 * Requesting a network with this method will count toward this limit. If this limit is
4970 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4971 * make sure to unregister the callbacks with
4972 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4973 *
4974 *
4975 * @param request {@link NetworkRequest} describing this request.
4976 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4977 * networks change state.
4978 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4979 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004980 */
junyulai5a5c99b2021-03-05 15:51:17 +08004981 @SuppressLint("ExecutorRegistration")
4982 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4983 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4984 final NetworkCapabilities nc = request.networkCapabilities;
4985 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004986 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004987 }
4988
4989 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004990 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4991 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4992 * network connection for updated bandwidth information. The caller will be notified via
4993 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4994 * method assumes that the caller has previously called
4995 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4996 * changes.
4997 *
4998 * @param network {@link Network} specifying which network you're interested.
4999 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5000 */
5001 public boolean requestBandwidthUpdate(@NonNull Network network) {
5002 try {
5003 return mService.requestBandwidthUpdate(network);
5004 } catch (RemoteException e) {
5005 throw e.rethrowFromSystemServer();
5006 }
5007 }
5008
5009 /**
5010 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
5011 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
5012 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005013 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
5014 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005015 *
5016 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
5017 * triggering it as soon as this call returns.
5018 *
5019 * @param networkCallback The {@link NetworkCallback} used when making the request.
5020 */
5021 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
5022 printStackTrace();
5023 checkCallbackNotNull(networkCallback);
5024 final List<NetworkRequest> reqs = new ArrayList<>();
5025 // Find all requests associated to this callback and stop callback triggers immediately.
5026 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
5027 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00005028 if (networkCallback.networkRequest == null) {
5029 throw new IllegalArgumentException("NetworkCallback was not registered");
5030 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005031 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
5032 Log.d(TAG, "NetworkCallback was already unregistered");
5033 return;
5034 }
5035 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
5036 if (e.getValue() == networkCallback) {
5037 reqs.add(e.getKey());
5038 }
5039 }
5040 // TODO: throw exception if callback was registered more than once (http://b/20701525).
5041 for (NetworkRequest r : reqs) {
5042 try {
5043 mService.releaseNetworkRequest(r);
5044 } catch (RemoteException e) {
5045 throw e.rethrowFromSystemServer();
5046 }
5047 // Only remove mapping if rpc was successful.
5048 sCallbacks.remove(r);
5049 }
5050 networkCallback.networkRequest = ALREADY_UNREGISTERED;
5051 }
5052 }
5053
5054 /**
5055 * Unregisters a callback previously registered via
5056 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5057 *
5058 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
5059 * PendingIntent passed to
5060 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5061 * Cannot be null.
5062 */
5063 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
5064 releaseNetworkRequest(operation);
5065 }
5066
5067 /**
5068 * Informs the system whether it should switch to {@code network} regardless of whether it is
5069 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
5070 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
5071 * the system default network regardless of any other network that's currently connected. If
5072 * {@code always} is true, then the choice is remembered, so that the next time the user
5073 * connects to this network, the system will switch to it.
5074 *
5075 * @param network The network to accept.
5076 * @param accept Whether to accept the network even if unvalidated.
5077 * @param always Whether to remember this choice in the future.
5078 *
5079 * @hide
5080 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005081 @SystemApi(client = MODULE_LIBRARIES)
5082 @RequiresPermission(anyOf = {
5083 android.Manifest.permission.NETWORK_SETTINGS,
5084 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5085 android.Manifest.permission.NETWORK_STACK,
5086 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5087 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005088 try {
5089 mService.setAcceptUnvalidated(network, accept, always);
5090 } catch (RemoteException e) {
5091 throw e.rethrowFromSystemServer();
5092 }
5093 }
5094
5095 /**
5096 * Informs the system whether it should consider the network as validated even if it only has
5097 * partial connectivity. If {@code accept} is true, then the network will be considered as
5098 * validated even if connectivity is only partial. If {@code always} is true, then the choice
5099 * is remembered, so that the next time the user connects to this network, the system will
5100 * switch to it.
5101 *
5102 * @param network The network to accept.
5103 * @param accept Whether to consider the network as validated even if it has partial
5104 * connectivity.
5105 * @param always Whether to remember this choice in the future.
5106 *
5107 * @hide
5108 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005109 @SystemApi(client = MODULE_LIBRARIES)
5110 @RequiresPermission(anyOf = {
5111 android.Manifest.permission.NETWORK_SETTINGS,
5112 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5113 android.Manifest.permission.NETWORK_STACK,
5114 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5115 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5116 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005117 try {
5118 mService.setAcceptPartialConnectivity(network, accept, always);
5119 } catch (RemoteException e) {
5120 throw e.rethrowFromSystemServer();
5121 }
5122 }
5123
5124 /**
5125 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5126 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5127 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5128 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5129 *
5130 * @param network The network to accept.
5131 *
5132 * @hide
5133 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005134 @SystemApi(client = MODULE_LIBRARIES)
5135 @RequiresPermission(anyOf = {
5136 android.Manifest.permission.NETWORK_SETTINGS,
5137 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5138 android.Manifest.permission.NETWORK_STACK,
5139 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5140 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005141 try {
5142 mService.setAvoidUnvalidated(network);
5143 } catch (RemoteException e) {
5144 throw e.rethrowFromSystemServer();
5145 }
5146 }
5147
5148 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005149 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005150 *
5151 * @param timeMs The expired current time. The value should be set within a limited time from
5152 * now.
5153 *
5154 * @hide
5155 */
5156 public void setTestAllowBadWifiUntil(long timeMs) {
5157 try {
5158 mService.setTestAllowBadWifiUntil(timeMs);
5159 } catch (RemoteException e) {
5160 throw e.rethrowFromSystemServer();
5161 }
5162 }
5163
5164 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005165 * Requests that the system open the captive portal app on the specified network.
5166 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005167 * <p>This is to be used on networks where a captive portal was detected, as per
5168 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5169 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005170 * @param network The network to log into.
5171 *
5172 * @hide
5173 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005174 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5175 @RequiresPermission(anyOf = {
5176 android.Manifest.permission.NETWORK_SETTINGS,
5177 android.Manifest.permission.NETWORK_STACK,
5178 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5179 })
5180 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005181 try {
5182 mService.startCaptivePortalApp(network);
5183 } catch (RemoteException e) {
5184 throw e.rethrowFromSystemServer();
5185 }
5186 }
5187
5188 /**
5189 * Requests that the system open the captive portal app with the specified extras.
5190 *
5191 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5192 * corresponding permission.
5193 * @param network Network on which the captive portal was detected.
5194 * @param appExtras Extras to include in the app start intent.
5195 * @hide
5196 */
5197 @SystemApi
5198 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5199 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5200 try {
5201 mService.startCaptivePortalAppInternal(network, appExtras);
5202 } catch (RemoteException e) {
5203 throw e.rethrowFromSystemServer();
5204 }
5205 }
5206
5207 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005208 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005209 * @hide
5210 */
5211 @SystemApi
5212 @RequiresPermission(anyOf = {
5213 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5214 android.Manifest.permission.NETWORK_STACK})
5215 public boolean shouldAvoidBadWifi() {
5216 try {
5217 return mService.shouldAvoidBadWifi();
5218 } catch (RemoteException e) {
5219 throw e.rethrowFromSystemServer();
5220 }
5221 }
5222
5223 /**
5224 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5225 * time-sensitive user-facing operations when the system default network is temporarily
5226 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5227 * this method), and the operation should be infrequent to ensure that data usage is limited.
5228 *
5229 * An example of such an operation might be a time-sensitive foreground activity, such as a
5230 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5231 */
5232 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5233
5234 /**
5235 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5236 * a backup channel for traffic that is primarily going over another network.
5237 *
5238 * An example might be maintaining backup connections to peers or servers for the purpose of
5239 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5240 * on backup paths should be negligible compared to the traffic on the main path.
5241 */
5242 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5243
5244 /**
5245 * It is acceptable to use metered data to improve network latency and performance.
5246 */
5247 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5248
5249 /**
5250 * Return value to use for unmetered networks. On such networks we currently set all the flags
5251 * to true.
5252 * @hide
5253 */
5254 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5255 MULTIPATH_PREFERENCE_HANDOVER |
5256 MULTIPATH_PREFERENCE_RELIABILITY |
5257 MULTIPATH_PREFERENCE_PERFORMANCE;
5258
Aaron Huangcff22942021-05-27 16:31:26 +08005259 /** @hide */
5260 @Retention(RetentionPolicy.SOURCE)
5261 @IntDef(flag = true, value = {
5262 MULTIPATH_PREFERENCE_HANDOVER,
5263 MULTIPATH_PREFERENCE_RELIABILITY,
5264 MULTIPATH_PREFERENCE_PERFORMANCE,
5265 })
5266 public @interface MultipathPreference {
5267 }
5268
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005269 /**
5270 * Provides a hint to the calling application on whether it is desirable to use the
5271 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5272 * for multipath data transfer on this network when it is not the system default network.
5273 * Applications desiring to use multipath network protocols should call this method before
5274 * each such operation.
5275 *
5276 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005277 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005278 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005279 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005280 */
5281 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5282 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5283 try {
5284 return mService.getMultipathPreference(network);
5285 } catch (RemoteException e) {
5286 throw e.rethrowFromSystemServer();
5287 }
5288 }
5289
5290 /**
5291 * Resets all connectivity manager settings back to factory defaults.
5292 * @hide
5293 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005294 @SystemApi(client = MODULE_LIBRARIES)
5295 @RequiresPermission(anyOf = {
5296 android.Manifest.permission.NETWORK_SETTINGS,
5297 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005298 public void factoryReset() {
5299 try {
5300 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005301 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005302 } catch (RemoteException e) {
5303 throw e.rethrowFromSystemServer();
5304 }
5305 }
5306
5307 /**
5308 * Binds the current process to {@code network}. All Sockets created in the future
5309 * (and not explicitly bound via a bound SocketFactory from
5310 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5311 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5312 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5313 * work and all host name resolutions will fail. This is by design so an application doesn't
5314 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5315 * To clear binding pass {@code null} for {@code network}. Using individually bound
5316 * Sockets created by Network.getSocketFactory().createSocket() and
5317 * performing network-specific host name resolutions via
5318 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5319 * {@code bindProcessToNetwork}.
5320 *
5321 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5322 * the current binding.
5323 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5324 */
5325 public boolean bindProcessToNetwork(@Nullable Network network) {
5326 // Forcing callers to call through non-static function ensures ConnectivityManager
5327 // instantiated.
5328 return setProcessDefaultNetwork(network);
5329 }
5330
5331 /**
5332 * Binds the current process to {@code network}. All Sockets created in the future
5333 * (and not explicitly bound via a bound SocketFactory from
5334 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5335 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5336 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5337 * work and all host name resolutions will fail. This is by design so an application doesn't
5338 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5339 * To clear binding pass {@code null} for {@code network}. Using individually bound
5340 * Sockets created by Network.getSocketFactory().createSocket() and
5341 * performing network-specific host name resolutions via
5342 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5343 * {@code setProcessDefaultNetwork}.
5344 *
5345 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5346 * the current binding.
5347 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5348 * @deprecated This function can throw {@link IllegalStateException}. Use
5349 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5350 * is a direct replacement.
5351 */
5352 @Deprecated
5353 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5354 int netId = (network == null) ? NETID_UNSET : network.netId;
5355 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5356
5357 if (netId != NETID_UNSET) {
5358 netId = network.getNetIdForResolv();
5359 }
5360
5361 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5362 return false;
5363 }
5364
5365 if (!isSameNetId) {
5366 // Set HTTP proxy system properties to match network.
5367 // TODO: Deprecate this static method and replace it with a non-static version.
5368 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005369 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005370 } catch (SecurityException e) {
5371 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5372 Log.e(TAG, "Can't set proxy properties", e);
5373 }
5374 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005375 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005376 // Must flush socket pool as idle sockets will be bound to previous network and may
5377 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005378 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005379 }
5380
5381 return true;
5382 }
5383
5384 /**
5385 * Returns the {@link Network} currently bound to this process via
5386 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5387 *
5388 * @return {@code Network} to which this process is bound, or {@code null}.
5389 */
5390 @Nullable
5391 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005392 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005393 // instantiated.
5394 return getProcessDefaultNetwork();
5395 }
5396
5397 /**
5398 * Returns the {@link Network} currently bound to this process via
5399 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5400 *
5401 * @return {@code Network} to which this process is bound, or {@code null}.
5402 * @deprecated Using this function can lead to other functions throwing
5403 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5404 * {@code getBoundNetworkForProcess} is a direct replacement.
5405 */
5406 @Deprecated
5407 @Nullable
5408 public static Network getProcessDefaultNetwork() {
5409 int netId = NetworkUtils.getBoundNetworkForProcess();
5410 if (netId == NETID_UNSET) return null;
5411 return new Network(netId);
5412 }
5413
5414 private void unsupportedStartingFrom(int version) {
5415 if (Process.myUid() == Process.SYSTEM_UID) {
5416 // The getApplicationInfo() call we make below is not supported in system context. Let
5417 // the call through here, and rely on the fact that ConnectivityService will refuse to
5418 // allow the system to use these APIs anyway.
5419 return;
5420 }
5421
5422 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5423 throw new UnsupportedOperationException(
5424 "This method is not supported in target SDK version " + version + " and above");
5425 }
5426 }
5427
5428 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5429 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5430 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5431 // remove these exemptions. Note that this check is not secure, and apps can still access these
5432 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5433 // so is unsupported and may break in the future. http://b/22728205
5434 private void checkLegacyRoutingApiAccess() {
5435 unsupportedStartingFrom(VERSION_CODES.M);
5436 }
5437
5438 /**
5439 * Binds host resolutions performed by this process to {@code network}.
5440 * {@link #bindProcessToNetwork} takes precedence over this setting.
5441 *
5442 * @param network The {@link Network} to bind host resolutions from the current process to, or
5443 * {@code null} to clear the current binding.
5444 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5445 * @hide
5446 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5447 */
5448 @Deprecated
5449 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5450 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5451 return NetworkUtils.bindProcessToNetworkForHostResolution(
5452 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5453 }
5454
5455 /**
5456 * Device is not restricting metered network activity while application is running on
5457 * background.
5458 */
5459 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5460
5461 /**
5462 * Device is restricting metered network activity while application is running on background,
5463 * but application is allowed to bypass it.
5464 * <p>
5465 * In this state, application should take action to mitigate metered network access.
5466 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5467 */
5468 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5469
5470 /**
5471 * Device is restricting metered network activity while application is running on background.
5472 * <p>
5473 * In this state, application should not try to use the network while running on background,
5474 * because it would be denied.
5475 */
5476 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5477
5478 /**
5479 * A change in the background metered network activity restriction has occurred.
5480 * <p>
5481 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5482 * applies to them.
5483 * <p>
5484 * This is only sent to registered receivers, not manifest receivers.
5485 */
5486 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5487 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5488 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5489
Aaron Huangcff22942021-05-27 16:31:26 +08005490 /** @hide */
5491 @Retention(RetentionPolicy.SOURCE)
5492 @IntDef(flag = false, value = {
5493 RESTRICT_BACKGROUND_STATUS_DISABLED,
5494 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5495 RESTRICT_BACKGROUND_STATUS_ENABLED,
5496 })
5497 public @interface RestrictBackgroundStatus {
5498 }
5499
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005500 /**
5501 * Determines if the calling application is subject to metered network restrictions while
5502 * running on background.
5503 *
5504 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5505 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5506 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5507 */
5508 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5509 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005510 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005511 } catch (RemoteException e) {
5512 throw e.rethrowFromSystemServer();
5513 }
5514 }
5515
5516 /**
5517 * The network watchlist is a list of domains and IP addresses that are associated with
5518 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5519 * currently used by the system for validation purposes.
5520 *
5521 * @return Hash of network watchlist config file. Null if config does not exist.
5522 */
5523 @Nullable
5524 public byte[] getNetworkWatchlistConfigHash() {
5525 try {
5526 return mService.getNetworkWatchlistConfigHash();
5527 } catch (RemoteException e) {
5528 Log.e(TAG, "Unable to get watchlist config hash");
5529 throw e.rethrowFromSystemServer();
5530 }
5531 }
5532
5533 /**
5534 * Returns the {@code uid} of the owner of a network connection.
5535 *
5536 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5537 * IPPROTO_UDP} currently supported.
5538 * @param local The local {@link InetSocketAddress} of a connection.
5539 * @param remote The remote {@link InetSocketAddress} of a connection.
5540 * @return {@code uid} if the connection is found and the app has permission to observe it
5541 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5542 * android.os.Process#INVALID_UID} if the connection is not found.
Sherri Lin443b7182023-02-08 04:49:29 +01005543 * @throws SecurityException if the caller is not the active VpnService for the current
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005544 * user.
Sherri Lin443b7182023-02-08 04:49:29 +01005545 * @throws IllegalArgumentException if an unsupported protocol is requested.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005546 */
5547 public int getConnectionOwnerUid(
5548 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5549 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5550 try {
5551 return mService.getConnectionOwnerUid(connectionInfo);
5552 } catch (RemoteException e) {
5553 throw e.rethrowFromSystemServer();
5554 }
5555 }
5556
5557 private void printStackTrace() {
5558 if (DEBUG) {
5559 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5560 final StringBuffer sb = new StringBuffer();
5561 for (int i = 3; i < callStack.length; i++) {
5562 final String stackTrace = callStack[i].toString();
5563 if (stackTrace == null || stackTrace.contains("android.os")) {
5564 break;
5565 }
5566 sb.append(" [").append(stackTrace).append("]");
5567 }
5568 Log.d(TAG, "StackLog:" + sb.toString());
5569 }
5570 }
5571
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005572 /** @hide */
5573 public TestNetworkManager startOrGetTestNetworkManager() {
5574 final IBinder tnBinder;
5575 try {
5576 tnBinder = mService.startOrGetTestNetworkService();
5577 } catch (RemoteException e) {
5578 throw e.rethrowFromSystemServer();
5579 }
5580
5581 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5582 }
5583
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005584 /** @hide */
5585 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5586 return new ConnectivityDiagnosticsManager(mContext, mService);
5587 }
5588
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005589 /**
5590 * Simulates a Data Stall for the specified Network.
5591 *
5592 * <p>This method should only be used for tests.
5593 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005594 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5595 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005596 *
5597 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005598 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5599 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5600 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005601 * @param network The Network for which a Data Stall is being simluated.
5602 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5603 * @throws SecurityException if the caller is not the owner of the given network.
5604 * @hide
5605 */
5606 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5607 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5608 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005609 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005610 @NonNull Network network, @NonNull PersistableBundle extras) {
5611 try {
5612 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5613 } catch (RemoteException e) {
5614 e.rethrowFromSystemServer();
5615 }
5616 }
5617
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005618 @NonNull
5619 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5620
5621 /**
5622 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5623 * receive available QoS events related to the {@link Network} and local ip + port
5624 * specified within socketInfo.
5625 * <p/>
5626 * The same {@link QosCallback} must be unregistered before being registered a second time,
5627 * otherwise {@link QosCallbackRegistrationException} is thrown.
5628 * <p/>
5629 * This API does not, in itself, require any permission if called with a network that is not
5630 * restricted. However, the underlying implementation currently only supports the IMS network,
5631 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5632 * useful, because they'd never be called back on networks that they would have access to.
5633 *
5634 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5635 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5636 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5637 * @throws RuntimeException if the app already has too many callbacks registered.
5638 *
5639 * Exceptions after the time of registration is passed through
5640 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5641 *
5642 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005643 * @param executor The executor on which the callback will be invoked. The provided
5644 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005645 * callbacks cannot be guaranteed.onQosCallbackRegistered
5646 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005647 *
5648 * @hide
5649 */
5650 @SystemApi
5651 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005652 @CallbackExecutor @NonNull final Executor executor,
5653 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005654 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005655 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005656 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005657
5658 try {
5659 synchronized (mQosCallbackConnections) {
5660 if (getQosCallbackConnection(callback) == null) {
5661 final QosCallbackConnection connection =
5662 new QosCallbackConnection(this, callback, executor);
5663 mQosCallbackConnections.add(connection);
5664 mService.registerQosSocketCallback(socketInfo, connection);
5665 } else {
5666 Log.e(TAG, "registerQosCallback: Callback already registered");
5667 throw new QosCallbackRegistrationException();
5668 }
5669 }
5670 } catch (final RemoteException e) {
5671 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5672
5673 // The same unregister method method is called for consistency even though nothing
5674 // will be sent to the ConnectivityService since the callback was never successfully
5675 // registered.
5676 unregisterQosCallback(callback);
5677 e.rethrowFromSystemServer();
5678 } catch (final ServiceSpecificException e) {
5679 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5680 unregisterQosCallback(callback);
5681 throw convertServiceException(e);
5682 }
5683 }
5684
5685 /**
5686 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5687 * events once unregistered and can be registered a second time.
5688 * <p/>
5689 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5690 *
5691 * @param callback the callback being unregistered
5692 *
5693 * @hide
5694 */
5695 @SystemApi
5696 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5697 Objects.requireNonNull(callback, "The callback must be non-null");
5698 try {
5699 synchronized (mQosCallbackConnections) {
5700 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5701 if (connection != null) {
5702 connection.stopReceivingMessages();
5703 mService.unregisterQosCallback(connection);
5704 mQosCallbackConnections.remove(connection);
5705 } else {
5706 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5707 }
5708 }
5709 } catch (final RemoteException e) {
5710 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5711 e.rethrowFromSystemServer();
5712 }
5713 }
5714
5715 /**
5716 * Gets the connection related to the callback.
5717 *
5718 * @param callback the callback to look up
5719 * @return the related connection
5720 */
5721 @Nullable
5722 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5723 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5724 // Checking by reference here is intentional
5725 if (connection.getCallback() == callback) {
5726 return connection;
5727 }
5728 }
5729 return null;
5730 }
5731
5732 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005733 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005734 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5735 * be used to request that the system provide a network without causing the network to be
5736 * in the foreground.
5737 *
5738 * <p>This method will attempt to find the best network that matches the passed
5739 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5740 * criteria. The platform will evaluate which network is the best at its own discretion.
5741 * Throughput, latency, cost per byte, policy, user preference and other considerations
5742 * may be factored in the decision of what is considered the best network.
5743 *
5744 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5745 * matching this request, while always attempting to match the request to a better network if
5746 * possible. If a better match is found, the platform will switch this request to the now-best
5747 * network and inform the app of the newly best network by invoking
5748 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5749 * will not try to maintain any other network than the best one currently matching the request:
5750 * a network not matching any network request may be disconnected at any time.
5751 *
5752 * <p>For example, an application could use this method to obtain a connected cellular network
5753 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5754 * radio to consume additional power. Or, an application could inform the system that it wants
5755 * a network supporting sending MMSes and have the system let it know about the currently best
5756 * MMS-supporting network through the provided {@link NetworkCallback}.
5757 *
5758 * <p>The status of the request can be followed by listening to the various callbacks described
5759 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5760 * used to direct traffic to the network (although accessing some networks may be subject to
5761 * holding specific permissions). Callers will learn about the specific characteristics of the
5762 * network through
5763 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5764 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5765 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5766 * matching the request at any given time; therefore when a better network matching the request
5767 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5768 * with the new network after which no further updates are given about the previously-best
5769 * network, unless it becomes the best again at some later time. All callbacks are invoked
5770 * in order on the same thread, which by default is a thread created by the framework running
5771 * in the app.
5772 *
5773 * <p>This{@link NetworkRequest} will live until released via
5774 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5775 * which point the system may let go of the network at any time.
5776 *
5777 * <p>It is presently unsupported to request a network with mutable
5778 * {@link NetworkCapabilities} such as
5779 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5780 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5781 * as these {@code NetworkCapabilities} represent states that a particular
5782 * network may never attain, and whether a network will attain these states
5783 * is unknown prior to bringing up the network so the framework does not
5784 * know how to go about satisfying a request with these capabilities.
5785 *
5786 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5787 * number of outstanding requests to 100 per app (identified by their UID), shared with
5788 * all variants of this method, of {@link #registerNetworkCallback} as well as
5789 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5790 * Requesting a network with this method will count toward this limit. If this limit is
5791 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5792 * make sure to unregister the callbacks with
5793 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5794 *
5795 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005796 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5797 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005798 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5799 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005800 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5801 * @throws SecurityException if missing the appropriate permissions.
5802 * @throws RuntimeException if the app already has too many callbacks registered.
5803 *
5804 * @hide
5805 */
5806 @SystemApi(client = MODULE_LIBRARIES)
5807 @SuppressLint("ExecutorRegistration")
5808 @RequiresPermission(anyOf = {
5809 android.Manifest.permission.NETWORK_SETTINGS,
5810 android.Manifest.permission.NETWORK_STACK,
5811 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5812 })
5813 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005814 @NonNull NetworkCallback networkCallback,
5815 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005816 final NetworkCapabilities nc = request.networkCapabilities;
5817 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005818 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005819 }
James Mattis12aeab82021-01-10 14:24:24 -08005820
5821 /**
James Mattis12aeab82021-01-10 14:24:24 -08005822 * Used by automotive devices to set the network preferences used to direct traffic at an
5823 * application level as per the given OemNetworkPreferences. An example use-case would be an
5824 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5825 * vehicle via a particular network.
5826 *
5827 * Calling this will overwrite the existing preference.
5828 *
5829 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5830 * @param executor the executor on which listener will be invoked.
5831 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5832 * communicate completion of setOemNetworkPreference(). This will only be
5833 * called once upon successful completion of setOemNetworkPreference().
5834 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5835 * @throws SecurityException if missing the appropriate permissions.
5836 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005837 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005838 */
James Mattis6e2d7022021-01-26 16:23:52 -08005839 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005840 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005841 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005842 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005843 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005844 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5845 if (null != listener) {
5846 Objects.requireNonNull(executor, "Executor must be non-null");
5847 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005848 final IOnCompleteListener listenerInternal = listener == null ? null :
5849 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005850 @Override
5851 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005852 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005853 }
5854 };
5855
5856 try {
5857 mService.setOemNetworkPreference(preference, listenerInternal);
5858 } catch (RemoteException e) {
5859 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5860 throw e.rethrowFromSystemServer();
5861 }
5862 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005863
Chalard Jeanad565e22021-02-25 17:23:40 +09005864 /**
5865 * Request that a user profile is put by default on a network matching a given preference.
5866 *
5867 * See the documentation for the individual preferences for a description of the supported
5868 * behaviors.
5869 *
5870 * @param profile the profile concerned.
5871 * @param preference the preference for this profile.
5872 * @param executor an executor to execute the listener on. Optional if listener is null.
5873 * @param listener an optional listener to listen for completion of the operation.
5874 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5875 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005876 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5877 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005878 * @hide
5879 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005880 // This function is for establishing per-profile default networking and can only be called by
5881 // the device policy manager, running as the system server. It would make no sense to call it
5882 // on a context for a user because it does not establish a setting on behalf of a user, rather
5883 // it establishes a setting for a user on behalf of the DPM.
5884 @SuppressLint({"UserHandle"})
5885 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005886 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005887 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005888 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005889 @ProfileNetworkPreferencePolicy final int preference,
5890 @Nullable @CallbackExecutor final Executor executor,
5891 @Nullable final Runnable listener) {
5892
5893 ProfileNetworkPreference.Builder preferenceBuilder =
5894 new ProfileNetworkPreference.Builder();
5895 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005896 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5897 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5898 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005899 setProfileNetworkPreferences(profile,
5900 List.of(preferenceBuilder.build()), executor, listener);
5901 }
5902
5903 /**
5904 * Set a list of default network selection policies for a user profile.
5905 *
5906 * Calling this API with a user handle defines the entire policy for that user handle.
5907 * It will overwrite any setting previously set for the same user profile,
5908 * and not affect previously set settings for other handles.
5909 *
5910 * Call this API with an empty list to remove settings for this user profile.
5911 *
5912 * See {@link ProfileNetworkPreference} for more details on each preference
5913 * parameter.
5914 *
5915 * @param profile the user profile for which the preference is being set.
5916 * @param profileNetworkPreferences the list of profile network preferences for the
5917 * provided profile.
5918 * @param executor an executor to execute the listener on. Optional if listener is null.
5919 * @param listener an optional listener to listen for completion of the operation.
5920 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5921 * @throws SecurityException if missing the appropriate permissions.
5922 * @hide
5923 */
5924 @SystemApi(client = MODULE_LIBRARIES)
5925 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5926 public void setProfileNetworkPreferences(
5927 @NonNull final UserHandle profile,
5928 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005929 @Nullable @CallbackExecutor final Executor executor,
5930 @Nullable final Runnable listener) {
5931 if (null != listener) {
5932 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5933 }
5934 final IOnCompleteListener proxy;
5935 if (null == listener) {
5936 proxy = null;
5937 } else {
5938 proxy = new IOnCompleteListener.Stub() {
5939 @Override
5940 public void onComplete() {
5941 executor.execute(listener::run);
5942 }
5943 };
5944 }
5945 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005946 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005947 } catch (RemoteException e) {
5948 throw e.rethrowFromSystemServer();
5949 }
5950 }
5951
lucaslin5cdbcfb2021-03-12 00:46:33 +08005952 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005953 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005954 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005955 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005956
5957 /**
5958 * Get the network ID range reserved for IPSec tunnel interfaces.
5959 *
5960 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5961 * @hide
5962 */
5963 @SystemApi(client = MODULE_LIBRARIES)
5964 @NonNull
5965 public static Range<Integer> getIpSecNetIdRange() {
5966 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5967 }
markchien738ad912021-12-09 18:15:45 +08005968
5969 /**
Junyu Laic279f182023-09-07 15:25:52 +08005970 * Sets data saver switch.
5971 *
5972 * @param enable True if enable.
5973 * @throws IllegalStateException if failed.
5974 * @hide
5975 */
5976 @FlaggedApi(Flags.SET_DATA_SAVER_VIA_CM)
5977 @SystemApi(client = MODULE_LIBRARIES)
5978 @RequiresPermission(anyOf = {
5979 android.Manifest.permission.NETWORK_SETTINGS,
5980 android.Manifest.permission.NETWORK_STACK,
5981 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5982 })
5983 public void setDataSaverEnabled(final boolean enable) {
5984 try {
5985 mService.setDataSaverEnabled(enable);
5986 } catch (RemoteException e) {
5987 throw e.rethrowFromSystemServer();
5988 }
5989 }
5990
5991 /**
markchiene46042b2022-03-02 18:07:35 +08005992 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5993 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005994 *
5995 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005996 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005997 * @hide
5998 */
5999 @SystemApi(client = MODULE_LIBRARIES)
6000 @RequiresPermission(anyOf = {
6001 android.Manifest.permission.NETWORK_SETTINGS,
6002 android.Manifest.permission.NETWORK_STACK,
6003 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6004 })
markchiene46042b2022-03-02 18:07:35 +08006005 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006006 try {
markchiene46042b2022-03-02 18:07:35 +08006007 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08006008 } catch (RemoteException e) {
6009 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006010 }
6011 }
6012
6013 /**
markchiene46042b2022-03-02 18:07:35 +08006014 * Removes the specified UID from the list of UIDs that are allowed to use background data on
6015 * metered networks when background data is restricted. The deny list takes precedence over
6016 * the allow list.
6017 *
6018 * @param uid uid of target app
6019 * @throws IllegalStateException if updating allow list failed.
6020 * @hide
6021 */
6022 @SystemApi(client = MODULE_LIBRARIES)
6023 @RequiresPermission(anyOf = {
6024 android.Manifest.permission.NETWORK_SETTINGS,
6025 android.Manifest.permission.NETWORK_STACK,
6026 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6027 })
6028 public void removeUidFromMeteredNetworkAllowList(final int uid) {
6029 try {
6030 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
6031 } catch (RemoteException e) {
6032 throw e.rethrowFromSystemServer();
6033 }
6034 }
6035
6036 /**
6037 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
6038 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08006039 *
6040 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006041 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08006042 * @hide
6043 */
6044 @SystemApi(client = MODULE_LIBRARIES)
6045 @RequiresPermission(anyOf = {
6046 android.Manifest.permission.NETWORK_SETTINGS,
6047 android.Manifest.permission.NETWORK_STACK,
6048 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6049 })
markchiene46042b2022-03-02 18:07:35 +08006050 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006051 try {
markchiene46042b2022-03-02 18:07:35 +08006052 mService.updateMeteredNetworkDenyList(uid, true /* add */);
6053 } catch (RemoteException e) {
6054 throw e.rethrowFromSystemServer();
6055 }
6056 }
6057
6058 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09006059 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08006060 * networks if background data is not restricted. The deny list takes precedence over the
6061 * allow list.
6062 *
6063 * @param uid uid of target app
6064 * @throws IllegalStateException if updating deny list failed.
6065 * @hide
6066 */
6067 @SystemApi(client = MODULE_LIBRARIES)
6068 @RequiresPermission(anyOf = {
6069 android.Manifest.permission.NETWORK_SETTINGS,
6070 android.Manifest.permission.NETWORK_STACK,
6071 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6072 })
6073 public void removeUidFromMeteredNetworkDenyList(final int uid) {
6074 try {
6075 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08006076 } catch (RemoteException e) {
6077 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08006078 }
6079 }
6080
6081 /**
6082 * Sets a firewall rule for the specified UID on the specified chain.
6083 *
6084 * @param chain target chain.
6085 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08006086 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08006087 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08006088 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08006089 * @hide
6090 */
6091 @SystemApi(client = MODULE_LIBRARIES)
6092 @RequiresPermission(anyOf = {
6093 android.Manifest.permission.NETWORK_SETTINGS,
6094 android.Manifest.permission.NETWORK_STACK,
6095 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6096 })
markchien3c04e662022-03-22 16:29:56 +08006097 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
6098 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08006099 try {
markchien3c04e662022-03-22 16:29:56 +08006100 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08006101 } catch (RemoteException e) {
6102 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006103 }
6104 }
markchien98a6f952022-01-13 23:43:53 +08006105
6106 /**
Motomu Utsumi900b8062023-01-19 16:16:49 +09006107 * Get firewall rule of specified firewall chain on specified uid.
6108 *
6109 * @param chain target chain.
6110 * @param uid target uid
6111 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
6112 * @throws UnsupportedOperationException if called on pre-T devices.
6113 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6114 * cause of the failure.
6115 * @hide
6116 */
6117 @RequiresPermission(anyOf = {
6118 android.Manifest.permission.NETWORK_SETTINGS,
6119 android.Manifest.permission.NETWORK_STACK,
6120 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6121 })
6122 public int getUidFirewallRule(@FirewallChain final int chain, final int uid) {
6123 try {
6124 return mService.getUidFirewallRule(chain, uid);
6125 } catch (RemoteException e) {
6126 throw e.rethrowFromSystemServer();
6127 }
6128 }
6129
6130 /**
markchien98a6f952022-01-13 23:43:53 +08006131 * Enables or disables the specified firewall chain.
6132 *
6133 * @param chain target chain.
6134 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00006135 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08006136 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08006137 * @hide
6138 */
6139 @SystemApi(client = MODULE_LIBRARIES)
6140 @RequiresPermission(anyOf = {
6141 android.Manifest.permission.NETWORK_SETTINGS,
6142 android.Manifest.permission.NETWORK_STACK,
6143 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6144 })
6145 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
6146 try {
6147 mService.setFirewallChainEnabled(chain, enable);
6148 } catch (RemoteException e) {
6149 throw e.rethrowFromSystemServer();
6150 }
6151 }
markchien00a0bed2022-01-13 23:46:13 +08006152
6153 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00006154 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006155 *
6156 * @param chain target chain.
6157 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6158 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006159 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6160 * cause of the failure.
6161 * @hide
6162 */
6163 @RequiresPermission(anyOf = {
6164 android.Manifest.permission.NETWORK_SETTINGS,
6165 android.Manifest.permission.NETWORK_STACK,
6166 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6167 })
6168 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6169 try {
6170 return mService.getFirewallChainEnabled(chain);
6171 } catch (RemoteException e) {
6172 throw e.rethrowFromSystemServer();
6173 }
6174 }
6175
6176 /**
markchien00a0bed2022-01-13 23:46:13 +08006177 * Replaces the contents of the specified UID-based firewall chain.
6178 *
6179 * @param chain target chain to replace.
6180 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006181 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006182 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6183 * @hide
6184 */
6185 @SystemApi(client = MODULE_LIBRARIES)
6186 @RequiresPermission(anyOf = {
6187 android.Manifest.permission.NETWORK_SETTINGS,
6188 android.Manifest.permission.NETWORK_STACK,
6189 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6190 })
6191 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6192 Objects.requireNonNull(uids);
6193 try {
6194 mService.replaceFirewallChain(chain, uids);
6195 } catch (RemoteException e) {
6196 throw e.rethrowFromSystemServer();
6197 }
6198 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006199
6200 /** @hide */
6201 public IBinder getCompanionDeviceManagerProxyService() {
6202 try {
6203 return mService.getCompanionDeviceManagerProxyService();
6204 } catch (RemoteException e) {
6205 throw e.rethrowFromSystemServer();
6206 }
6207 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006208}