blob: 8963e308da7fae5e2a519935c90fa585bce01936 [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 Laidf210362023-10-24 02:47:50 +000029import 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 Laidf210362023-10-24 02:47:50 +0000119 // 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})
Anton Kulakov6eea22b2023-10-13 15:04:01 +00003823 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
3824 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3825 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003826 try {
Anton Kulakov6eea22b2023-10-13 15:04:01 +00003827 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003828 } catch (RemoteException e) {
3829 throw e.rethrowFromSystemServer();
3830 }
3831 }
3832
3833 /**
3834 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3835 * changes. Should be extended by applications wanting notifications.
3836 *
3837 * A {@code NetworkCallback} is registered by calling
3838 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3839 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3840 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3841 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3842 * A {@code NetworkCallback} should be registered at most once at any time.
3843 * A {@code NetworkCallback} that has been unregistered can be registered again.
3844 */
3845 public static class NetworkCallback {
3846 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003847 * No flags associated with this callback.
3848 * @hide
3849 */
3850 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003851
Roshan Piuse08bc182020-12-22 15:10:42 -08003852 /**
lucaslinc582d502022-01-27 09:07:00 +08003853 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3854 *
3855 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3856 * Prior to Android 12, this information is always returned to apps holding the appropriate
3857 * permission, possibly noting that the app has used location.
3858 * <p>In Android 12 and above, by default the sent objects do not contain any location
3859 * information, even if the app holds the necessary permissions, and the system does not
3860 * take note of location usage by the app. Apps can request that location information is
3861 * included, in which case the system will check location permission and the location
3862 * toggle state, and take note of location usage by the app if any such information is
3863 * returned.
3864 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003865 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3866 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3867 * <p>
3868 * These include:
3869 * <li> Some transport info instances (retrieved via
3870 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3871 * contain location sensitive information.
3872 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003873 * sensitive for wifi suggestor apps (i.e using
3874 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003875 * </p>
3876 * <p>
3877 * Note:
3878 * <li> Retrieving this location sensitive information (subject to app's location
3879 * permissions) will be noted by system. </li>
3880 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003881 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003882 */
Roshan Pius189d0092021-03-11 21:16:44 -08003883 // Note: Some existing fields which are location sensitive may still be included without
3884 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003885 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3886
3887 /** @hide */
3888 @Retention(RetentionPolicy.SOURCE)
3889 @IntDef(flag = true, prefix = "FLAG_", value = {
3890 FLAG_NONE,
3891 FLAG_INCLUDE_LOCATION_INFO
3892 })
3893 public @interface Flag { }
3894
3895 /**
3896 * All the valid flags for error checking.
3897 */
3898 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3899
3900 public NetworkCallback() {
3901 this(FLAG_NONE);
3902 }
3903
3904 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003905 if ((flags & VALID_FLAGS) != flags) {
3906 throw new IllegalArgumentException("Invalid flags");
3907 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003908 mFlags = flags;
3909 }
3910
3911 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003912 * Called when the framework connects to a new network to evaluate whether it satisfies this
3913 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3914 * callback. There is no guarantee that this new network will satisfy any requests, or that
3915 * the network will stay connected for longer than the time necessary to evaluate it.
3916 * <p>
3917 * Most applications <b>should not</b> act on this callback, and should instead use
3918 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3919 * the framework in properly evaluating the network &mdash; for example, an application that
3920 * can automatically log in to a captive portal without user intervention.
3921 *
3922 * @param network The {@link Network} of the network that is being evaluated.
3923 *
3924 * @hide
3925 */
3926 public void onPreCheck(@NonNull Network network) {}
3927
3928 /**
3929 * Called when the framework connects and has declared a new network ready for use.
3930 * This callback may be called more than once if the {@link Network} that is
3931 * satisfying the request changes.
3932 *
3933 * @param network The {@link Network} of the satisfying network.
3934 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3935 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3936 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3937 * @hide
3938 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003939 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003940 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003941 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003942 // Internally only this method is called when a new network is available, and
3943 // it calls the callback in the same way and order that older versions used
3944 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003945 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3946 onBlockedStatusChanged(network, blocked);
3947 }
3948
3949 /**
3950 * Legacy variant of onAvailable that takes a boolean blocked reason.
3951 *
3952 * This method has never been public API, but it's not final, so there may be apps that
3953 * implemented it and rely on it being called. Do our best not to break them.
3954 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3955 * this method is called. There does not seem to be a way to avoid this.
3956 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3957 *
3958 * @hide
3959 */
3960 public void onAvailable(@NonNull Network network,
3961 @NonNull NetworkCapabilities networkCapabilities,
3962 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003963 onAvailable(network);
3964 if (!networkCapabilities.hasCapability(
3965 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3966 onNetworkSuspended(network);
3967 }
3968 onCapabilitiesChanged(network, networkCapabilities);
3969 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003970 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003971 }
3972
3973 /**
3974 * Called when the framework connects and has declared a new network ready for use.
3975 *
3976 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3977 * be available at the same time, and onAvailable will be called for each of these as they
3978 * appear.
3979 *
3980 * <p>For callbacks registered with {@link #requestNetwork} and
3981 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3982 * is the new best network for this request and is now tracked by this callback ; this
3983 * callback will no longer receive method calls about other networks that may have been
3984 * passed to this method previously. The previously-best network may have disconnected, or
3985 * it may still be around and the newly-best network may simply be better.
3986 *
3987 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3988 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3989 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3990 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3991 *
3992 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3993 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3994 * this callback as this is prone to race conditions (there is no guarantee the objects
3995 * returned by these methods will be current). Instead, wait for a call to
3996 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3997 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3998 * to be well-ordered with respect to other callbacks.
3999 *
4000 * @param network The {@link Network} of the satisfying network.
4001 */
4002 public void onAvailable(@NonNull Network network) {}
4003
4004 /**
4005 * Called when the network is about to be lost, typically because there are no outstanding
4006 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
4007 * with the new replacement network for graceful handover. This method is not guaranteed
4008 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
4009 * network is suddenly disconnected.
4010 *
4011 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4012 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4013 * this callback as this is prone to race conditions ; calling these methods while in a
4014 * callback may return an outdated or even a null object.
4015 *
4016 * @param network The {@link Network} that is about to be lost.
4017 * @param maxMsToLive The time in milliseconds the system intends to keep the network
4018 * connected for graceful handover; note that the network may still
4019 * suffer a hard loss at any time.
4020 */
4021 public void onLosing(@NonNull Network network, int maxMsToLive) {}
4022
4023 /**
4024 * Called when a network disconnects or otherwise no longer satisfies this request or
4025 * callback.
4026 *
4027 * <p>If the callback was registered with requestNetwork() or
4028 * registerDefaultNetworkCallback(), it will only be invoked against the last network
4029 * returned by onAvailable() when that network is lost and no other network satisfies
4030 * the criteria of the request.
4031 *
4032 * <p>If the callback was registered with registerNetworkCallback() it will be called for
4033 * each network which no longer satisfies the criteria of the callback.
4034 *
4035 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4036 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4037 * this callback as this is prone to race conditions ; calling these methods while in a
4038 * callback may return an outdated or even a null object.
4039 *
4040 * @param network The {@link Network} lost.
4041 */
4042 public void onLost(@NonNull Network network) {}
4043
4044 /**
4045 * Called if no network is found within the timeout time specified in
4046 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
4047 * requested network request cannot be fulfilled (whether or not a timeout was
4048 * specified). When this callback is invoked the associated
4049 * {@link NetworkRequest} will have already been removed and released, as if
4050 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
4051 */
4052 public void onUnavailable() {}
4053
4054 /**
4055 * Called when the network corresponding to this request changes capabilities but still
4056 * satisfies the requested criteria.
4057 *
4058 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4059 * to be called immediately after {@link #onAvailable}.
4060 *
4061 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
4062 * ConnectivityManager methods in this callback as this is prone to race conditions :
4063 * calling these methods while in a callback may return an outdated or even a null object.
4064 *
4065 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08004066 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004067 * network.
4068 */
4069 public void onCapabilitiesChanged(@NonNull Network network,
4070 @NonNull NetworkCapabilities networkCapabilities) {}
4071
4072 /**
4073 * Called when the network corresponding to this request changes {@link LinkProperties}.
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 #getNetworkCapabilities(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 link properties have changed.
4083 * @param linkProperties The new {@link LinkProperties} for this network.
4084 */
4085 public void onLinkPropertiesChanged(@NonNull Network network,
4086 @NonNull LinkProperties linkProperties) {}
4087
4088 /**
4089 * Called when the network the framework connected to for this request suspends data
4090 * transmission temporarily.
4091 *
4092 * <p>This generally means that while the TCP connections are still live temporarily
4093 * network data fails to transfer. To give a specific example, this is used on cellular
4094 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4095 * means read operations on sockets on this network will block once the buffers are
4096 * drained, and write operations will block once the buffers are full.
4097 *
4098 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4099 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4100 * this callback as this is prone to race conditions (there is no guarantee the objects
4101 * returned by these methods will be current).
4102 *
4103 * @hide
4104 */
4105 public void onNetworkSuspended(@NonNull Network network) {}
4106
4107 /**
4108 * Called when the network the framework connected to for this request
4109 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4110 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4111
4112 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4113 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4114 * this callback as this is prone to race conditions : calling these methods while in a
4115 * callback may return an outdated or even a null object.
4116 *
4117 * @hide
4118 */
4119 public void onNetworkResumed(@NonNull Network network) {}
4120
4121 /**
4122 * Called when access to the specified network is blocked or unblocked.
4123 *
4124 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4125 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4126 * this callback as this is prone to race conditions : calling these methods while in a
4127 * callback may return an outdated or even a null object.
4128 *
4129 * @param network The {@link Network} whose blocked status has changed.
4130 * @param blocked The blocked status of this {@link Network}.
4131 */
4132 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4133
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004134 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004135 * Called when access to the specified network is blocked or unblocked, or the reason for
4136 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004137 *
4138 * If a NetworkCallback object implements this method,
4139 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
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 * @hide
4149 */
4150 @SystemApi(client = MODULE_LIBRARIES)
4151 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4152 onBlockedStatusChanged(network, blocked != 0);
4153 }
4154
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004155 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004156 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004157 }
4158
4159 /**
4160 * Constant error codes used by ConnectivityService to communicate about failures and errors
4161 * across a Binder boundary.
4162 * @hide
4163 */
4164 public interface Errors {
4165 int TOO_MANY_REQUESTS = 1;
4166 }
4167
4168 /** @hide */
4169 public static class TooManyRequestsException extends RuntimeException {}
4170
4171 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4172 switch (e.errorCode) {
4173 case Errors.TOO_MANY_REQUESTS:
4174 return new TooManyRequestsException();
4175 default:
4176 Log.w(TAG, "Unknown service error code " + e.errorCode);
4177 return new RuntimeException(e);
4178 }
4179 }
4180
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004181 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004182 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004183 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004184 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004185 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004186 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004187 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004188 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004189 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004190 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004191 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004192 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004193 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004194 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004195 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004196 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004197 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004198 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004199 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004200 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004201 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004202 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004203
4204 /** @hide */
4205 public static String getCallbackName(int whichCallback) {
4206 switch (whichCallback) {
4207 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4208 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4209 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4210 case CALLBACK_LOST: return "CALLBACK_LOST";
4211 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4212 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4213 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4214 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4215 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4216 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4217 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4218 default:
4219 return Integer.toString(whichCallback);
4220 }
4221 }
4222
zhujiatai79b0de92022-09-22 15:44:02 +08004223 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004224 private static final String TAG = "ConnectivityManager.CallbackHandler";
4225 private static final boolean DBG = false;
4226
4227 CallbackHandler(Looper looper) {
4228 super(looper);
4229 }
4230
4231 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004232 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004233 }
4234
4235 @Override
4236 public void handleMessage(Message message) {
4237 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004238 // the sInstance can't be null because to send this message a ConnectivityManager
4239 // instance must have been created prior to creating the thread on which this
4240 // Handler is running.
4241 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004242 return;
4243 }
4244
4245 final NetworkRequest request = getObject(message, NetworkRequest.class);
4246 final Network network = getObject(message, Network.class);
4247 final NetworkCallback callback;
4248 synchronized (sCallbacks) {
4249 callback = sCallbacks.get(request);
4250 if (callback == null) {
4251 Log.w(TAG,
4252 "callback not found for " + getCallbackName(message.what) + " message");
4253 return;
4254 }
4255 if (message.what == CALLBACK_UNAVAIL) {
4256 sCallbacks.remove(request);
4257 callback.networkRequest = ALREADY_UNREGISTERED;
4258 }
4259 }
4260 if (DBG) {
4261 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4262 }
4263
4264 switch (message.what) {
4265 case CALLBACK_PRECHECK: {
4266 callback.onPreCheck(network);
4267 break;
4268 }
4269 case CALLBACK_AVAILABLE: {
4270 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4271 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004272 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004273 break;
4274 }
4275 case CALLBACK_LOSING: {
4276 callback.onLosing(network, message.arg1);
4277 break;
4278 }
4279 case CALLBACK_LOST: {
4280 callback.onLost(network);
4281 break;
4282 }
4283 case CALLBACK_UNAVAIL: {
4284 callback.onUnavailable();
4285 break;
4286 }
4287 case CALLBACK_CAP_CHANGED: {
4288 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4289 callback.onCapabilitiesChanged(network, cap);
4290 break;
4291 }
4292 case CALLBACK_IP_CHANGED: {
4293 LinkProperties lp = getObject(message, LinkProperties.class);
4294 callback.onLinkPropertiesChanged(network, lp);
4295 break;
4296 }
4297 case CALLBACK_SUSPENDED: {
4298 callback.onNetworkSuspended(network);
4299 break;
4300 }
4301 case CALLBACK_RESUMED: {
4302 callback.onNetworkResumed(network);
4303 break;
4304 }
4305 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004306 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004307 }
4308 }
4309 }
4310
4311 private <T> T getObject(Message msg, Class<T> c) {
4312 return (T) msg.getData().getParcelable(c.getSimpleName());
4313 }
4314 }
4315
4316 private CallbackHandler getDefaultHandler() {
4317 synchronized (sCallbacks) {
4318 if (sCallbackHandler == null) {
4319 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4320 }
4321 return sCallbackHandler;
4322 }
4323 }
4324
4325 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4326 private static CallbackHandler sCallbackHandler;
4327
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004328 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4329 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4330 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004331 printStackTrace();
4332 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004333 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4334 throw new IllegalArgumentException("null NetworkCapabilities");
4335 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004336 final NetworkRequest request;
4337 final String callingPackageName = mContext.getOpPackageName();
4338 try {
4339 synchronized(sCallbacks) {
4340 if (callback.networkRequest != null
4341 && callback.networkRequest != ALREADY_UNREGISTERED) {
4342 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4343 // and requests (http://b/20701525).
4344 Log.e(TAG, "NetworkCallback was already registered");
4345 }
4346 Messenger messenger = new Messenger(handler);
4347 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004348 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004349 if (reqType == LISTEN) {
4350 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004351 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004352 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004353 } else {
4354 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004355 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4356 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004357 }
4358 if (request != null) {
4359 sCallbacks.put(request, callback);
4360 }
4361 callback.networkRequest = request;
4362 }
4363 } catch (RemoteException e) {
4364 throw e.rethrowFromSystemServer();
4365 } catch (ServiceSpecificException e) {
4366 throw convertServiceException(e);
4367 }
4368 return request;
4369 }
4370
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004371 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4372 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4373 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4374 legacyType, handler);
4375 }
4376
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004377 /**
4378 * Helper function to request a network with a particular legacy type.
4379 *
4380 * This API is only for use in internal system code that requests networks with legacy type and
4381 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4382 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4383 *
4384 * @param request {@link NetworkRequest} describing this request.
4385 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4386 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4387 * be a positive value (i.e. >0).
4388 * @param legacyType to specify the network type(#TYPE_*).
4389 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4390 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4391 * the callback must not be shared - it uniquely specifies this request.
4392 *
4393 * @hide
4394 */
4395 @SystemApi
4396 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4397 public void requestNetwork(@NonNull NetworkRequest request,
4398 int timeoutMs, int legacyType, @NonNull Handler handler,
4399 @NonNull NetworkCallback networkCallback) {
4400 if (legacyType == TYPE_NONE) {
4401 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4402 }
4403 CallbackHandler cbHandler = new CallbackHandler(handler);
4404 NetworkCapabilities nc = request.networkCapabilities;
4405 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4406 }
4407
4408 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004409 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004410 *
4411 * <p>This method will attempt to find the best network that matches the passed
4412 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4413 * criteria. The platform will evaluate which network is the best at its own discretion.
4414 * Throughput, latency, cost per byte, policy, user preference and other considerations
4415 * may be factored in the decision of what is considered the best network.
4416 *
4417 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4418 * matching this request, while always attempting to match the request to a better network if
4419 * possible. If a better match is found, the platform will switch this request to the now-best
4420 * network and inform the app of the newly best network by invoking
4421 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4422 * will not try to maintain any other network than the best one currently matching the request:
4423 * a network not matching any network request may be disconnected at any time.
4424 *
4425 * <p>For example, an application could use this method to obtain a connected cellular network
4426 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4427 * radio to consume additional power. Or, an application could inform the system that it wants
4428 * a network supporting sending MMSes and have the system let it know about the currently best
4429 * MMS-supporting network through the provided {@link NetworkCallback}.
4430 *
4431 * <p>The status of the request can be followed by listening to the various callbacks described
4432 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4433 * used to direct traffic to the network (although accessing some networks may be subject to
4434 * holding specific permissions). Callers will learn about the specific characteristics of the
4435 * network through
4436 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4437 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4438 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4439 * matching the request at any given time; therefore when a better network matching the request
4440 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4441 * with the new network after which no further updates are given about the previously-best
4442 * network, unless it becomes the best again at some later time. All callbacks are invoked
4443 * in order on the same thread, which by default is a thread created by the framework running
4444 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004445 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004446 * callbacks are invoked.
4447 *
4448 * <p>This{@link NetworkRequest} will live until released via
4449 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4450 * which point the system may let go of the network at any time.
4451 *
4452 * <p>A version of this method which takes a timeout is
4453 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4454 * wait for a limited amount of time for the network to become unavailable.
4455 *
4456 * <p>It is presently unsupported to request a network with mutable
4457 * {@link NetworkCapabilities} such as
4458 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4459 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4460 * as these {@code NetworkCapabilities} represent states that a particular
4461 * network may never attain, and whether a network will attain these states
4462 * is unknown prior to bringing up the network so the framework does not
4463 * know how to go about satisfying a request with these capabilities.
4464 *
4465 * <p>This method requires the caller to hold either the
4466 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4467 * or the ability to modify system settings as determined by
4468 * {@link android.provider.Settings.System#canWrite}.</p>
4469 *
4470 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4471 * number of outstanding requests to 100 per app (identified by their UID), shared with
4472 * all variants of this method, of {@link #registerNetworkCallback} as well as
4473 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4474 * Requesting a network with this method will count toward this limit. If this limit is
4475 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4476 * make sure to unregister the callbacks with
4477 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4478 *
4479 * @param request {@link NetworkRequest} describing this request.
4480 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4481 * the callback must not be shared - it uniquely specifies this request.
4482 * The callback is invoked on the default internal Handler.
4483 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4484 * @throws SecurityException if missing the appropriate permissions.
4485 * @throws RuntimeException if the app already has too many callbacks registered.
4486 */
4487 public void requestNetwork(@NonNull NetworkRequest request,
4488 @NonNull NetworkCallback networkCallback) {
4489 requestNetwork(request, networkCallback, getDefaultHandler());
4490 }
4491
4492 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004493 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004494 *
4495 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4496 * but runs all the callbacks on the passed Handler.
4497 *
4498 * <p>This method has the same permission requirements as
4499 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4500 * and throws the same exceptions in the same conditions.
4501 *
4502 * @param request {@link NetworkRequest} describing this request.
4503 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4504 * the callback must not be shared - it uniquely specifies this request.
4505 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4506 */
4507 public void requestNetwork(@NonNull NetworkRequest request,
4508 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4509 CallbackHandler cbHandler = new CallbackHandler(handler);
4510 NetworkCapabilities nc = request.networkCapabilities;
4511 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4512 }
4513
4514 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004515 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004516 * by a timeout.
4517 *
4518 * This function behaves identically to the non-timed-out version
4519 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4520 * is not found within the given time (in milliseconds) the
4521 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4522 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4523 * not have to be released if timed-out (it is automatically released). Unregistering a
4524 * request that timed out is not an error.
4525 *
4526 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4527 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4528 * for that purpose. Calling this method will attempt to bring up the requested network.
4529 *
4530 * <p>This method has the same permission requirements as
4531 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4532 * and throws the same exceptions in the same conditions.
4533 *
4534 * @param request {@link NetworkRequest} describing this request.
4535 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4536 * the callback must not be shared - it uniquely specifies this request.
4537 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4538 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4539 * be a positive value (i.e. >0).
4540 */
4541 public void requestNetwork(@NonNull NetworkRequest request,
4542 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4543 checkTimeout(timeoutMs);
4544 NetworkCapabilities nc = request.networkCapabilities;
4545 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4546 getDefaultHandler());
4547 }
4548
4549 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004550 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004551 * by a timeout.
4552 *
4553 * This method behaves identically to
4554 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4555 * on the passed Handler.
4556 *
4557 * <p>This method has the same permission requirements as
4558 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4559 * and throws the same exceptions in the same conditions.
4560 *
4561 * @param request {@link NetworkRequest} describing this request.
4562 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4563 * the callback must not be shared - it uniquely specifies this request.
4564 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4565 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4566 * before {@link NetworkCallback#onUnavailable} is called.
4567 */
4568 public void requestNetwork(@NonNull NetworkRequest request,
4569 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4570 checkTimeout(timeoutMs);
4571 CallbackHandler cbHandler = new CallbackHandler(handler);
4572 NetworkCapabilities nc = request.networkCapabilities;
4573 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4574 }
4575
4576 /**
4577 * The lookup key for a {@link Network} object included with the intent after
4578 * successfully finding a network for the applications request. Retrieve it with
4579 * {@link android.content.Intent#getParcelableExtra(String)}.
4580 * <p>
4581 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4582 * then you must get a ConnectivityManager instance before doing so.
4583 */
4584 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4585
4586 /**
4587 * The lookup key for a {@link NetworkRequest} object included with the intent after
4588 * successfully finding a network for the applications request. Retrieve it with
4589 * {@link android.content.Intent#getParcelableExtra(String)}.
4590 */
4591 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4592
4593
4594 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004595 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004596 *
4597 * This function behaves identically to the version that takes a NetworkCallback, but instead
4598 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4599 * the request may outlive the calling application and get called back when a suitable
4600 * network is found.
4601 * <p>
4602 * The operation is an Intent broadcast that goes to a broadcast receiver that
4603 * you registered with {@link Context#registerReceiver} or through the
4604 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4605 * <p>
4606 * The operation Intent is delivered with two extras, a {@link Network} typed
4607 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4608 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4609 * the original requests parameters. It is important to create a new,
4610 * {@link NetworkCallback} based request before completing the processing of the
4611 * Intent to reserve the network or it will be released shortly after the Intent
4612 * is processed.
4613 * <p>
4614 * If there is already a request for this Intent registered (with the equality of
4615 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4616 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4617 * <p>
4618 * The request may be released normally by calling
4619 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4620 * <p>It is presently unsupported to request a network with either
4621 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4622 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4623 * as these {@code NetworkCapabilities} represent states that a particular
4624 * network may never attain, and whether a network will attain these states
4625 * is unknown prior to bringing up the network so the framework does not
4626 * know how to go about satisfying a request with these capabilities.
4627 *
4628 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4629 * number of outstanding requests to 100 per app (identified by their UID), shared with
4630 * all variants of this method, of {@link #registerNetworkCallback} as well as
4631 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4632 * Requesting a network with this method will count toward this limit. If this limit is
4633 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4634 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4635 * or {@link #releaseNetworkRequest(PendingIntent)}.
4636 *
4637 * <p>This method requires the caller to hold either the
4638 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4639 * or the ability to modify system settings as determined by
4640 * {@link android.provider.Settings.System#canWrite}.</p>
4641 *
4642 * @param request {@link NetworkRequest} describing this request.
4643 * @param operation Action to perform when the network is available (corresponds
4644 * to the {@link NetworkCallback#onAvailable} call. Typically
4645 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4646 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4647 * @throws SecurityException if missing the appropriate permissions.
4648 * @throws RuntimeException if the app already has too many callbacks registered.
4649 */
4650 public void requestNetwork(@NonNull NetworkRequest request,
4651 @NonNull PendingIntent operation) {
4652 printStackTrace();
4653 checkPendingIntentNotNull(operation);
4654 try {
4655 mService.pendingRequestForNetwork(
4656 request.networkCapabilities, operation, mContext.getOpPackageName(),
4657 getAttributionTag());
4658 } catch (RemoteException e) {
4659 throw e.rethrowFromSystemServer();
4660 } catch (ServiceSpecificException e) {
4661 throw convertServiceException(e);
4662 }
4663 }
4664
4665 /**
4666 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4667 * <p>
4668 * This method has the same behavior as
4669 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4670 * releasing network resources and disconnecting.
4671 *
4672 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4673 * PendingIntent passed to
4674 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4675 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4676 */
4677 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4678 printStackTrace();
4679 checkPendingIntentNotNull(operation);
4680 try {
4681 mService.releasePendingNetworkRequest(operation);
4682 } catch (RemoteException e) {
4683 throw e.rethrowFromSystemServer();
4684 }
4685 }
4686
4687 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004688 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004689 }
4690
4691 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004692 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004693 }
4694
4695 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004696 if (timeoutMs <= 0) {
4697 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4698 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004699 }
4700
4701 /**
4702 * Registers to receive notifications about all networks which satisfy the given
4703 * {@link NetworkRequest}. The callbacks will continue to be called until
4704 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4705 * called.
4706 *
4707 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4708 * number of outstanding requests to 100 per app (identified by their UID), shared with
4709 * all variants of this method, of {@link #requestNetwork} as well as
4710 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4711 * Requesting a network with this method will count toward this limit. If this limit is
4712 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4713 * make sure to unregister the callbacks with
4714 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4715 *
4716 * @param request {@link NetworkRequest} describing this request.
4717 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4718 * networks change state.
4719 * The callback is invoked on the default internal Handler.
4720 * @throws RuntimeException if the app already has too many callbacks registered.
4721 */
4722 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4723 public void registerNetworkCallback(@NonNull NetworkRequest request,
4724 @NonNull NetworkCallback networkCallback) {
4725 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4726 }
4727
4728 /**
4729 * Registers to receive notifications about all networks which satisfy the given
4730 * {@link NetworkRequest}. The callbacks will continue to be called until
4731 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4732 * called.
4733 *
4734 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4735 * number of outstanding requests to 100 per app (identified by their UID), shared with
4736 * all variants of this method, of {@link #requestNetwork} as well as
4737 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4738 * Requesting a network with this method will count toward this limit. If this limit is
4739 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4740 * make sure to unregister the callbacks with
4741 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4742 *
4743 *
4744 * @param request {@link NetworkRequest} describing this request.
4745 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4746 * networks change state.
4747 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4748 * @throws RuntimeException if the app already has too many callbacks registered.
4749 */
4750 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4751 public void registerNetworkCallback(@NonNull NetworkRequest request,
4752 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4753 CallbackHandler cbHandler = new CallbackHandler(handler);
4754 NetworkCapabilities nc = request.networkCapabilities;
4755 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4756 }
4757
4758 /**
4759 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4760 * {@link NetworkRequest}.
4761 *
4762 * This function behaves identically to the version that takes a NetworkCallback, but instead
4763 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4764 * the request may outlive the calling application and get called back when a suitable
4765 * network is found.
4766 * <p>
4767 * The operation is an Intent broadcast that goes to a broadcast receiver that
4768 * you registered with {@link Context#registerReceiver} or through the
4769 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4770 * <p>
4771 * The operation Intent is delivered with two extras, a {@link Network} typed
4772 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4773 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4774 * the original requests parameters.
4775 * <p>
4776 * If there is already a request for this Intent registered (with the equality of
4777 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4778 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4779 * <p>
4780 * The request may be released normally by calling
4781 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4782 *
4783 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4784 * number of outstanding requests to 100 per app (identified by their UID), shared with
4785 * all variants of this method, of {@link #requestNetwork} as well as
4786 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4787 * Requesting a network with this method will count toward this limit. If this limit is
4788 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4789 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4790 * or {@link #releaseNetworkRequest(PendingIntent)}.
4791 *
4792 * @param request {@link NetworkRequest} describing this request.
4793 * @param operation Action to perform when the network is available (corresponds
4794 * to the {@link NetworkCallback#onAvailable} call. Typically
4795 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4796 * @throws RuntimeException if the app already has too many callbacks registered.
4797 */
4798 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4799 public void registerNetworkCallback(@NonNull NetworkRequest request,
4800 @NonNull PendingIntent operation) {
4801 printStackTrace();
4802 checkPendingIntentNotNull(operation);
4803 try {
4804 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004805 request.networkCapabilities, operation, mContext.getOpPackageName(),
4806 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004807 } catch (RemoteException e) {
4808 throw e.rethrowFromSystemServer();
4809 } catch (ServiceSpecificException e) {
4810 throw convertServiceException(e);
4811 }
4812 }
4813
4814 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004815 * Registers to receive notifications about changes in the application's default network. This
4816 * may be a physical network or a virtual network, such as a VPN that applies to the
4817 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004818 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4819 *
4820 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4821 * number of outstanding requests to 100 per app (identified by their UID), shared with
4822 * all variants of this method, of {@link #requestNetwork} as well as
4823 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4824 * Requesting a network with this method will count toward this limit. If this limit is
4825 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4826 * make sure to unregister the callbacks with
4827 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4828 *
4829 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004830 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004831 * The callback is invoked on the default internal Handler.
4832 * @throws RuntimeException if the app already has too many callbacks registered.
4833 */
4834 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4835 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4836 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4837 }
4838
4839 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004840 * Registers to receive notifications about changes in the application's default network. This
4841 * may be a physical network or a virtual network, such as a VPN that applies to the
4842 * application. The callbacks will continue to be called until either the application exits or
4843 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4844 *
4845 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4846 * number of outstanding requests to 100 per app (identified by their UID), shared with
4847 * all variants of this method, of {@link #requestNetwork} as well as
4848 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4849 * Requesting a network with this method will count toward this limit. If this limit is
4850 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4851 * make sure to unregister the callbacks with
4852 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4853 *
4854 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4855 * application's default network changes.
4856 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4857 * @throws RuntimeException if the app already has too many callbacks registered.
4858 */
4859 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4860 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4861 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004862 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004863 }
4864
4865 /**
4866 * Registers to receive notifications about changes in the default network for the specified
4867 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4868 * UID. The callbacks will continue to be called until either the application exits or
4869 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4870 *
4871 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4872 * number of outstanding requests to 100 per app (identified by their UID), shared with
4873 * all variants of this method, of {@link #requestNetwork} as well as
4874 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4875 * Requesting a network with this method will count toward this limit. If this limit is
4876 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4877 * make sure to unregister the callbacks with
4878 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4879 *
4880 * @param uid the UID for which to track default network changes.
4881 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4882 * UID's default network changes.
4883 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4884 * @throws RuntimeException if the app already has too many callbacks registered.
4885 * @hide
4886 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004887 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004888 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4889 @RequiresPermission(anyOf = {
4890 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4891 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004892 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004893 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004894 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004895 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004896 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4897 }
4898
4899 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004900 * Registers to receive notifications about changes in the system default network. The callbacks
4901 * will continue to be called until either the application exits or
4902 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4903 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004904 * This method should not be used to determine networking state seen by applications, because in
4905 * many cases, most or even all application traffic may not use the default network directly,
4906 * and traffic from different applications may go on different networks by default. As an
4907 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4908 * and not onto the system default network. Applications or system components desiring to do
4909 * determine network state as seen by applications should use other methods such as
4910 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4911 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004912 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4913 * number of outstanding requests to 100 per app (identified by their UID), shared with
4914 * all variants of this method, of {@link #requestNetwork} as well as
4915 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4916 * Requesting a network with this method will count toward this limit. If this limit is
4917 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4918 * make sure to unregister the callbacks with
4919 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4920 *
4921 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4922 * system default network changes.
4923 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4924 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004925 *
4926 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004927 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004928 @SystemApi(client = MODULE_LIBRARIES)
4929 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4930 @RequiresPermission(anyOf = {
4931 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004932 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00004933 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004934 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004935 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004936 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004937 CallbackHandler cbHandler = new CallbackHandler(handler);
4938 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004939 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004940 }
4941
4942 /**
junyulaibd123062021-03-15 11:48:48 +08004943 * Registers to receive notifications about the best matching network which satisfy the given
4944 * {@link NetworkRequest}. The callbacks will continue to be called until
4945 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4946 * called.
4947 *
4948 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4949 * number of outstanding requests to 100 per app (identified by their UID), shared with
4950 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4951 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4952 * Requesting a network with this method will count toward this limit. If this limit is
4953 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4954 * make sure to unregister the callbacks with
4955 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4956 *
4957 *
4958 * @param request {@link NetworkRequest} describing this request.
4959 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4960 * networks change state.
4961 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4962 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004963 */
junyulai5a5c99b2021-03-05 15:51:17 +08004964 @SuppressLint("ExecutorRegistration")
4965 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4966 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4967 final NetworkCapabilities nc = request.networkCapabilities;
4968 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004969 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004970 }
4971
4972 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004973 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4974 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4975 * network connection for updated bandwidth information. The caller will be notified via
4976 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4977 * method assumes that the caller has previously called
4978 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4979 * changes.
4980 *
4981 * @param network {@link Network} specifying which network you're interested.
4982 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4983 */
4984 public boolean requestBandwidthUpdate(@NonNull Network network) {
4985 try {
4986 return mService.requestBandwidthUpdate(network);
4987 } catch (RemoteException e) {
4988 throw e.rethrowFromSystemServer();
4989 }
4990 }
4991
4992 /**
4993 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4994 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4995 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09004996 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
4997 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004998 *
4999 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
5000 * triggering it as soon as this call returns.
5001 *
5002 * @param networkCallback The {@link NetworkCallback} used when making the request.
5003 */
5004 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
5005 printStackTrace();
5006 checkCallbackNotNull(networkCallback);
5007 final List<NetworkRequest> reqs = new ArrayList<>();
5008 // Find all requests associated to this callback and stop callback triggers immediately.
5009 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
5010 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00005011 if (networkCallback.networkRequest == null) {
5012 throw new IllegalArgumentException("NetworkCallback was not registered");
5013 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005014 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
5015 Log.d(TAG, "NetworkCallback was already unregistered");
5016 return;
5017 }
5018 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
5019 if (e.getValue() == networkCallback) {
5020 reqs.add(e.getKey());
5021 }
5022 }
5023 // TODO: throw exception if callback was registered more than once (http://b/20701525).
5024 for (NetworkRequest r : reqs) {
5025 try {
5026 mService.releaseNetworkRequest(r);
5027 } catch (RemoteException e) {
5028 throw e.rethrowFromSystemServer();
5029 }
5030 // Only remove mapping if rpc was successful.
5031 sCallbacks.remove(r);
5032 }
5033 networkCallback.networkRequest = ALREADY_UNREGISTERED;
5034 }
5035 }
5036
5037 /**
5038 * Unregisters a callback previously registered via
5039 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5040 *
5041 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
5042 * PendingIntent passed to
5043 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5044 * Cannot be null.
5045 */
5046 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
5047 releaseNetworkRequest(operation);
5048 }
5049
5050 /**
5051 * Informs the system whether it should switch to {@code network} regardless of whether it is
5052 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
5053 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
5054 * the system default network regardless of any other network that's currently connected. If
5055 * {@code always} is true, then the choice is remembered, so that the next time the user
5056 * connects to this network, the system will switch to it.
5057 *
5058 * @param network The network to accept.
5059 * @param accept Whether to accept the network even if unvalidated.
5060 * @param always Whether to remember this choice in the future.
5061 *
5062 * @hide
5063 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005064 @SystemApi(client = MODULE_LIBRARIES)
5065 @RequiresPermission(anyOf = {
5066 android.Manifest.permission.NETWORK_SETTINGS,
5067 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5068 android.Manifest.permission.NETWORK_STACK,
5069 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5070 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005071 try {
5072 mService.setAcceptUnvalidated(network, accept, always);
5073 } catch (RemoteException e) {
5074 throw e.rethrowFromSystemServer();
5075 }
5076 }
5077
5078 /**
5079 * Informs the system whether it should consider the network as validated even if it only has
5080 * partial connectivity. If {@code accept} is true, then the network will be considered as
5081 * validated even if connectivity is only partial. If {@code always} is true, then the choice
5082 * is remembered, so that the next time the user connects to this network, the system will
5083 * switch to it.
5084 *
5085 * @param network The network to accept.
5086 * @param accept Whether to consider the network as validated even if it has partial
5087 * connectivity.
5088 * @param always Whether to remember this choice in the future.
5089 *
5090 * @hide
5091 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005092 @SystemApi(client = MODULE_LIBRARIES)
5093 @RequiresPermission(anyOf = {
5094 android.Manifest.permission.NETWORK_SETTINGS,
5095 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5096 android.Manifest.permission.NETWORK_STACK,
5097 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5098 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5099 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005100 try {
5101 mService.setAcceptPartialConnectivity(network, accept, always);
5102 } catch (RemoteException e) {
5103 throw e.rethrowFromSystemServer();
5104 }
5105 }
5106
5107 /**
5108 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5109 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5110 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5111 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5112 *
5113 * @param network The network to accept.
5114 *
5115 * @hide
5116 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005117 @SystemApi(client = MODULE_LIBRARIES)
5118 @RequiresPermission(anyOf = {
5119 android.Manifest.permission.NETWORK_SETTINGS,
5120 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5121 android.Manifest.permission.NETWORK_STACK,
5122 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5123 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005124 try {
5125 mService.setAvoidUnvalidated(network);
5126 } catch (RemoteException e) {
5127 throw e.rethrowFromSystemServer();
5128 }
5129 }
5130
5131 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005132 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005133 *
5134 * @param timeMs The expired current time. The value should be set within a limited time from
5135 * now.
5136 *
5137 * @hide
5138 */
5139 public void setTestAllowBadWifiUntil(long timeMs) {
5140 try {
5141 mService.setTestAllowBadWifiUntil(timeMs);
5142 } catch (RemoteException e) {
5143 throw e.rethrowFromSystemServer();
5144 }
5145 }
5146
5147 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005148 * Requests that the system open the captive portal app on the specified network.
5149 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005150 * <p>This is to be used on networks where a captive portal was detected, as per
5151 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5152 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005153 * @param network The network to log into.
5154 *
5155 * @hide
5156 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005157 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5158 @RequiresPermission(anyOf = {
5159 android.Manifest.permission.NETWORK_SETTINGS,
5160 android.Manifest.permission.NETWORK_STACK,
5161 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5162 })
5163 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005164 try {
5165 mService.startCaptivePortalApp(network);
5166 } catch (RemoteException e) {
5167 throw e.rethrowFromSystemServer();
5168 }
5169 }
5170
5171 /**
5172 * Requests that the system open the captive portal app with the specified extras.
5173 *
5174 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5175 * corresponding permission.
5176 * @param network Network on which the captive portal was detected.
5177 * @param appExtras Extras to include in the app start intent.
5178 * @hide
5179 */
5180 @SystemApi
5181 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5182 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5183 try {
5184 mService.startCaptivePortalAppInternal(network, appExtras);
5185 } catch (RemoteException e) {
5186 throw e.rethrowFromSystemServer();
5187 }
5188 }
5189
5190 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005191 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005192 * @hide
5193 */
5194 @SystemApi
5195 @RequiresPermission(anyOf = {
5196 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5197 android.Manifest.permission.NETWORK_STACK})
5198 public boolean shouldAvoidBadWifi() {
5199 try {
5200 return mService.shouldAvoidBadWifi();
5201 } catch (RemoteException e) {
5202 throw e.rethrowFromSystemServer();
5203 }
5204 }
5205
5206 /**
5207 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5208 * time-sensitive user-facing operations when the system default network is temporarily
5209 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5210 * this method), and the operation should be infrequent to ensure that data usage is limited.
5211 *
5212 * An example of such an operation might be a time-sensitive foreground activity, such as a
5213 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5214 */
5215 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5216
5217 /**
5218 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5219 * a backup channel for traffic that is primarily going over another network.
5220 *
5221 * An example might be maintaining backup connections to peers or servers for the purpose of
5222 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5223 * on backup paths should be negligible compared to the traffic on the main path.
5224 */
5225 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5226
5227 /**
5228 * It is acceptable to use metered data to improve network latency and performance.
5229 */
5230 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5231
5232 /**
5233 * Return value to use for unmetered networks. On such networks we currently set all the flags
5234 * to true.
5235 * @hide
5236 */
5237 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5238 MULTIPATH_PREFERENCE_HANDOVER |
5239 MULTIPATH_PREFERENCE_RELIABILITY |
5240 MULTIPATH_PREFERENCE_PERFORMANCE;
5241
Aaron Huangcff22942021-05-27 16:31:26 +08005242 /** @hide */
5243 @Retention(RetentionPolicy.SOURCE)
5244 @IntDef(flag = true, value = {
5245 MULTIPATH_PREFERENCE_HANDOVER,
5246 MULTIPATH_PREFERENCE_RELIABILITY,
5247 MULTIPATH_PREFERENCE_PERFORMANCE,
5248 })
5249 public @interface MultipathPreference {
5250 }
5251
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005252 /**
5253 * Provides a hint to the calling application on whether it is desirable to use the
5254 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5255 * for multipath data transfer on this network when it is not the system default network.
5256 * Applications desiring to use multipath network protocols should call this method before
5257 * each such operation.
5258 *
5259 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005260 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005261 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005262 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005263 */
5264 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5265 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5266 try {
5267 return mService.getMultipathPreference(network);
5268 } catch (RemoteException e) {
5269 throw e.rethrowFromSystemServer();
5270 }
5271 }
5272
5273 /**
5274 * Resets all connectivity manager settings back to factory defaults.
5275 * @hide
5276 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005277 @SystemApi(client = MODULE_LIBRARIES)
5278 @RequiresPermission(anyOf = {
5279 android.Manifest.permission.NETWORK_SETTINGS,
5280 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005281 public void factoryReset() {
5282 try {
5283 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005284 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005285 } catch (RemoteException e) {
5286 throw e.rethrowFromSystemServer();
5287 }
5288 }
5289
5290 /**
5291 * Binds the current process to {@code network}. All Sockets created in the future
5292 * (and not explicitly bound via a bound SocketFactory from
5293 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5294 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5295 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5296 * work and all host name resolutions will fail. This is by design so an application doesn't
5297 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5298 * To clear binding pass {@code null} for {@code network}. Using individually bound
5299 * Sockets created by Network.getSocketFactory().createSocket() and
5300 * performing network-specific host name resolutions via
5301 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5302 * {@code bindProcessToNetwork}.
5303 *
5304 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5305 * the current binding.
5306 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5307 */
5308 public boolean bindProcessToNetwork(@Nullable Network network) {
5309 // Forcing callers to call through non-static function ensures ConnectivityManager
5310 // instantiated.
5311 return setProcessDefaultNetwork(network);
5312 }
5313
5314 /**
5315 * Binds the current process to {@code network}. All Sockets created in the future
5316 * (and not explicitly bound via a bound SocketFactory from
5317 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5318 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5319 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5320 * work and all host name resolutions will fail. This is by design so an application doesn't
5321 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5322 * To clear binding pass {@code null} for {@code network}. Using individually bound
5323 * Sockets created by Network.getSocketFactory().createSocket() and
5324 * performing network-specific host name resolutions via
5325 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5326 * {@code setProcessDefaultNetwork}.
5327 *
5328 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5329 * the current binding.
5330 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5331 * @deprecated This function can throw {@link IllegalStateException}. Use
5332 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5333 * is a direct replacement.
5334 */
5335 @Deprecated
5336 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5337 int netId = (network == null) ? NETID_UNSET : network.netId;
5338 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5339
5340 if (netId != NETID_UNSET) {
5341 netId = network.getNetIdForResolv();
5342 }
5343
5344 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5345 return false;
5346 }
5347
5348 if (!isSameNetId) {
5349 // Set HTTP proxy system properties to match network.
5350 // TODO: Deprecate this static method and replace it with a non-static version.
5351 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005352 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005353 } catch (SecurityException e) {
5354 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5355 Log.e(TAG, "Can't set proxy properties", e);
5356 }
5357 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005358 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005359 // Must flush socket pool as idle sockets will be bound to previous network and may
5360 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005361 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005362 }
5363
5364 return true;
5365 }
5366
5367 /**
5368 * Returns the {@link Network} currently bound to this process via
5369 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5370 *
5371 * @return {@code Network} to which this process is bound, or {@code null}.
5372 */
5373 @Nullable
5374 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005375 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005376 // instantiated.
5377 return getProcessDefaultNetwork();
5378 }
5379
5380 /**
5381 * Returns the {@link Network} currently bound to this process via
5382 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5383 *
5384 * @return {@code Network} to which this process is bound, or {@code null}.
5385 * @deprecated Using this function can lead to other functions throwing
5386 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5387 * {@code getBoundNetworkForProcess} is a direct replacement.
5388 */
5389 @Deprecated
5390 @Nullable
5391 public static Network getProcessDefaultNetwork() {
5392 int netId = NetworkUtils.getBoundNetworkForProcess();
5393 if (netId == NETID_UNSET) return null;
5394 return new Network(netId);
5395 }
5396
5397 private void unsupportedStartingFrom(int version) {
5398 if (Process.myUid() == Process.SYSTEM_UID) {
5399 // The getApplicationInfo() call we make below is not supported in system context. Let
5400 // the call through here, and rely on the fact that ConnectivityService will refuse to
5401 // allow the system to use these APIs anyway.
5402 return;
5403 }
5404
5405 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5406 throw new UnsupportedOperationException(
5407 "This method is not supported in target SDK version " + version + " and above");
5408 }
5409 }
5410
5411 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5412 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5413 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5414 // remove these exemptions. Note that this check is not secure, and apps can still access these
5415 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5416 // so is unsupported and may break in the future. http://b/22728205
5417 private void checkLegacyRoutingApiAccess() {
5418 unsupportedStartingFrom(VERSION_CODES.M);
5419 }
5420
5421 /**
5422 * Binds host resolutions performed by this process to {@code network}.
5423 * {@link #bindProcessToNetwork} takes precedence over this setting.
5424 *
5425 * @param network The {@link Network} to bind host resolutions from the current process to, or
5426 * {@code null} to clear the current binding.
5427 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5428 * @hide
5429 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5430 */
5431 @Deprecated
5432 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5433 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5434 return NetworkUtils.bindProcessToNetworkForHostResolution(
5435 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5436 }
5437
5438 /**
5439 * Device is not restricting metered network activity while application is running on
5440 * background.
5441 */
5442 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5443
5444 /**
5445 * Device is restricting metered network activity while application is running on background,
5446 * but application is allowed to bypass it.
5447 * <p>
5448 * In this state, application should take action to mitigate metered network access.
5449 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5450 */
5451 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5452
5453 /**
5454 * Device is restricting metered network activity while application is running on background.
5455 * <p>
5456 * In this state, application should not try to use the network while running on background,
5457 * because it would be denied.
5458 */
5459 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5460
5461 /**
5462 * A change in the background metered network activity restriction has occurred.
5463 * <p>
5464 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5465 * applies to them.
5466 * <p>
5467 * This is only sent to registered receivers, not manifest receivers.
5468 */
5469 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5470 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5471 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5472
Aaron Huangcff22942021-05-27 16:31:26 +08005473 /** @hide */
5474 @Retention(RetentionPolicy.SOURCE)
5475 @IntDef(flag = false, value = {
5476 RESTRICT_BACKGROUND_STATUS_DISABLED,
5477 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5478 RESTRICT_BACKGROUND_STATUS_ENABLED,
5479 })
5480 public @interface RestrictBackgroundStatus {
5481 }
5482
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005483 /**
5484 * Determines if the calling application is subject to metered network restrictions while
5485 * running on background.
5486 *
5487 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5488 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5489 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5490 */
5491 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5492 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005493 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005494 } catch (RemoteException e) {
5495 throw e.rethrowFromSystemServer();
5496 }
5497 }
5498
5499 /**
5500 * The network watchlist is a list of domains and IP addresses that are associated with
5501 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5502 * currently used by the system for validation purposes.
5503 *
5504 * @return Hash of network watchlist config file. Null if config does not exist.
5505 */
5506 @Nullable
5507 public byte[] getNetworkWatchlistConfigHash() {
5508 try {
5509 return mService.getNetworkWatchlistConfigHash();
5510 } catch (RemoteException e) {
5511 Log.e(TAG, "Unable to get watchlist config hash");
5512 throw e.rethrowFromSystemServer();
5513 }
5514 }
5515
5516 /**
5517 * Returns the {@code uid} of the owner of a network connection.
5518 *
5519 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5520 * IPPROTO_UDP} currently supported.
5521 * @param local The local {@link InetSocketAddress} of a connection.
5522 * @param remote The remote {@link InetSocketAddress} of a connection.
5523 * @return {@code uid} if the connection is found and the app has permission to observe it
5524 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5525 * android.os.Process#INVALID_UID} if the connection is not found.
Sherri Lin443b7182023-02-08 04:49:29 +01005526 * @throws SecurityException if the caller is not the active VpnService for the current
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005527 * user.
Sherri Lin443b7182023-02-08 04:49:29 +01005528 * @throws IllegalArgumentException if an unsupported protocol is requested.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005529 */
5530 public int getConnectionOwnerUid(
5531 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5532 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5533 try {
5534 return mService.getConnectionOwnerUid(connectionInfo);
5535 } catch (RemoteException e) {
5536 throw e.rethrowFromSystemServer();
5537 }
5538 }
5539
5540 private void printStackTrace() {
5541 if (DEBUG) {
5542 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5543 final StringBuffer sb = new StringBuffer();
5544 for (int i = 3; i < callStack.length; i++) {
5545 final String stackTrace = callStack[i].toString();
5546 if (stackTrace == null || stackTrace.contains("android.os")) {
5547 break;
5548 }
5549 sb.append(" [").append(stackTrace).append("]");
5550 }
5551 Log.d(TAG, "StackLog:" + sb.toString());
5552 }
5553 }
5554
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005555 /** @hide */
5556 public TestNetworkManager startOrGetTestNetworkManager() {
5557 final IBinder tnBinder;
5558 try {
5559 tnBinder = mService.startOrGetTestNetworkService();
5560 } catch (RemoteException e) {
5561 throw e.rethrowFromSystemServer();
5562 }
5563
5564 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5565 }
5566
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005567 /** @hide */
5568 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5569 return new ConnectivityDiagnosticsManager(mContext, mService);
5570 }
5571
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005572 /**
5573 * Simulates a Data Stall for the specified Network.
5574 *
5575 * <p>This method should only be used for tests.
5576 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005577 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5578 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005579 *
5580 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005581 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5582 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5583 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005584 * @param network The Network for which a Data Stall is being simluated.
5585 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5586 * @throws SecurityException if the caller is not the owner of the given network.
5587 * @hide
5588 */
5589 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5590 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5591 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005592 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005593 @NonNull Network network, @NonNull PersistableBundle extras) {
5594 try {
5595 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5596 } catch (RemoteException e) {
5597 e.rethrowFromSystemServer();
5598 }
5599 }
5600
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005601 @NonNull
5602 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5603
5604 /**
5605 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5606 * receive available QoS events related to the {@link Network} and local ip + port
5607 * specified within socketInfo.
5608 * <p/>
5609 * The same {@link QosCallback} must be unregistered before being registered a second time,
5610 * otherwise {@link QosCallbackRegistrationException} is thrown.
5611 * <p/>
5612 * This API does not, in itself, require any permission if called with a network that is not
5613 * restricted. However, the underlying implementation currently only supports the IMS network,
5614 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5615 * useful, because they'd never be called back on networks that they would have access to.
5616 *
5617 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5618 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5619 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5620 * @throws RuntimeException if the app already has too many callbacks registered.
5621 *
5622 * Exceptions after the time of registration is passed through
5623 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5624 *
5625 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005626 * @param executor The executor on which the callback will be invoked. The provided
5627 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005628 * callbacks cannot be guaranteed.onQosCallbackRegistered
5629 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005630 *
5631 * @hide
5632 */
5633 @SystemApi
5634 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005635 @CallbackExecutor @NonNull final Executor executor,
5636 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005637 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005638 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005639 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005640
5641 try {
5642 synchronized (mQosCallbackConnections) {
5643 if (getQosCallbackConnection(callback) == null) {
5644 final QosCallbackConnection connection =
5645 new QosCallbackConnection(this, callback, executor);
5646 mQosCallbackConnections.add(connection);
5647 mService.registerQosSocketCallback(socketInfo, connection);
5648 } else {
5649 Log.e(TAG, "registerQosCallback: Callback already registered");
5650 throw new QosCallbackRegistrationException();
5651 }
5652 }
5653 } catch (final RemoteException e) {
5654 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5655
5656 // The same unregister method method is called for consistency even though nothing
5657 // will be sent to the ConnectivityService since the callback was never successfully
5658 // registered.
5659 unregisterQosCallback(callback);
5660 e.rethrowFromSystemServer();
5661 } catch (final ServiceSpecificException e) {
5662 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5663 unregisterQosCallback(callback);
5664 throw convertServiceException(e);
5665 }
5666 }
5667
5668 /**
5669 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5670 * events once unregistered and can be registered a second time.
5671 * <p/>
5672 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5673 *
5674 * @param callback the callback being unregistered
5675 *
5676 * @hide
5677 */
5678 @SystemApi
5679 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5680 Objects.requireNonNull(callback, "The callback must be non-null");
5681 try {
5682 synchronized (mQosCallbackConnections) {
5683 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5684 if (connection != null) {
5685 connection.stopReceivingMessages();
5686 mService.unregisterQosCallback(connection);
5687 mQosCallbackConnections.remove(connection);
5688 } else {
5689 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5690 }
5691 }
5692 } catch (final RemoteException e) {
5693 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5694 e.rethrowFromSystemServer();
5695 }
5696 }
5697
5698 /**
5699 * Gets the connection related to the callback.
5700 *
5701 * @param callback the callback to look up
5702 * @return the related connection
5703 */
5704 @Nullable
5705 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5706 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5707 // Checking by reference here is intentional
5708 if (connection.getCallback() == callback) {
5709 return connection;
5710 }
5711 }
5712 return null;
5713 }
5714
5715 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005716 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005717 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5718 * be used to request that the system provide a network without causing the network to be
5719 * in the foreground.
5720 *
5721 * <p>This method will attempt to find the best network that matches the passed
5722 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5723 * criteria. The platform will evaluate which network is the best at its own discretion.
5724 * Throughput, latency, cost per byte, policy, user preference and other considerations
5725 * may be factored in the decision of what is considered the best network.
5726 *
5727 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5728 * matching this request, while always attempting to match the request to a better network if
5729 * possible. If a better match is found, the platform will switch this request to the now-best
5730 * network and inform the app of the newly best network by invoking
5731 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5732 * will not try to maintain any other network than the best one currently matching the request:
5733 * a network not matching any network request may be disconnected at any time.
5734 *
5735 * <p>For example, an application could use this method to obtain a connected cellular network
5736 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5737 * radio to consume additional power. Or, an application could inform the system that it wants
5738 * a network supporting sending MMSes and have the system let it know about the currently best
5739 * MMS-supporting network through the provided {@link NetworkCallback}.
5740 *
5741 * <p>The status of the request can be followed by listening to the various callbacks described
5742 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5743 * used to direct traffic to the network (although accessing some networks may be subject to
5744 * holding specific permissions). Callers will learn about the specific characteristics of the
5745 * network through
5746 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5747 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5748 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5749 * matching the request at any given time; therefore when a better network matching the request
5750 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5751 * with the new network after which no further updates are given about the previously-best
5752 * network, unless it becomes the best again at some later time. All callbacks are invoked
5753 * in order on the same thread, which by default is a thread created by the framework running
5754 * in the app.
5755 *
5756 * <p>This{@link NetworkRequest} will live until released via
5757 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5758 * which point the system may let go of the network at any time.
5759 *
5760 * <p>It is presently unsupported to request a network with mutable
5761 * {@link NetworkCapabilities} such as
5762 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5763 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5764 * as these {@code NetworkCapabilities} represent states that a particular
5765 * network may never attain, and whether a network will attain these states
5766 * is unknown prior to bringing up the network so the framework does not
5767 * know how to go about satisfying a request with these capabilities.
5768 *
5769 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5770 * number of outstanding requests to 100 per app (identified by their UID), shared with
5771 * all variants of this method, of {@link #registerNetworkCallback} as well as
5772 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5773 * Requesting a network with this method will count toward this limit. If this limit is
5774 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5775 * make sure to unregister the callbacks with
5776 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5777 *
5778 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005779 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5780 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005781 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5782 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005783 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5784 * @throws SecurityException if missing the appropriate permissions.
5785 * @throws RuntimeException if the app already has too many callbacks registered.
5786 *
5787 * @hide
5788 */
5789 @SystemApi(client = MODULE_LIBRARIES)
5790 @SuppressLint("ExecutorRegistration")
5791 @RequiresPermission(anyOf = {
5792 android.Manifest.permission.NETWORK_SETTINGS,
5793 android.Manifest.permission.NETWORK_STACK,
5794 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5795 })
5796 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005797 @NonNull NetworkCallback networkCallback,
5798 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005799 final NetworkCapabilities nc = request.networkCapabilities;
5800 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005801 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005802 }
James Mattis12aeab82021-01-10 14:24:24 -08005803
5804 /**
James Mattis12aeab82021-01-10 14:24:24 -08005805 * Used by automotive devices to set the network preferences used to direct traffic at an
5806 * application level as per the given OemNetworkPreferences. An example use-case would be an
5807 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5808 * vehicle via a particular network.
5809 *
5810 * Calling this will overwrite the existing preference.
5811 *
5812 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5813 * @param executor the executor on which listener will be invoked.
5814 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5815 * communicate completion of setOemNetworkPreference(). This will only be
5816 * called once upon successful completion of setOemNetworkPreference().
5817 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5818 * @throws SecurityException if missing the appropriate permissions.
5819 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005820 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005821 */
James Mattis6e2d7022021-01-26 16:23:52 -08005822 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005823 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005824 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005825 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005826 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005827 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5828 if (null != listener) {
5829 Objects.requireNonNull(executor, "Executor must be non-null");
5830 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005831 final IOnCompleteListener listenerInternal = listener == null ? null :
5832 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005833 @Override
5834 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005835 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005836 }
5837 };
5838
5839 try {
5840 mService.setOemNetworkPreference(preference, listenerInternal);
5841 } catch (RemoteException e) {
5842 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5843 throw e.rethrowFromSystemServer();
5844 }
5845 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005846
Chalard Jeanad565e22021-02-25 17:23:40 +09005847 /**
5848 * Request that a user profile is put by default on a network matching a given preference.
5849 *
5850 * See the documentation for the individual preferences for a description of the supported
5851 * behaviors.
5852 *
5853 * @param profile the profile concerned.
5854 * @param preference the preference for this profile.
5855 * @param executor an executor to execute the listener on. Optional if listener is null.
5856 * @param listener an optional listener to listen for completion of the operation.
5857 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5858 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005859 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5860 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005861 * @hide
5862 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005863 // This function is for establishing per-profile default networking and can only be called by
5864 // the device policy manager, running as the system server. It would make no sense to call it
5865 // on a context for a user because it does not establish a setting on behalf of a user, rather
5866 // it establishes a setting for a user on behalf of the DPM.
5867 @SuppressLint({"UserHandle"})
5868 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005869 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005870 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005871 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005872 @ProfileNetworkPreferencePolicy final int preference,
5873 @Nullable @CallbackExecutor final Executor executor,
5874 @Nullable final Runnable listener) {
5875
5876 ProfileNetworkPreference.Builder preferenceBuilder =
5877 new ProfileNetworkPreference.Builder();
5878 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005879 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5880 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5881 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005882 setProfileNetworkPreferences(profile,
5883 List.of(preferenceBuilder.build()), executor, listener);
5884 }
5885
5886 /**
5887 * Set a list of default network selection policies for a user profile.
5888 *
5889 * Calling this API with a user handle defines the entire policy for that user handle.
5890 * It will overwrite any setting previously set for the same user profile,
5891 * and not affect previously set settings for other handles.
5892 *
5893 * Call this API with an empty list to remove settings for this user profile.
5894 *
5895 * See {@link ProfileNetworkPreference} for more details on each preference
5896 * parameter.
5897 *
5898 * @param profile the user profile for which the preference is being set.
5899 * @param profileNetworkPreferences the list of profile network preferences for the
5900 * provided profile.
5901 * @param executor an executor to execute the listener on. Optional if listener is null.
5902 * @param listener an optional listener to listen for completion of the operation.
5903 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5904 * @throws SecurityException if missing the appropriate permissions.
5905 * @hide
5906 */
5907 @SystemApi(client = MODULE_LIBRARIES)
5908 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5909 public void setProfileNetworkPreferences(
5910 @NonNull final UserHandle profile,
5911 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005912 @Nullable @CallbackExecutor final Executor executor,
5913 @Nullable final Runnable listener) {
5914 if (null != listener) {
5915 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5916 }
5917 final IOnCompleteListener proxy;
5918 if (null == listener) {
5919 proxy = null;
5920 } else {
5921 proxy = new IOnCompleteListener.Stub() {
5922 @Override
5923 public void onComplete() {
5924 executor.execute(listener::run);
5925 }
5926 };
5927 }
5928 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005929 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005930 } catch (RemoteException e) {
5931 throw e.rethrowFromSystemServer();
5932 }
5933 }
5934
lucaslin5cdbcfb2021-03-12 00:46:33 +08005935 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005936 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005937 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005938 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005939
5940 /**
5941 * Get the network ID range reserved for IPSec tunnel interfaces.
5942 *
5943 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5944 * @hide
5945 */
5946 @SystemApi(client = MODULE_LIBRARIES)
5947 @NonNull
5948 public static Range<Integer> getIpSecNetIdRange() {
5949 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5950 }
markchien738ad912021-12-09 18:15:45 +08005951
5952 /**
Junyu Laidf210362023-10-24 02:47:50 +00005953 * Sets data saver switch.
5954 *
5955 * @param enable True if enable.
5956 * @throws IllegalStateException if failed.
5957 * @hide
5958 */
5959 @FlaggedApi(Flags.SET_DATA_SAVER_VIA_CM)
5960 @SystemApi(client = MODULE_LIBRARIES)
5961 @RequiresPermission(anyOf = {
5962 android.Manifest.permission.NETWORK_SETTINGS,
5963 android.Manifest.permission.NETWORK_STACK,
5964 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5965 })
5966 public void setDataSaverEnabled(final boolean enable) {
5967 try {
5968 mService.setDataSaverEnabled(enable);
5969 } catch (RemoteException e) {
5970 throw e.rethrowFromSystemServer();
5971 }
5972 }
5973
5974 /**
markchiene46042b2022-03-02 18:07:35 +08005975 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5976 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005977 *
5978 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005979 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005980 * @hide
5981 */
5982 @SystemApi(client = MODULE_LIBRARIES)
5983 @RequiresPermission(anyOf = {
5984 android.Manifest.permission.NETWORK_SETTINGS,
5985 android.Manifest.permission.NETWORK_STACK,
5986 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5987 })
markchiene46042b2022-03-02 18:07:35 +08005988 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08005989 try {
markchiene46042b2022-03-02 18:07:35 +08005990 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08005991 } catch (RemoteException e) {
5992 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005993 }
5994 }
5995
5996 /**
markchiene46042b2022-03-02 18:07:35 +08005997 * Removes the specified UID from the list of UIDs that are allowed to use background data on
5998 * metered networks when background data is restricted. The deny list takes precedence over
5999 * the allow list.
6000 *
6001 * @param uid uid of target app
6002 * @throws IllegalStateException if updating allow list failed.
6003 * @hide
6004 */
6005 @SystemApi(client = MODULE_LIBRARIES)
6006 @RequiresPermission(anyOf = {
6007 android.Manifest.permission.NETWORK_SETTINGS,
6008 android.Manifest.permission.NETWORK_STACK,
6009 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6010 })
6011 public void removeUidFromMeteredNetworkAllowList(final int uid) {
6012 try {
6013 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
6014 } catch (RemoteException e) {
6015 throw e.rethrowFromSystemServer();
6016 }
6017 }
6018
6019 /**
6020 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
6021 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08006022 *
6023 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006024 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08006025 * @hide
6026 */
6027 @SystemApi(client = MODULE_LIBRARIES)
6028 @RequiresPermission(anyOf = {
6029 android.Manifest.permission.NETWORK_SETTINGS,
6030 android.Manifest.permission.NETWORK_STACK,
6031 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6032 })
markchiene46042b2022-03-02 18:07:35 +08006033 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006034 try {
markchiene46042b2022-03-02 18:07:35 +08006035 mService.updateMeteredNetworkDenyList(uid, true /* add */);
6036 } catch (RemoteException e) {
6037 throw e.rethrowFromSystemServer();
6038 }
6039 }
6040
6041 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09006042 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08006043 * networks if background data is not restricted. The deny list takes precedence over the
6044 * allow list.
6045 *
6046 * @param uid uid of target app
6047 * @throws IllegalStateException if updating deny list failed.
6048 * @hide
6049 */
6050 @SystemApi(client = MODULE_LIBRARIES)
6051 @RequiresPermission(anyOf = {
6052 android.Manifest.permission.NETWORK_SETTINGS,
6053 android.Manifest.permission.NETWORK_STACK,
6054 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6055 })
6056 public void removeUidFromMeteredNetworkDenyList(final int uid) {
6057 try {
6058 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08006059 } catch (RemoteException e) {
6060 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08006061 }
6062 }
6063
6064 /**
6065 * Sets a firewall rule for the specified UID on the specified chain.
6066 *
6067 * @param chain target chain.
6068 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08006069 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08006070 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08006071 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08006072 * @hide
6073 */
6074 @SystemApi(client = MODULE_LIBRARIES)
6075 @RequiresPermission(anyOf = {
6076 android.Manifest.permission.NETWORK_SETTINGS,
6077 android.Manifest.permission.NETWORK_STACK,
6078 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6079 })
markchien3c04e662022-03-22 16:29:56 +08006080 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
6081 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08006082 try {
markchien3c04e662022-03-22 16:29:56 +08006083 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08006084 } catch (RemoteException e) {
6085 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006086 }
6087 }
markchien98a6f952022-01-13 23:43:53 +08006088
6089 /**
Motomu Utsumi900b8062023-01-19 16:16:49 +09006090 * Get firewall rule of specified firewall chain on specified uid.
6091 *
6092 * @param chain target chain.
6093 * @param uid target uid
6094 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
6095 * @throws UnsupportedOperationException if called on pre-T devices.
6096 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6097 * cause of the failure.
6098 * @hide
6099 */
6100 @RequiresPermission(anyOf = {
6101 android.Manifest.permission.NETWORK_SETTINGS,
6102 android.Manifest.permission.NETWORK_STACK,
6103 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6104 })
6105 public int getUidFirewallRule(@FirewallChain final int chain, final int uid) {
6106 try {
6107 return mService.getUidFirewallRule(chain, uid);
6108 } catch (RemoteException e) {
6109 throw e.rethrowFromSystemServer();
6110 }
6111 }
6112
6113 /**
markchien98a6f952022-01-13 23:43:53 +08006114 * Enables or disables the specified firewall chain.
6115 *
6116 * @param chain target chain.
6117 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00006118 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08006119 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08006120 * @hide
6121 */
6122 @SystemApi(client = MODULE_LIBRARIES)
6123 @RequiresPermission(anyOf = {
6124 android.Manifest.permission.NETWORK_SETTINGS,
6125 android.Manifest.permission.NETWORK_STACK,
6126 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6127 })
6128 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
6129 try {
6130 mService.setFirewallChainEnabled(chain, enable);
6131 } catch (RemoteException e) {
6132 throw e.rethrowFromSystemServer();
6133 }
6134 }
markchien00a0bed2022-01-13 23:46:13 +08006135
6136 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00006137 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006138 *
6139 * @param chain target chain.
6140 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6141 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006142 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6143 * cause of the failure.
6144 * @hide
6145 */
6146 @RequiresPermission(anyOf = {
6147 android.Manifest.permission.NETWORK_SETTINGS,
6148 android.Manifest.permission.NETWORK_STACK,
6149 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6150 })
6151 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6152 try {
6153 return mService.getFirewallChainEnabled(chain);
6154 } catch (RemoteException e) {
6155 throw e.rethrowFromSystemServer();
6156 }
6157 }
6158
6159 /**
markchien00a0bed2022-01-13 23:46:13 +08006160 * Replaces the contents of the specified UID-based firewall chain.
6161 *
6162 * @param chain target chain to replace.
6163 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006164 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006165 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6166 * @hide
6167 */
6168 @SystemApi(client = MODULE_LIBRARIES)
6169 @RequiresPermission(anyOf = {
6170 android.Manifest.permission.NETWORK_SETTINGS,
6171 android.Manifest.permission.NETWORK_STACK,
6172 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6173 })
6174 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6175 Objects.requireNonNull(uids);
6176 try {
6177 mService.replaceFirewallChain(chain, uids);
6178 } catch (RemoteException e) {
6179 throw e.rethrowFromSystemServer();
6180 }
6181 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006182
6183 /** @hide */
6184 public IBinder getCompanionDeviceManagerProxyService() {
6185 try {
6186 return mService.getCompanionDeviceManagerProxyService();
6187 } catch (RemoteException e) {
6188 throw e.rethrowFromSystemServer();
6189 }
6190 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006191}