blob: eb8f8c3db997bbdcd2a84cb20c3b643d92b53f92 [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;
Junyu Laic3dc5b62023-09-06 19:10:02 +080019import static android.content.pm.ApplicationInfo.FLAG_PERSISTENT;
20import static android.content.pm.ApplicationInfo.FLAG_SYSTEM;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080021import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090022import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
23import static android.net.NetworkRequest.Type.LISTEN;
junyulai7664f622021-03-12 20:05:08 +080024import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090025import static android.net.NetworkRequest.Type.REQUEST;
26import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colittia77d05e2021-01-29 20:14:04 +090027import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090028import static android.net.QosCallback.QosCallbackRegistrationException;
29
Junyu Laic3dc5b62023-09-06 19:10:02 +080030import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE;
31
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090032import android.annotation.CallbackExecutor;
Junyu Laidf210362023-10-24 02:47:50 +000033import android.annotation.FlaggedApi;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090034import android.annotation.IntDef;
35import android.annotation.NonNull;
36import android.annotation.Nullable;
Chalard Jean2fb66f12023-08-25 12:50:37 +090037import android.annotation.RequiresApi;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090038import android.annotation.RequiresPermission;
39import android.annotation.SdkConstant;
40import android.annotation.SdkConstant.SdkConstantType;
41import android.annotation.SuppressLint;
42import android.annotation.SystemApi;
43import android.annotation.SystemService;
Junyu Laic3dc5b62023-09-06 19:10:02 +080044import android.annotation.TargetApi;
45import android.app.Application;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090046import android.app.PendingIntent;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090047import android.app.admin.DevicePolicyManager;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090048import android.compat.annotation.UnsupportedAppUsage;
Junyu Laic3dc5b62023-09-06 19:10:02 +080049import android.content.BroadcastReceiver;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090050import android.content.ComponentName;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090051import android.content.Context;
52import android.content.Intent;
Junyu Laic3dc5b62023-09-06 19:10:02 +080053import android.content.IntentFilter;
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +090054import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090055import android.net.IpSecManager.UdpEncapsulationSocket;
56import android.net.SocketKeepalive.Callback;
57import android.net.TetheringManager.StartTetheringCallback;
58import android.net.TetheringManager.TetheringEventCallback;
59import android.net.TetheringManager.TetheringRequest;
60import android.os.Binder;
61import android.os.Build;
62import android.os.Build.VERSION_CODES;
63import android.os.Bundle;
64import android.os.Handler;
65import android.os.IBinder;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090066import android.os.Looper;
67import android.os.Message;
68import android.os.Messenger;
69import android.os.ParcelFileDescriptor;
70import android.os.PersistableBundle;
71import android.os.Process;
72import android.os.RemoteException;
73import android.os.ResultReceiver;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090074import android.os.ServiceSpecificException;
Chalard Jeanad565e22021-02-25 17:23:40 +090075import android.os.UserHandle;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090076import android.provider.Settings;
77import android.telephony.SubscriptionManager;
78import android.telephony.TelephonyManager;
79import android.util.ArrayMap;
80import android.util.Log;
81import android.util.Range;
82import android.util.SparseIntArray;
83
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090084import com.android.internal.annotations.GuardedBy;
Junyu Laic3dc5b62023-09-06 19:10:02 +080085import com.android.internal.annotations.VisibleForTesting;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090086
87import libcore.net.event.NetworkEventDispatcher;
88
89import java.io.IOException;
90import java.io.UncheckedIOException;
91import java.lang.annotation.Retention;
92import java.lang.annotation.RetentionPolicy;
93import java.net.DatagramSocket;
94import java.net.InetAddress;
95import java.net.InetSocketAddress;
96import java.net.Socket;
97import java.util.ArrayList;
98import java.util.Collection;
99import java.util.HashMap;
100import java.util.List;
101import java.util.Map;
102import java.util.Objects;
103import java.util.concurrent.Executor;
104import java.util.concurrent.ExecutorService;
105import java.util.concurrent.Executors;
106import java.util.concurrent.RejectedExecutionException;
Junyu Laic3dc5b62023-09-06 19:10:02 +0800107import java.util.concurrent.atomic.AtomicBoolean;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900108
109/**
110 * Class that answers queries about the state of network connectivity. It also
111 * notifies applications when network connectivity changes.
112 * <p>
113 * The primary responsibilities of this class are to:
114 * <ol>
115 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
116 * <li>Send broadcast intents when network connectivity changes</li>
117 * <li>Attempt to "fail over" to another network when connectivity to a network
118 * is lost</li>
119 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
120 * state of the available networks</li>
121 * <li>Provide an API that allows applications to request and select networks for their data
122 * traffic</li>
123 * </ol>
124 */
125@SystemService(Context.CONNECTIVITY_SERVICE)
126public class ConnectivityManager {
127 private static final String TAG = "ConnectivityManager";
128 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
129
Junyu Laidf210362023-10-24 02:47:50 +0000130 // TODO : remove this class when udc-mainline-prod is abandoned and android.net.flags.Flags is
131 // available here
132 /** @hide */
133 public static class Flags {
134 static final String SET_DATA_SAVER_VIA_CM =
135 "com.android.net.flags.set_data_saver_via_cm";
Junyu Laibb594802023-09-04 11:37:03 +0800136 static final String SUPPORT_IS_UID_NETWORKING_BLOCKED =
137 "com.android.net.flags.support_is_uid_networking_blocked";
Junyu Laidf210362023-10-24 02:47:50 +0000138 }
139
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900140 /**
141 * A change in network connectivity has occurred. A default connection has either
142 * been established or lost. The NetworkInfo for the affected network is
143 * sent as an extra; it should be consulted to see what kind of
144 * connectivity event occurred.
145 * <p/>
146 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
147 * broadcast if they declare the broadcast receiver in their manifest. Apps
148 * will still receive broadcasts if they register their
149 * {@link android.content.BroadcastReceiver} with
150 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
151 * and that context is still valid.
152 * <p/>
153 * If this is a connection that was the result of failing over from a
154 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
155 * set to true.
156 * <p/>
157 * For a loss of connectivity, if the connectivity manager is attempting
158 * to connect (or has already connected) to another network, the
159 * NetworkInfo for the new network is also passed as an extra. This lets
160 * any receivers of the broadcast know that they should not necessarily
161 * tell the user that no data traffic will be possible. Instead, the
162 * receiver should expect another broadcast soon, indicating either that
163 * the failover attempt succeeded (and so there is still overall data
164 * connectivity), or that the failover attempt failed, meaning that all
165 * connectivity has been lost.
166 * <p/>
167 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
168 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900169 * <p />
170 * Note that this broadcast is deprecated and generally tries to implement backwards
171 * compatibility with older versions of Android. As such, it may not reflect new
172 * capabilities of the system, like multiple networks being connected at the same
173 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900174 *
175 * @deprecated apps should use the more versatile {@link #requestNetwork},
176 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
177 * functions instead for faster and more detailed updates about the network
178 * changes they care about.
179 */
180 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
181 @Deprecated
182 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
183
184 /**
185 * The device has connected to a network that has presented a captive
186 * portal, which is blocking Internet connectivity. The user was presented
187 * with a notification that network sign in is required,
188 * and the user invoked the notification's action indicating they
189 * desire to sign in to the network. Apps handling this activity should
190 * facilitate signing in to the network. This action includes a
191 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
192 * the network presenting the captive portal; all communication with the
193 * captive portal must be done using this {@code Network} object.
194 * <p/>
195 * This activity includes a {@link CaptivePortal} extra named
196 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
197 * outcomes of the captive portal sign in to the system:
198 * <ul>
199 * <li> When the app handling this action believes the user has signed in to
200 * the network and the captive portal has been dismissed, the app should
201 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
202 * reevaluate the network. If reevaluation finds the network no longer
203 * subject to a captive portal, the network may become the default active
204 * data network.</li>
205 * <li> When the app handling this action believes the user explicitly wants
206 * to ignore the captive portal and the network, the app should call
207 * {@link CaptivePortal#ignoreNetwork}. </li>
208 * </ul>
209 */
210 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
211 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
212
213 /**
214 * The lookup key for a {@link NetworkInfo} object. Retrieve with
215 * {@link android.content.Intent#getParcelableExtra(String)}.
216 *
217 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
218 * can't accurately represent modern network characteristics.
219 * Please obtain information about networks from the {@link NetworkCapabilities}
220 * or {@link LinkProperties} objects instead.
221 */
222 @Deprecated
223 public static final String EXTRA_NETWORK_INFO = "networkInfo";
224
225 /**
226 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
227 *
228 * @see android.content.Intent#getIntExtra(String, int)
229 * @deprecated The network type is not rich enough to represent the characteristics
230 * of modern networks. Please use {@link NetworkCapabilities} instead,
231 * in particular the transports.
232 */
233 @Deprecated
234 public static final String EXTRA_NETWORK_TYPE = "networkType";
235
236 /**
237 * The lookup key for a boolean that indicates whether a connect event
238 * is for a network to which the connectivity manager was failing over
239 * following a disconnect on another network.
240 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
241 *
242 * @deprecated See {@link NetworkInfo}.
243 */
244 @Deprecated
245 public static final String EXTRA_IS_FAILOVER = "isFailover";
246 /**
247 * The lookup key for a {@link NetworkInfo} object. This is supplied when
248 * there is another network that it may be possible to connect to. Retrieve with
249 * {@link android.content.Intent#getParcelableExtra(String)}.
250 *
251 * @deprecated See {@link NetworkInfo}.
252 */
253 @Deprecated
254 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
255 /**
256 * The lookup key for a boolean that indicates whether there is a
257 * complete lack of connectivity, i.e., no network is available.
258 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
259 */
260 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
261 /**
262 * The lookup key for a string that indicates why an attempt to connect
263 * to a network failed. The string has no particular structure. It is
264 * intended to be used in notifications presented to users. Retrieve
265 * it with {@link android.content.Intent#getStringExtra(String)}.
266 */
267 public static final String EXTRA_REASON = "reason";
268 /**
269 * The lookup key for a string that provides optionally supplied
270 * extra information about the network state. The information
271 * may be passed up from the lower networking layers, and its
272 * meaning may be specific to a particular network type. Retrieve
273 * it with {@link android.content.Intent#getStringExtra(String)}.
274 *
275 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
276 */
277 @Deprecated
278 public static final String EXTRA_EXTRA_INFO = "extraInfo";
279 /**
280 * The lookup key for an int that provides information about
281 * our connection to the internet at large. 0 indicates no connection,
282 * 100 indicates a great connection. Retrieve it with
283 * {@link android.content.Intent#getIntExtra(String, int)}.
284 * {@hide}
285 */
286 public static final String EXTRA_INET_CONDITION = "inetCondition";
287 /**
288 * The lookup key for a {@link CaptivePortal} object included with the
289 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
290 * object can be used to either indicate to the system that the captive
291 * portal has been dismissed or that the user does not want to pursue
292 * signing in to captive portal. Retrieve it with
293 * {@link android.content.Intent#getParcelableExtra(String)}.
294 */
295 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
296
297 /**
298 * Key for passing a URL to the captive portal login activity.
299 */
300 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
301
302 /**
303 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
304 * portal login activity.
305 * {@hide}
306 */
307 @SystemApi
308 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
309 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
310
311 /**
312 * Key for passing a user agent string to the captive portal login activity.
313 * {@hide}
314 */
315 @SystemApi
316 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
317 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
318
319 /**
320 * Broadcast action to indicate the change of data activity status
321 * (idle or active) on a network in a recent period.
322 * The network becomes active when data transmission is started, or
323 * idle if there is no data transmission for a period of time.
324 * {@hide}
325 */
326 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
327 public static final String ACTION_DATA_ACTIVITY_CHANGE =
328 "android.net.conn.DATA_ACTIVITY_CHANGE";
329 /**
330 * The lookup key for an enum that indicates the network device type on which this data activity
331 * change happens.
332 * {@hide}
333 */
334 public static final String EXTRA_DEVICE_TYPE = "deviceType";
335 /**
336 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
337 * it is actively sending or receiving data and {@code false} means it is idle.
338 * {@hide}
339 */
340 public static final String EXTRA_IS_ACTIVE = "isActive";
341 /**
342 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
343 * {@hide}
344 */
345 public static final String EXTRA_REALTIME_NS = "tsNanos";
346
347 /**
348 * Broadcast Action: The setting for background data usage has changed
349 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
350 * <p>
351 * If an application uses the network in the background, it should listen
352 * for this broadcast and stop using the background data if the value is
353 * {@code false}.
354 * <p>
355 *
356 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
357 * of background data depends on several combined factors, and
358 * this broadcast is no longer sent. Instead, when background
359 * data is unavailable, {@link #getActiveNetworkInfo()} will now
360 * appear disconnected. During first boot after a platform
361 * upgrade, this broadcast will be sent once if
362 * {@link #getBackgroundDataSetting()} was {@code false} before
363 * the upgrade.
364 */
365 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
366 @Deprecated
367 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
368 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
369
370 /**
371 * Broadcast Action: The network connection may not be good
372 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
373 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
374 * the network and it's condition.
375 * @hide
376 */
377 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
378 @UnsupportedAppUsage
379 public static final String INET_CONDITION_ACTION =
380 "android.net.conn.INET_CONDITION_ACTION";
381
382 /**
383 * Broadcast Action: A tetherable connection has come or gone.
384 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
385 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
386 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
387 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
388 * the current state of tethering. Each include a list of
389 * interface names in that state (may be empty).
390 * @hide
391 */
392 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
393 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
394 public static final String ACTION_TETHER_STATE_CHANGED =
395 TetheringManager.ACTION_TETHER_STATE_CHANGED;
396
397 /**
398 * @hide
399 * gives a String[] listing all the interfaces configured for
400 * tethering and currently available for tethering.
401 */
402 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
403 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
404
405 /**
406 * @hide
407 * gives a String[] listing all the interfaces currently in local-only
408 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
409 */
410 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
411
412 /**
413 * @hide
414 * gives a String[] listing all the interfaces currently tethered
415 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
416 */
417 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
418 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
419
420 /**
421 * @hide
422 * gives a String[] listing all the interfaces we tried to tether and
423 * failed. Use {@link #getLastTetherError} to find the error code
424 * for any interfaces listed here.
425 */
426 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
427 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
428
429 /**
430 * Broadcast Action: The captive portal tracker has finished its test.
431 * Sent only while running Setup Wizard, in lieu of showing a user
432 * notification.
433 * @hide
434 */
435 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
436 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
437 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
438 /**
439 * The lookup key for a boolean that indicates whether a captive portal was detected.
440 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
441 * @hide
442 */
443 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
444
445 /**
446 * Action used to display a dialog that asks the user whether to connect to a network that is
447 * not validated. This intent is used to start the dialog in settings via startActivity.
448 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800449 * This action includes a {@link Network} typed extra which is called
450 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
451 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900452 * @hide
453 */
lucaslincf6d4502021-03-04 17:09:51 +0800454 @SystemApi(client = MODULE_LIBRARIES)
455 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900456
457 /**
458 * Action used to display a dialog that asks the user whether to avoid a network that is no
459 * longer validated. This intent is used to start the dialog in settings via startActivity.
460 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800461 * This action includes a {@link Network} typed extra which is called
462 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
463 * validated.
464 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900465 * @hide
466 */
lucaslincf6d4502021-03-04 17:09:51 +0800467 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900468 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800469 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900470
471 /**
472 * Action used to display a dialog that asks the user whether to stay connected to a network
473 * that has not validated. This intent is used to start the dialog in settings via
474 * startActivity.
475 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800476 * This action includes a {@link Network} typed extra which is called
477 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
478 * connectivity.
479 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900480 * @hide
481 */
lucaslincf6d4502021-03-04 17:09:51 +0800482 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900483 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800484 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900485
486 /**
paulhub49c8422021-04-07 16:18:13 +0800487 * Clear DNS Cache Action: This is broadcast when networks have changed and old
488 * DNS entries should be cleared.
489 * @hide
490 */
491 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
492 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
493 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
494
495 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900496 * Invalid tethering type.
497 * @see #startTethering(int, boolean, OnStartTetheringCallback)
498 * @hide
499 */
500 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
501
502 /**
503 * Wifi tethering type.
504 * @see #startTethering(int, boolean, OnStartTetheringCallback)
505 * @hide
506 */
507 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900508 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900509
510 /**
511 * USB tethering type.
512 * @see #startTethering(int, boolean, OnStartTetheringCallback)
513 * @hide
514 */
515 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900516 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900517
518 /**
519 * Bluetooth tethering type.
520 * @see #startTethering(int, boolean, OnStartTetheringCallback)
521 * @hide
522 */
523 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900524 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900525
526 /**
527 * Wifi P2p tethering type.
528 * Wifi P2p tethering is set through events automatically, and don't
529 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
530 * @hide
531 */
532 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
533
534 /**
535 * Extra used for communicating with the TetherService. Includes the type of tethering to
536 * enable if any.
537 * @hide
538 */
539 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
540
541 /**
542 * Extra used for communicating with the TetherService. Includes the type of tethering for
543 * which to cancel provisioning.
544 * @hide
545 */
546 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
547
548 /**
549 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
550 * provisioning.
551 * @hide
552 */
553 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
554
555 /**
556 * Tells the TetherService to run a provision check now.
557 * @hide
558 */
559 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
560
561 /**
562 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
563 * which will receive provisioning results. Can be left empty.
564 * @hide
565 */
566 public static final String EXTRA_PROVISION_CALLBACK =
567 TetheringConstants.EXTRA_PROVISION_CALLBACK;
568
569 /**
570 * The absence of a connection type.
571 * @hide
572 */
573 @SystemApi
574 public static final int TYPE_NONE = -1;
575
576 /**
577 * A Mobile data connection. Devices may support more than one.
578 *
579 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
580 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000581 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900582 */
583 @Deprecated
584 public static final int TYPE_MOBILE = 0;
585
586 /**
587 * A WIFI data connection. Devices may support more than one.
588 *
589 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
590 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000591 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900592 */
593 @Deprecated
594 public static final int TYPE_WIFI = 1;
595
596 /**
597 * An MMS-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 * Multimedia Messaging Service servers.
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_MMS} capability.
605 */
606 @Deprecated
607 public static final int TYPE_MOBILE_MMS = 2;
608
609 /**
610 * A SUPL-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 used by applications needing to talk to the carrier's
613 * Secure User Plane Location servers for help locating the device.
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_SUPL} capability.
618 */
619 @Deprecated
620 public static final int TYPE_MOBILE_SUPL = 3;
621
622 /**
623 * A DUN-specific Mobile data connection. This network type may use the
624 * same network interface as {@link #TYPE_MOBILE} or it may use a different
625 * one. This is sometimes by the system when setting up an upstream connection
626 * for tethering so that the carrier is aware of DUN traffic.
627 *
628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
630 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
631 */
632 @Deprecated
633 public static final int TYPE_MOBILE_DUN = 4;
634
635 /**
636 * A High Priority Mobile data connection. This network type uses the
637 * same network interface as {@link #TYPE_MOBILE} but the routing setup
638 * is different.
639 *
640 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
641 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000642 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900643 */
644 @Deprecated
645 public static final int TYPE_MOBILE_HIPRI = 5;
646
647 /**
648 * A WiMAX data connection.
649 *
650 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
651 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000652 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900653 */
654 @Deprecated
655 public static final int TYPE_WIMAX = 6;
656
657 /**
658 * A Bluetooth data connection.
659 *
660 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
661 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000662 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900663 */
664 @Deprecated
665 public static final int TYPE_BLUETOOTH = 7;
666
667 /**
668 * Fake data connection. This should not be used on shipping devices.
669 * @deprecated This is not used any more.
670 */
671 @Deprecated
672 public static final int TYPE_DUMMY = 8;
673
674 /**
675 * An Ethernet data connection.
676 *
677 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
678 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000679 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900680 */
681 @Deprecated
682 public static final int TYPE_ETHERNET = 9;
683
684 /**
685 * Over the air Administration.
686 * @deprecated Use {@link NetworkCapabilities} instead.
687 * {@hide}
688 */
689 @Deprecated
690 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
691 public static final int TYPE_MOBILE_FOTA = 10;
692
693 /**
694 * IP Multimedia Subsystem.
695 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
696 * {@hide}
697 */
698 @Deprecated
699 @UnsupportedAppUsage
700 public static final int TYPE_MOBILE_IMS = 11;
701
702 /**
703 * Carrier Branded Services.
704 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
705 * {@hide}
706 */
707 @Deprecated
708 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
709 public static final int TYPE_MOBILE_CBS = 12;
710
711 /**
712 * A Wi-Fi p2p connection. Only requesting processes will have access to
713 * the peers connected.
714 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
715 * {@hide}
716 */
717 @Deprecated
718 @SystemApi
719 public static final int TYPE_WIFI_P2P = 13;
720
721 /**
722 * The network to use for initially attaching to the network
723 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
724 * {@hide}
725 */
726 @Deprecated
727 @UnsupportedAppUsage
728 public static final int TYPE_MOBILE_IA = 14;
729
730 /**
731 * Emergency PDN connection for emergency services. This
732 * may include IMS and MMS in emergency situations.
733 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
734 * {@hide}
735 */
736 @Deprecated
737 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
738 public static final int TYPE_MOBILE_EMERGENCY = 15;
739
740 /**
741 * The network that uses proxy to achieve connectivity.
742 * @deprecated Use {@link NetworkCapabilities} instead.
743 * {@hide}
744 */
745 @Deprecated
746 @SystemApi
747 public static final int TYPE_PROXY = 16;
748
749 /**
750 * A virtual network using one or more native bearers.
751 * It may or may not be providing security services.
752 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
753 */
754 @Deprecated
755 public static final int TYPE_VPN = 17;
756
757 /**
758 * A network that is exclusively meant to be used for testing
759 *
760 * @deprecated Use {@link NetworkCapabilities} instead.
761 * @hide
762 */
763 @Deprecated
764 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
765
766 /**
767 * @deprecated Use {@link NetworkCapabilities} instead.
768 * @hide
769 */
770 @Deprecated
771 @Retention(RetentionPolicy.SOURCE)
772 @IntDef(prefix = { "TYPE_" }, value = {
773 TYPE_NONE,
774 TYPE_MOBILE,
775 TYPE_WIFI,
776 TYPE_MOBILE_MMS,
777 TYPE_MOBILE_SUPL,
778 TYPE_MOBILE_DUN,
779 TYPE_MOBILE_HIPRI,
780 TYPE_WIMAX,
781 TYPE_BLUETOOTH,
782 TYPE_DUMMY,
783 TYPE_ETHERNET,
784 TYPE_MOBILE_FOTA,
785 TYPE_MOBILE_IMS,
786 TYPE_MOBILE_CBS,
787 TYPE_WIFI_P2P,
788 TYPE_MOBILE_IA,
789 TYPE_MOBILE_EMERGENCY,
790 TYPE_PROXY,
791 TYPE_VPN,
792 TYPE_TEST
793 })
794 public @interface LegacyNetworkType {}
795
796 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
797 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
798 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
799 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
800 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
801
802 /** {@hide} */
803 public static final int MAX_RADIO_TYPE = TYPE_TEST;
804
805 /** {@hide} */
806 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
807
808 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
809
810 /**
811 * If you want to set the default network preference,you can directly
812 * change the networkAttributes array in framework's config.xml.
813 *
814 * @deprecated Since we support so many more networks now, the single
815 * network default network preference can't really express
816 * the hierarchy. Instead, the default is defined by the
817 * networkAttributes in config.xml. You can determine
818 * the current value by calling {@link #getNetworkPreference()}
819 * from an App.
820 */
821 @Deprecated
822 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
823
824 /**
825 * @hide
826 */
827 public static final int REQUEST_ID_UNSET = 0;
828
829 /**
830 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
831 * This allows to distinguish when unregistering NetworkCallbacks those that were never
832 * registered from those that were already unregistered.
833 * @hide
834 */
835 private static final NetworkRequest ALREADY_UNREGISTERED =
836 new NetworkRequest.Builder().clearCapabilities().build();
837
838 /**
839 * A NetID indicating no Network is selected.
840 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
841 * @hide
842 */
843 public static final int NETID_UNSET = 0;
844
845 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000846 * Flag to indicate that an app is not subject to any restrictions that could result in its
847 * network access blocked.
848 *
849 * @hide
850 */
851 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
852 public static final int BLOCKED_REASON_NONE = 0;
853
854 /**
855 * Flag to indicate that an app is subject to Battery saver restrictions that would
856 * result in its network access being blocked.
857 *
858 * @hide
859 */
860 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
861 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
862
863 /**
864 * Flag to indicate that an app is subject to Doze restrictions that would
865 * result in its network access being blocked.
866 *
867 * @hide
868 */
869 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
870 public static final int BLOCKED_REASON_DOZE = 1 << 1;
871
872 /**
873 * Flag to indicate that an app is subject to App Standby restrictions that would
874 * result in its network access being blocked.
875 *
876 * @hide
877 */
878 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
879 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
880
881 /**
882 * Flag to indicate that an app is subject to Restricted mode restrictions that would
883 * result in its network access being blocked.
884 *
885 * @hide
886 */
887 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
888 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
889
890 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900891 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
892 * is not currently connected.
893 *
894 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
895 *
896 * @hide
897 */
898 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
899 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
900
901 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100902 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
903 * result in its network access being blocked.
904 *
905 * @hide
906 */
907 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
908 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
909
910 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000911 * Flag to indicate that an app is subject to Data saver restrictions that would
912 * result in its metered network access being blocked.
913 *
914 * @hide
915 */
916 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
917 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
918
919 /**
920 * Flag to indicate that an app is subject to user restrictions that would
921 * result in its metered network access being blocked.
922 *
923 * @hide
924 */
925 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
926 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
927
928 /**
929 * Flag to indicate that an app is subject to Device admin restrictions that would
930 * result in its metered network access being blocked.
931 *
932 * @hide
933 */
934 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
935 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
936
937 /**
938 * @hide
939 */
940 @Retention(RetentionPolicy.SOURCE)
941 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
942 BLOCKED_REASON_NONE,
943 BLOCKED_REASON_BATTERY_SAVER,
944 BLOCKED_REASON_DOZE,
945 BLOCKED_REASON_APP_STANDBY,
946 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900947 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100948 BLOCKED_REASON_LOW_POWER_STANDBY,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000949 BLOCKED_METERED_REASON_DATA_SAVER,
950 BLOCKED_METERED_REASON_USER_RESTRICTED,
951 BLOCKED_METERED_REASON_ADMIN_DISABLED,
952 })
953 public @interface BlockedReason {}
954
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900955 /**
956 * Set of blocked reasons that are only applicable on metered networks.
957 *
958 * @hide
959 */
960 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
961 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
962
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900963 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
964 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900965
Robert Horvathd945bf02022-01-27 19:55:16 +0100966 // LINT.IfChange(firewall_chain)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900967 /**
markchiene1561fa2021-12-09 22:00:56 +0800968 * Firewall chain for device idle (doze mode).
969 * Allowlist of apps that have network access in device idle.
970 * @hide
971 */
972 @SystemApi(client = MODULE_LIBRARIES)
973 public static final int FIREWALL_CHAIN_DOZABLE = 1;
974
975 /**
976 * Firewall chain used for app standby.
977 * Denylist of apps that do not have network access.
978 * @hide
979 */
980 @SystemApi(client = MODULE_LIBRARIES)
981 public static final int FIREWALL_CHAIN_STANDBY = 2;
982
983 /**
984 * Firewall chain used for battery saver.
985 * Allowlist of apps that have network access when battery saver is on.
986 * @hide
987 */
988 @SystemApi(client = MODULE_LIBRARIES)
989 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
990
991 /**
992 * Firewall chain used for restricted networking mode.
993 * Allowlist of apps that have access in restricted networking mode.
994 * @hide
995 */
996 @SystemApi(client = MODULE_LIBRARIES)
997 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
998
Robert Horvath34cba142022-01-27 19:52:43 +0100999 /**
1000 * Firewall chain used for low power standby.
1001 * Allowlist of apps that have access in low power standby.
1002 * @hide
1003 */
1004 @SystemApi(client = MODULE_LIBRARIES)
1005 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
1006
Motomu Utsumib08654c2022-05-11 05:56:26 +00001007 /**
Motomu Utsumid9801492022-06-01 13:57:27 +00001008 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001009 *
1010 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1011 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1012 *
1013 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1014 * independent of the others. The chains can be enabled and disabled independently, and apps can
1015 * be added and removed from each chain independently.
1016 *
1017 * @see #FIREWALL_CHAIN_OEM_DENY_2
1018 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001019 * @hide
1020 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001021 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001022 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1023
1024 /**
1025 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001026 *
1027 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1028 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1029 *
1030 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1031 * independent of the others. The chains can be enabled and disabled independently, and apps can
1032 * be added and removed from each chain independently.
1033 *
1034 * @see #FIREWALL_CHAIN_OEM_DENY_1
1035 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001036 * @hide
1037 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001038 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001039 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1040
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001041 /**
1042 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001043 *
1044 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1045 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1046 *
1047 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1048 * independent of the others. The chains can be enabled and disabled independently, and apps can
1049 * be added and removed from each chain independently.
1050 *
1051 * @see #FIREWALL_CHAIN_OEM_DENY_1
1052 * @see #FIREWALL_CHAIN_OEM_DENY_2
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001053 * @hide
1054 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001055 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001056 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1057
markchiene1561fa2021-12-09 22:00:56 +08001058 /** @hide */
1059 @Retention(RetentionPolicy.SOURCE)
1060 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1061 FIREWALL_CHAIN_DOZABLE,
1062 FIREWALL_CHAIN_STANDBY,
1063 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001064 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001065 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Motomu Utsumid9801492022-06-01 13:57:27 +00001066 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001067 FIREWALL_CHAIN_OEM_DENY_2,
1068 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001069 })
1070 public @interface FirewallChain {}
Robert Horvathd945bf02022-01-27 19:55:16 +01001071 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
markchiene1561fa2021-12-09 22:00:56 +08001072
1073 /**
markchien011a7f52022-03-29 01:07:22 +08001074 * A firewall rule which allows or drops packets depending on existing policy.
1075 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1076 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001077 * @hide
1078 */
1079 @SystemApi(client = MODULE_LIBRARIES)
1080 public static final int FIREWALL_RULE_DEFAULT = 0;
1081
1082 /**
markchien011a7f52022-03-29 01:07:22 +08001083 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1084 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001085 * @hide
1086 */
1087 @SystemApi(client = MODULE_LIBRARIES)
1088 public static final int FIREWALL_RULE_ALLOW = 1;
1089
1090 /**
markchien011a7f52022-03-29 01:07:22 +08001091 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1092 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001093 * @hide
1094 */
1095 @SystemApi(client = MODULE_LIBRARIES)
1096 public static final int FIREWALL_RULE_DENY = 2;
1097
1098 /** @hide */
1099 @Retention(RetentionPolicy.SOURCE)
1100 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1101 FIREWALL_RULE_DEFAULT,
1102 FIREWALL_RULE_ALLOW,
1103 FIREWALL_RULE_DENY
1104 })
1105 public @interface FirewallRule {}
1106
1107 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001108 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1109 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1110 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1111 * methods that take a Context argument.
1112 */
1113 private static ConnectivityManager sInstance;
1114
1115 private final Context mContext;
1116
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001117 @GuardedBy("mTetheringEventCallbacks")
1118 private TetheringManager mTetheringManager;
1119
1120 private TetheringManager getTetheringManager() {
1121 synchronized (mTetheringEventCallbacks) {
1122 if (mTetheringManager == null) {
1123 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1124 }
1125 return mTetheringManager;
1126 }
1127 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001128
1129 /**
1130 * Tests if a given integer represents a valid network type.
1131 * @param networkType the type to be tested
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001132 * @return {@code true} if the type is valid, else {@code false}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001133 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1134 * validate a network type.
1135 */
1136 @Deprecated
1137 public static boolean isNetworkTypeValid(int networkType) {
1138 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1139 }
1140
1141 /**
1142 * Returns a non-localized string representing a given network type.
1143 * ONLY used for debugging output.
1144 * @param type the type needing naming
1145 * @return a String for the given type, or a string version of the type ("87")
1146 * if no name is known.
1147 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1148 * {@hide}
1149 */
1150 @Deprecated
1151 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1152 public static String getNetworkTypeName(int type) {
1153 switch (type) {
1154 case TYPE_NONE:
1155 return "NONE";
1156 case TYPE_MOBILE:
1157 return "MOBILE";
1158 case TYPE_WIFI:
1159 return "WIFI";
1160 case TYPE_MOBILE_MMS:
1161 return "MOBILE_MMS";
1162 case TYPE_MOBILE_SUPL:
1163 return "MOBILE_SUPL";
1164 case TYPE_MOBILE_DUN:
1165 return "MOBILE_DUN";
1166 case TYPE_MOBILE_HIPRI:
1167 return "MOBILE_HIPRI";
1168 case TYPE_WIMAX:
1169 return "WIMAX";
1170 case TYPE_BLUETOOTH:
1171 return "BLUETOOTH";
1172 case TYPE_DUMMY:
1173 return "DUMMY";
1174 case TYPE_ETHERNET:
1175 return "ETHERNET";
1176 case TYPE_MOBILE_FOTA:
1177 return "MOBILE_FOTA";
1178 case TYPE_MOBILE_IMS:
1179 return "MOBILE_IMS";
1180 case TYPE_MOBILE_CBS:
1181 return "MOBILE_CBS";
1182 case TYPE_WIFI_P2P:
1183 return "WIFI_P2P";
1184 case TYPE_MOBILE_IA:
1185 return "MOBILE_IA";
1186 case TYPE_MOBILE_EMERGENCY:
1187 return "MOBILE_EMERGENCY";
1188 case TYPE_PROXY:
1189 return "PROXY";
1190 case TYPE_VPN:
1191 return "VPN";
Junyu Laic9f1ca62022-07-25 16:31:59 +08001192 case TYPE_TEST:
1193 return "TEST";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001194 default:
1195 return Integer.toString(type);
1196 }
1197 }
1198
1199 /**
1200 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001201 */
lucaslin10774b72021-03-17 14:16:01 +08001202 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001203 public void systemReady() {
1204 try {
1205 mService.systemReady();
1206 } catch (RemoteException e) {
1207 throw e.rethrowFromSystemServer();
1208 }
1209 }
1210
1211 /**
1212 * Checks if a given type uses the cellular data connection.
1213 * This should be replaced in the future by a network property.
1214 * @param networkType the type to check
1215 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1216 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1217 * {@hide}
1218 */
1219 @Deprecated
1220 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1221 public static boolean isNetworkTypeMobile(int networkType) {
1222 switch (networkType) {
1223 case TYPE_MOBILE:
1224 case TYPE_MOBILE_MMS:
1225 case TYPE_MOBILE_SUPL:
1226 case TYPE_MOBILE_DUN:
1227 case TYPE_MOBILE_HIPRI:
1228 case TYPE_MOBILE_FOTA:
1229 case TYPE_MOBILE_IMS:
1230 case TYPE_MOBILE_CBS:
1231 case TYPE_MOBILE_IA:
1232 case TYPE_MOBILE_EMERGENCY:
1233 return true;
1234 default:
1235 return false;
1236 }
1237 }
1238
1239 /**
1240 * Checks if the given network type is backed by a Wi-Fi radio.
1241 *
1242 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1243 * @hide
1244 */
1245 @Deprecated
1246 public static boolean isNetworkTypeWifi(int networkType) {
1247 switch (networkType) {
1248 case TYPE_WIFI:
1249 case TYPE_WIFI_P2P:
1250 return true;
1251 default:
1252 return false;
1253 }
1254 }
1255
1256 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001257 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001258 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Junyu Lai35665cc2022-12-19 17:37:48 +08001259 * Specify that the traffic for this user should by follow the default rules:
1260 * applications in the profile designated by the UserHandle behave like any
1261 * other application and use the system default network as their default
1262 * network. Compare other PROFILE_NETWORK_PREFERENCE_* settings.
Chalard Jeanad565e22021-02-25 17:23:40 +09001263 * @hide
1264 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001265 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001266 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1267
1268 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001269 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001270 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001271 * Specify that the traffic for this user should by default go on a network with
1272 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1273 * if no such network is available.
1274 * @hide
1275 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001276 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001277 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1278
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001279 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001280 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001281 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001282 * Specify that the traffic for this user should by default go on a network with
1283 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
Junyu Lai35665cc2022-12-19 17:37:48 +08001284 * should not have a default network at all (that is, network accesses that
1285 * do not specify a network explicitly terminate with an error), even if there
1286 * is a system default network available to apps outside this preference.
1287 * The apps can still use a non-enterprise network if they request it explicitly
1288 * provided that specific network doesn't require any specific permission they
1289 * do not hold.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001290 * @hide
1291 */
1292 @SystemApi(client = MODULE_LIBRARIES)
1293 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1294
Junyu Lai35665cc2022-12-19 17:37:48 +08001295 /**
1296 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
1297 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1298 * Specify that the traffic for this user should by default go on a network with
1299 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}.
1300 * If there is no such network, the apps will have no default
1301 * network at all, even if there are available non-enterprise networks on the
1302 * device (that is, network accesses that do not specify a network explicitly
1303 * terminate with an error). Additionally, the designated apps should be
1304 * blocked from using any non-enterprise network even if they specify it
1305 * explicitly, unless they hold specific privilege overriding this (see
1306 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS}).
1307 * @hide
1308 */
1309 @SystemApi(client = MODULE_LIBRARIES)
1310 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING = 3;
1311
Chalard Jeanad565e22021-02-25 17:23:40 +09001312 /** @hide */
1313 @Retention(RetentionPolicy.SOURCE)
1314 @IntDef(value = {
1315 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001316 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1317 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001318 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001319 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001320 }
1321
1322 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001323 * Specifies the preferred network type. When the device has more
1324 * than one type available the preferred network type will be used.
1325 *
1326 * @param preference the network type to prefer over all others. It is
1327 * unspecified what happens to the old preferred network in the
1328 * overall ordering.
1329 * @deprecated Functionality has been removed as it no longer makes sense,
1330 * with many more than two networks - we'd need an array to express
1331 * preference. Instead we use dynamic network properties of
1332 * the networks to describe their precedence.
1333 */
1334 @Deprecated
1335 public void setNetworkPreference(int preference) {
1336 }
1337
1338 /**
1339 * Retrieves the current preferred network type.
1340 *
1341 * @return an integer representing the preferred network type
1342 *
1343 * @deprecated Functionality has been removed as it no longer makes sense,
1344 * with many more than two networks - we'd need an array to express
1345 * preference. Instead we use dynamic network properties of
1346 * the networks to describe their precedence.
1347 */
1348 @Deprecated
1349 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1350 public int getNetworkPreference() {
1351 return TYPE_NONE;
1352 }
1353
1354 /**
1355 * Returns details about the currently active default data network. When
1356 * connected, this network is the default route for outgoing connections.
1357 * You should always check {@link NetworkInfo#isConnected()} before initiating
1358 * network traffic. This may return {@code null} when there is no default
1359 * network.
1360 * Note that if the default network is a VPN, this method will return the
1361 * NetworkInfo for one of its underlying networks instead, or null if the
1362 * VPN agent did not specify any. Apps interested in learning about VPNs
1363 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1364 *
1365 * @return a {@link NetworkInfo} object for the current default network
1366 * or {@code null} if no default network is currently active
1367 * @deprecated See {@link NetworkInfo}.
1368 */
1369 @Deprecated
1370 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1371 @Nullable
1372 public NetworkInfo getActiveNetworkInfo() {
1373 try {
1374 return mService.getActiveNetworkInfo();
1375 } catch (RemoteException e) {
1376 throw e.rethrowFromSystemServer();
1377 }
1378 }
1379
1380 /**
1381 * Returns a {@link Network} object corresponding to the currently active
1382 * default data network. In the event that the current active default data
1383 * network disconnects, the returned {@code Network} object will no longer
1384 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001385 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001386 *
1387 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001388 * {@code null} if no default network is currently active or if
1389 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001390 */
1391 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1392 @Nullable
1393 public Network getActiveNetwork() {
1394 try {
1395 return mService.getActiveNetwork();
1396 } catch (RemoteException e) {
1397 throw e.rethrowFromSystemServer();
1398 }
1399 }
1400
1401 /**
1402 * Returns a {@link Network} object corresponding to the currently active
1403 * default data network for a specific UID. In the event that the default data
1404 * network disconnects, the returned {@code Network} object will no longer
1405 * be usable. This will return {@code null} when there is no default
1406 * network for the UID.
1407 *
1408 * @return a {@link Network} object for the current default network for the
1409 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001410 *
1411 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001412 */
1413 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1414 @Nullable
1415 public Network getActiveNetworkForUid(int uid) {
1416 return getActiveNetworkForUid(uid, false);
1417 }
1418
1419 /** {@hide} */
1420 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1421 try {
1422 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1423 } catch (RemoteException e) {
1424 throw e.rethrowFromSystemServer();
1425 }
1426 }
1427
lucaslin3ba7cc22022-12-19 02:35:33 +00001428 private static UidRange[] getUidRangeArray(@NonNull Collection<Range<Integer>> ranges) {
1429 Objects.requireNonNull(ranges);
1430 final UidRange[] rangesArray = new UidRange[ranges.size()];
1431 int index = 0;
1432 for (Range<Integer> range : ranges) {
1433 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1434 }
1435
1436 return rangesArray;
1437 }
1438
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001439 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001440 * Adds or removes a requirement for given UID ranges to use the VPN.
1441 *
1442 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1443 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1444 * otherwise have permission to bypass the VPN (e.g., because they have the
1445 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1446 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1447 * set to {@code false}, a previously-added restriction is removed.
1448 * <p>
1449 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1450 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1451 * remove a previously-added range, the exact range must be removed as is.
1452 * <p>
1453 * The changes are applied asynchronously and may not have been applied by the time the method
1454 * returns. Apps will be notified about any changes that apply to them via
1455 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1456 * effect.
1457 * <p>
lucaslin3ba7cc22022-12-19 02:35:33 +00001458 * This method will block the specified UIDs from accessing non-VPN networks, but does not
1459 * affect what the UIDs get as their default network.
1460 * Compare {@link #setVpnDefaultForUids(String, Collection)}, which declares that the UIDs
1461 * should only have a VPN as their default network, but does not block them from accessing other
1462 * networks if they request them explicitly with the {@link Network} API.
1463 * <p>
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001464 * This method should be called only by the VPN code.
1465 *
1466 * @param ranges the UID ranges to restrict
1467 * @param requireVpn whether the specified UID ranges must use a VPN
1468 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001469 * @hide
1470 */
1471 @RequiresPermission(anyOf = {
1472 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001473 android.Manifest.permission.NETWORK_STACK,
1474 android.Manifest.permission.NETWORK_SETTINGS})
1475 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001476 public void setRequireVpnForUids(boolean requireVpn,
1477 @NonNull Collection<Range<Integer>> ranges) {
1478 Objects.requireNonNull(ranges);
1479 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1480 // This method is not necessarily expected to be used outside the system server, so
1481 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1482 // stack process, or by tests.
lucaslin3ba7cc22022-12-19 02:35:33 +00001483 final UidRange[] rangesArray = getUidRangeArray(ranges);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001484 try {
1485 mService.setRequireVpnForUids(requireVpn, rangesArray);
1486 } catch (RemoteException e) {
1487 throw e.rethrowFromSystemServer();
1488 }
1489 }
1490
1491 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001492 * Inform the system that this VPN session should manage the passed UIDs.
1493 *
1494 * A VPN with the specified session ID may call this method to inform the system that the UIDs
1495 * in the specified range are subject to a VPN.
1496 * When this is called, the system will only choose a VPN for the default network of the UIDs in
1497 * the specified ranges.
1498 *
1499 * This method declares that the UIDs in the range will only have a VPN for their default
1500 * network, but does not block the UIDs from accessing other networks (permissions allowing) by
1501 * explicitly requesting it with the {@link Network} API.
1502 * Compare {@link #setRequireVpnForUids(boolean, Collection)}, which does not affect what
1503 * network the UIDs get as default, but will block them from accessing non-VPN networks.
1504 *
1505 * @param session The VPN session which manages the passed UIDs.
1506 * @param ranges The uid ranges which will treat VPN as their only default network.
1507 *
1508 * @hide
1509 */
1510 @RequiresPermission(anyOf = {
1511 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1512 android.Manifest.permission.NETWORK_STACK,
1513 android.Manifest.permission.NETWORK_SETTINGS})
1514 @SystemApi(client = MODULE_LIBRARIES)
1515 public void setVpnDefaultForUids(@NonNull String session,
1516 @NonNull Collection<Range<Integer>> ranges) {
1517 Objects.requireNonNull(ranges);
1518 final UidRange[] rangesArray = getUidRangeArray(ranges);
1519 try {
1520 mService.setVpnNetworkPreference(session, rangesArray);
1521 } catch (RemoteException e) {
1522 throw e.rethrowFromSystemServer();
1523 }
1524 }
1525
1526 /**
chiachangwange0192a72023-02-06 13:25:01 +00001527 * Temporarily set automaticOnOff keeplaive TCP polling alarm timer to 1 second.
1528 *
1529 * TODO: Remove this when the TCP polling design is replaced with callback.
Jean Chalard17cbf062023-02-13 05:07:48 +00001530 * @param timeMs The time of expiry, with System.currentTimeMillis() base. The value should be
1531 * set no more than 5 minutes in the future.
chiachangwange0192a72023-02-06 13:25:01 +00001532 * @hide
1533 */
1534 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
1535 try {
1536 mService.setTestLowTcpPollingTimerForKeepalive(timeMs);
1537 } catch (RemoteException e) {
1538 throw e.rethrowFromSystemServer();
1539 }
1540 }
1541
1542 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001543 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1544 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1545 * but is still supported for backwards compatibility.
1546 * <p>
1547 * This type of VPN is assumed always to use the system default network, and must always declare
1548 * exactly one underlying network, which is the network that was the default when the VPN
1549 * connected.
1550 * <p>
1551 * Calling this method with {@code true} enables legacy behaviour, specifically:
1552 * <ul>
1553 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1554 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1555 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1556 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1557 * underlying the VPN.</li>
1558 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1559 * similarly replaced by the VPN network state.</li>
1560 * <li>Information on current network interfaces passed to NetworkStatsService will not
1561 * include any VPN interfaces.</li>
1562 * </ul>
1563 *
1564 * @param enabled whether legacy lockdown VPN is enabled or disabled
1565 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001566 * @hide
1567 */
1568 @RequiresPermission(anyOf = {
1569 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001570 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001571 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001572 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001573 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1574 try {
1575 mService.setLegacyLockdownVpnEnabled(enabled);
1576 } catch (RemoteException e) {
1577 throw e.rethrowFromSystemServer();
1578 }
1579 }
1580
1581 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001582 * Returns details about the currently active default data network for a given uid.
1583 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001584 *
1585 * @return a {@link NetworkInfo} object for the current default network
1586 * for the given uid or {@code null} if no default network is
1587 * available for the specified uid.
1588 *
1589 * {@hide}
1590 */
1591 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1592 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1593 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1594 return getActiveNetworkInfoForUid(uid, false);
1595 }
1596
1597 /** {@hide} */
1598 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1599 try {
1600 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1601 } catch (RemoteException e) {
1602 throw e.rethrowFromSystemServer();
1603 }
1604 }
1605
1606 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001607 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001608 *
1609 * @param networkType integer specifying which networkType in
1610 * which you're interested.
1611 * @return a {@link NetworkInfo} object for the requested
1612 * network type or {@code null} if the type is not
1613 * supported by the device. If {@code networkType} is
1614 * TYPE_VPN and a VPN is active for the calling app,
1615 * then this method will try to return one of the
1616 * underlying networks for the VPN or null if the
1617 * VPN agent didn't specify any.
1618 *
1619 * @deprecated This method does not support multiple connected networks
1620 * of the same type. Use {@link #getAllNetworks} and
1621 * {@link #getNetworkInfo(android.net.Network)} instead.
1622 */
1623 @Deprecated
1624 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1625 @Nullable
1626 public NetworkInfo getNetworkInfo(int networkType) {
1627 try {
1628 return mService.getNetworkInfo(networkType);
1629 } catch (RemoteException e) {
1630 throw e.rethrowFromSystemServer();
1631 }
1632 }
1633
1634 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001635 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001636 *
1637 * @param network {@link Network} specifying which network
1638 * in which you're interested.
1639 * @return a {@link NetworkInfo} object for the requested
1640 * network or {@code null} if the {@code Network}
1641 * is not valid.
1642 * @deprecated See {@link NetworkInfo}.
1643 */
1644 @Deprecated
1645 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1646 @Nullable
1647 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1648 return getNetworkInfoForUid(network, Process.myUid(), false);
1649 }
1650
1651 /** {@hide} */
1652 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1653 try {
1654 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1655 } catch (RemoteException e) {
1656 throw e.rethrowFromSystemServer();
1657 }
1658 }
1659
1660 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001661 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001662 *
1663 * @return an array of {@link NetworkInfo} objects. Check each
1664 * {@link NetworkInfo#getType} for which type each applies.
1665 *
1666 * @deprecated This method does not support multiple connected networks
1667 * of the same type. Use {@link #getAllNetworks} and
1668 * {@link #getNetworkInfo(android.net.Network)} instead.
1669 */
1670 @Deprecated
1671 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1672 @NonNull
1673 public NetworkInfo[] getAllNetworkInfo() {
1674 try {
1675 return mService.getAllNetworkInfo();
1676 } catch (RemoteException e) {
1677 throw e.rethrowFromSystemServer();
1678 }
1679 }
1680
1681 /**
junyulaib1211372021-03-03 12:09:05 +08001682 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1683 * connected.
1684 * @hide
1685 */
1686 @SystemApi(client = MODULE_LIBRARIES)
1687 @RequiresPermission(anyOf = {
1688 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1689 android.Manifest.permission.NETWORK_STACK,
1690 android.Manifest.permission.NETWORK_SETTINGS})
1691 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001692 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001693 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001694 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001695 } catch (RemoteException e) {
1696 throw e.rethrowFromSystemServer();
1697 }
1698 }
1699
1700 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001701 * Returns the {@link Network} object currently serving a given type, or
1702 * null if the given type is not connected.
1703 *
1704 * @hide
1705 * @deprecated This method does not support multiple connected networks
1706 * of the same type. Use {@link #getAllNetworks} and
1707 * {@link #getNetworkInfo(android.net.Network)} instead.
1708 */
1709 @Deprecated
1710 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1711 @UnsupportedAppUsage
1712 public Network getNetworkForType(int networkType) {
1713 try {
1714 return mService.getNetworkForType(networkType);
1715 } catch (RemoteException e) {
1716 throw e.rethrowFromSystemServer();
1717 }
1718 }
1719
1720 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001721 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001722 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001723 * @deprecated This method does not provide any notification of network state changes, forcing
1724 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1725 * Apps should use methods such as
1726 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1727 * Apps that desire to obtain information about networks that do not apply to them
1728 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1729 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001730 * @return an array of {@link Network} objects.
1731 */
1732 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1733 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001734 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001735 public Network[] getAllNetworks() {
1736 try {
1737 return mService.getAllNetworks();
1738 } catch (RemoteException e) {
1739 throw e.rethrowFromSystemServer();
1740 }
1741 }
1742
1743 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001744 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001745 * the Networks that applications run by the given user will use by default.
1746 * @hide
1747 */
1748 @UnsupportedAppUsage
1749 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1750 try {
1751 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001752 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001753 } catch (RemoteException e) {
1754 throw e.rethrowFromSystemServer();
1755 }
1756 }
1757
1758 /**
1759 * Returns the IP information for the current default network.
1760 *
1761 * @return a {@link LinkProperties} object describing the IP info
1762 * for the current default network, or {@code null} if there
1763 * is no current default network.
1764 *
1765 * {@hide}
1766 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1767 * value of {@link #getActiveNetwork()} instead. In particular,
1768 * this method will return non-null LinkProperties even if the
1769 * app is blocked by policy from using this network.
1770 */
1771 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1772 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1773 public LinkProperties getActiveLinkProperties() {
1774 try {
1775 return mService.getActiveLinkProperties();
1776 } catch (RemoteException e) {
1777 throw e.rethrowFromSystemServer();
1778 }
1779 }
1780
1781 /**
1782 * Returns the IP information for a given network type.
1783 *
1784 * @param networkType the network type of interest.
1785 * @return a {@link LinkProperties} object describing the IP info
1786 * for the given networkType, or {@code null} if there is
1787 * no current default network.
1788 *
1789 * {@hide}
1790 * @deprecated This method does not support multiple connected networks
1791 * of the same type. Use {@link #getAllNetworks},
1792 * {@link #getNetworkInfo(android.net.Network)}, and
1793 * {@link #getLinkProperties(android.net.Network)} instead.
1794 */
1795 @Deprecated
1796 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1797 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1798 public LinkProperties getLinkProperties(int networkType) {
1799 try {
1800 return mService.getLinkPropertiesForType(networkType);
1801 } catch (RemoteException e) {
1802 throw e.rethrowFromSystemServer();
1803 }
1804 }
1805
1806 /**
1807 * Get the {@link LinkProperties} for the given {@link Network}. This
1808 * will return {@code null} if the network is unknown.
1809 *
1810 * @param network The {@link Network} object identifying the network in question.
1811 * @return The {@link LinkProperties} for the network, or {@code null}.
1812 */
1813 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1814 @Nullable
1815 public LinkProperties getLinkProperties(@Nullable Network network) {
1816 try {
1817 return mService.getLinkProperties(network);
1818 } catch (RemoteException e) {
1819 throw e.rethrowFromSystemServer();
1820 }
1821 }
1822
1823 /**
lucaslinc582d502022-01-27 09:07:00 +08001824 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001825 *
lucaslinc582d502022-01-27 09:07:00 +08001826 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1827 * given package, considering its permissions.
1828 *
1829 * @param lp A {@link LinkProperties} which will be redacted.
1830 * @param uid The target uid.
1831 * @param packageName The name of the package, for appops logging.
1832 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1833 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1834 * @hide
1835 */
1836 @RequiresPermission(anyOf = {
1837 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1838 android.Manifest.permission.NETWORK_STACK,
1839 android.Manifest.permission.NETWORK_SETTINGS})
1840 @SystemApi(client = MODULE_LIBRARIES)
1841 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001842 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001843 @NonNull String packageName) {
1844 try {
lucaslind2b06132022-03-02 10:56:57 +08001845 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001846 lp, uid, packageName, getAttributionTag());
1847 } catch (RemoteException e) {
1848 throw e.rethrowFromSystemServer();
1849 }
1850 }
1851
1852 /**
1853 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1854 *
1855 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1856 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1857 * sensitive information. To retrieve this location sensitive information (subject to
1858 * the caller's location permissions), use a {@link NetworkCallback} with the
1859 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1860 *
1861 * This method returns {@code null} if the network is unknown or if the |network| argument
1862 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001863 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001864 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001865 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001866 */
1867 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1868 @Nullable
1869 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1870 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001871 return mService.getNetworkCapabilities(
1872 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001873 } catch (RemoteException e) {
1874 throw e.rethrowFromSystemServer();
1875 }
1876 }
1877
1878 /**
lucaslinc582d502022-01-27 09:07:00 +08001879 * Redact {@link NetworkCapabilities} for a given package.
1880 *
1881 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001882 * to the given package, considering its permissions. If the passed capabilities contain
1883 * location-sensitive information, they will be redacted to the correct degree for the location
1884 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1885 * that level of location. If the UID holds no location permission, the returned object will
1886 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001887 *
1888 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1889 * @param uid The target uid.
1890 * @param packageName The name of the package, for appops logging.
1891 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1892 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1893 * @hide
1894 */
1895 @RequiresPermission(anyOf = {
1896 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1897 android.Manifest.permission.NETWORK_STACK,
1898 android.Manifest.permission.NETWORK_SETTINGS})
1899 @SystemApi(client = MODULE_LIBRARIES)
1900 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001901 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001902 @NonNull NetworkCapabilities nc,
1903 int uid, @NonNull String packageName) {
1904 try {
lucaslind2b06132022-03-02 10:56:57 +08001905 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001906 getAttributionTag());
1907 } catch (RemoteException e) {
1908 throw e.rethrowFromSystemServer();
1909 }
1910 }
1911
1912 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001913 * Gets a URL that can be used for resolving whether a captive portal is present.
1914 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1915 * portal is present.
1916 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1917 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1918 *
1919 * The system network validation may be using different strategies to detect captive portals,
1920 * so this method does not necessarily return a URL used by the system. It only returns a URL
1921 * that may be relevant for other components trying to detect captive portals.
1922 *
1923 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001924 * @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 +09001925 * system.
1926 */
1927 @Deprecated
1928 @SystemApi
1929 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1930 public String getCaptivePortalServerUrl() {
1931 try {
1932 return mService.getCaptivePortalServerUrl();
1933 } catch (RemoteException e) {
1934 throw e.rethrowFromSystemServer();
1935 }
1936 }
1937
1938 /**
1939 * Tells the underlying networking system that the caller wants to
1940 * begin using the named feature. The interpretation of {@code feature}
1941 * is completely up to each networking implementation.
1942 *
1943 * <p>This method requires the caller to hold either the
1944 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1945 * or the ability to modify system settings as determined by
1946 * {@link android.provider.Settings.System#canWrite}.</p>
1947 *
1948 * @param networkType specifies which network the request pertains to
1949 * @param feature the name of the feature to be used
1950 * @return an integer value representing the outcome of the request.
1951 * The interpretation of this value is specific to each networking
1952 * implementation+feature combination, except that the value {@code -1}
1953 * always indicates failure.
1954 *
1955 * @deprecated Deprecated in favor of the cleaner
1956 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1957 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1958 * throw {@code UnsupportedOperationException} if called.
1959 * @removed
1960 */
1961 @Deprecated
1962 public int startUsingNetworkFeature(int networkType, String feature) {
1963 checkLegacyRoutingApiAccess();
1964 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1965 if (netCap == null) {
1966 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1967 feature);
1968 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1969 }
1970
1971 NetworkRequest request = null;
1972 synchronized (sLegacyRequests) {
1973 LegacyRequest l = sLegacyRequests.get(netCap);
1974 if (l != null) {
1975 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1976 renewRequestLocked(l);
1977 if (l.currentNetwork != null) {
1978 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1979 } else {
1980 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1981 }
1982 }
1983
1984 request = requestNetworkForFeatureLocked(netCap);
1985 }
1986 if (request != null) {
1987 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1988 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1989 } else {
1990 Log.d(TAG, " request Failed");
1991 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1992 }
1993 }
1994
1995 /**
1996 * Tells the underlying networking system that the caller is finished
1997 * using the named feature. The interpretation of {@code feature}
1998 * is completely up to each networking implementation.
1999 *
2000 * <p>This method requires the caller to hold either the
2001 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2002 * or the ability to modify system settings as determined by
2003 * {@link android.provider.Settings.System#canWrite}.</p>
2004 *
2005 * @param networkType specifies which network the request pertains to
2006 * @param feature the name of the feature that is no longer needed
2007 * @return an integer value representing the outcome of the request.
2008 * The interpretation of this value is specific to each networking
2009 * implementation+feature combination, except that the value {@code -1}
2010 * always indicates failure.
2011 *
2012 * @deprecated Deprecated in favor of the cleaner
2013 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
2014 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2015 * throw {@code UnsupportedOperationException} if called.
2016 * @removed
2017 */
2018 @Deprecated
2019 public int stopUsingNetworkFeature(int networkType, String feature) {
2020 checkLegacyRoutingApiAccess();
2021 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
2022 if (netCap == null) {
2023 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
2024 feature);
2025 return -1;
2026 }
2027
2028 if (removeRequestForFeature(netCap)) {
2029 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
2030 }
2031 return 1;
2032 }
2033
2034 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2035 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
2036 if (networkType == TYPE_MOBILE) {
2037 switch (feature) {
2038 case "enableCBS":
2039 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
2040 case "enableDUN":
2041 case "enableDUNAlways":
2042 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
2043 case "enableFOTA":
2044 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
2045 case "enableHIPRI":
2046 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
2047 case "enableIMS":
2048 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
2049 case "enableMMS":
2050 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
2051 case "enableSUPL":
2052 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
2053 default:
2054 return null;
2055 }
2056 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
2057 return networkCapabilitiesForType(TYPE_WIFI_P2P);
2058 }
2059 return null;
2060 }
2061
2062 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
2063 if (netCap == null) return TYPE_NONE;
2064 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
2065 return TYPE_MOBILE_CBS;
2066 }
2067 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2068 return TYPE_MOBILE_IMS;
2069 }
2070 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
2071 return TYPE_MOBILE_FOTA;
2072 }
2073 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
2074 return TYPE_MOBILE_DUN;
2075 }
2076 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
2077 return TYPE_MOBILE_SUPL;
2078 }
2079 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2080 return TYPE_MOBILE_MMS;
2081 }
2082 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
2083 return TYPE_MOBILE_HIPRI;
2084 }
2085 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
2086 return TYPE_WIFI_P2P;
2087 }
2088 return TYPE_NONE;
2089 }
2090
2091 private static class LegacyRequest {
2092 NetworkCapabilities networkCapabilities;
2093 NetworkRequest networkRequest;
2094 int expireSequenceNumber;
2095 Network currentNetwork;
2096 int delay = -1;
2097
2098 private void clearDnsBinding() {
2099 if (currentNetwork != null) {
2100 currentNetwork = null;
2101 setProcessDefaultNetworkForHostResolution(null);
2102 }
2103 }
2104
2105 NetworkCallback networkCallback = new NetworkCallback() {
2106 @Override
2107 public void onAvailable(Network network) {
2108 currentNetwork = network;
2109 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
2110 setProcessDefaultNetworkForHostResolution(network);
2111 }
2112 @Override
2113 public void onLost(Network network) {
2114 if (network.equals(currentNetwork)) clearDnsBinding();
2115 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2116 }
2117 };
2118 }
2119
2120 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2121 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2122 new HashMap<>();
2123
2124 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2125 synchronized (sLegacyRequests) {
2126 LegacyRequest l = sLegacyRequests.get(netCap);
2127 if (l != null) return l.networkRequest;
2128 }
2129 return null;
2130 }
2131
2132 private void renewRequestLocked(LegacyRequest l) {
2133 l.expireSequenceNumber++;
2134 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2135 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2136 }
2137
2138 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2139 int ourSeqNum = -1;
2140 synchronized (sLegacyRequests) {
2141 LegacyRequest l = sLegacyRequests.get(netCap);
2142 if (l == null) return;
2143 ourSeqNum = l.expireSequenceNumber;
2144 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2145 }
2146 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2147 }
2148
2149 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2150 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2151 int delay = -1;
2152 int type = legacyTypeForNetworkCapabilities(netCap);
2153 try {
2154 delay = mService.getRestoreDefaultNetworkDelay(type);
2155 } catch (RemoteException e) {
2156 throw e.rethrowFromSystemServer();
2157 }
2158 LegacyRequest l = new LegacyRequest();
2159 l.networkCapabilities = netCap;
2160 l.delay = delay;
2161 l.expireSequenceNumber = 0;
2162 l.networkRequest = sendRequestForNetwork(
2163 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2164 if (l.networkRequest == null) return null;
2165 sLegacyRequests.put(netCap, l);
2166 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2167 return l.networkRequest;
2168 }
2169
2170 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2171 if (delay >= 0) {
2172 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2173 CallbackHandler handler = getDefaultHandler();
2174 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2175 handler.sendMessageDelayed(msg, delay);
2176 }
2177 }
2178
2179 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2180 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2181 final LegacyRequest l;
2182 synchronized (sLegacyRequests) {
2183 l = sLegacyRequests.remove(netCap);
2184 }
2185 if (l == null) return false;
2186 unregisterNetworkCallback(l.networkCallback);
2187 l.clearDnsBinding();
2188 return true;
2189 }
2190
2191 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2192 static {
2193 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2194 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2195 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2196 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2197 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2198 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2199 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2200 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2201 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2202 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2203 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2204 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2205 }
2206
2207 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2208 static {
2209 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2210 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2211 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2212 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2213 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2214 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2215 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2216 }
2217
2218 /**
2219 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2220 * instance suitable for registering a request or callback. Throws an
2221 * IllegalArgumentException if no mapping from the legacy type to
2222 * NetworkCapabilities is known.
2223 *
2224 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2225 * to find the network instead.
2226 * @hide
2227 */
2228 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2229 final NetworkCapabilities nc = new NetworkCapabilities();
2230
2231 // Map from type to transports.
2232 final int NOT_FOUND = -1;
2233 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002234 if (transport == NOT_FOUND) {
2235 throw new IllegalArgumentException("unknown legacy type: " + type);
2236 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002237 nc.addTransportType(transport);
2238
2239 // Map from type to capabilities.
2240 nc.addCapability(sLegacyTypeToCapability.get(
2241 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2242 nc.maybeMarkCapabilitiesRestricted();
2243 return nc;
2244 }
2245
2246 /** @hide */
2247 public static class PacketKeepaliveCallback {
2248 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2249 public PacketKeepaliveCallback() {
2250 }
2251 /** The requested keepalive was successfully started. */
2252 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2253 public void onStarted() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002254 /** The keepalive was resumed after being paused by the system. */
2255 public void onResumed() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002256 /** The keepalive was successfully stopped. */
2257 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2258 public void onStopped() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002259 /** The keepalive was paused automatically by the system. */
2260 public void onPaused() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002261 /** An error occurred. */
2262 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2263 public void onError(int error) {}
2264 }
2265
2266 /**
2267 * Allows applications to request that the system periodically send specific packets on their
2268 * behalf, using hardware offload to save battery power.
2269 *
2270 * To request that the system send keepalives, call one of the methods that return a
2271 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2272 * passing in a non-null callback. If the callback is successfully started, the callback's
2273 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2274 * specifying one of the {@code ERROR_*} constants in this class.
2275 *
2276 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2277 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2278 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2279 *
2280 * @deprecated Use {@link SocketKeepalive} instead.
2281 *
2282 * @hide
2283 */
2284 public class PacketKeepalive {
2285
2286 private static final String TAG = "PacketKeepalive";
2287
2288 /** @hide */
2289 public static final int SUCCESS = 0;
2290
2291 /** @hide */
2292 public static final int NO_KEEPALIVE = -1;
2293
2294 /** @hide */
2295 public static final int BINDER_DIED = -10;
2296
2297 /** The specified {@code Network} is not connected. */
2298 public static final int ERROR_INVALID_NETWORK = -20;
2299 /** The specified IP addresses are invalid. For example, the specified source IP address is
2300 * not configured on the specified {@code Network}. */
2301 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2302 /** The requested port is invalid. */
2303 public static final int ERROR_INVALID_PORT = -22;
2304 /** The packet length is invalid (e.g., too long). */
2305 public static final int ERROR_INVALID_LENGTH = -23;
2306 /** The packet transmission interval is invalid (e.g., too short). */
2307 public static final int ERROR_INVALID_INTERVAL = -24;
2308
2309 /** The hardware does not support this request. */
2310 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2311 /** The hardware returned an error. */
2312 public static final int ERROR_HARDWARE_ERROR = -31;
2313
2314 /** The NAT-T destination port for IPsec */
2315 public static final int NATT_PORT = 4500;
2316
2317 /** The minimum interval in seconds between keepalive packet transmissions */
2318 public static final int MIN_INTERVAL = 10;
2319
2320 private final Network mNetwork;
2321 private final ISocketKeepaliveCallback mCallback;
2322 private final ExecutorService mExecutor;
2323
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002324 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2325 public void stop() {
2326 try {
2327 mExecutor.execute(() -> {
2328 try {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002329 mService.stopKeepalive(mCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002330 } catch (RemoteException e) {
2331 Log.e(TAG, "Error stopping packet keepalive: ", e);
2332 throw e.rethrowFromSystemServer();
2333 }
2334 });
2335 } catch (RejectedExecutionException e) {
2336 // The internal executor has already stopped due to previous event.
2337 }
2338 }
2339
2340 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002341 Objects.requireNonNull(network, "network cannot be null");
2342 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002343 mNetwork = network;
2344 mExecutor = Executors.newSingleThreadExecutor();
2345 mCallback = new ISocketKeepaliveCallback.Stub() {
2346 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002347 public void onStarted() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002348 final long token = Binder.clearCallingIdentity();
2349 try {
2350 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002351 callback.onStarted();
2352 });
2353 } finally {
2354 Binder.restoreCallingIdentity(token);
2355 }
2356 }
2357
2358 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002359 public void onResumed() {
2360 final long token = Binder.clearCallingIdentity();
2361 try {
2362 mExecutor.execute(() -> {
2363 callback.onResumed();
2364 });
2365 } finally {
2366 Binder.restoreCallingIdentity(token);
2367 }
2368 }
2369
2370 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002371 public void onStopped() {
2372 final long token = Binder.clearCallingIdentity();
2373 try {
2374 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002375 callback.onStopped();
2376 });
2377 } finally {
2378 Binder.restoreCallingIdentity(token);
2379 }
2380 mExecutor.shutdown();
2381 }
2382
2383 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002384 public void onPaused() {
2385 final long token = Binder.clearCallingIdentity();
2386 try {
2387 mExecutor.execute(() -> {
2388 callback.onPaused();
2389 });
2390 } finally {
2391 Binder.restoreCallingIdentity(token);
2392 }
2393 mExecutor.shutdown();
2394 }
2395
2396 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002397 public void onError(int error) {
2398 final long token = Binder.clearCallingIdentity();
2399 try {
2400 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002401 callback.onError(error);
2402 });
2403 } finally {
2404 Binder.restoreCallingIdentity(token);
2405 }
2406 mExecutor.shutdown();
2407 }
2408
2409 @Override
2410 public void onDataReceived() {
2411 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2412 // this callback when data is received.
2413 }
2414 };
2415 }
2416 }
2417
2418 /**
2419 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2420 *
2421 * @deprecated Use {@link #createSocketKeepalive} instead.
2422 *
2423 * @hide
2424 */
2425 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2426 public PacketKeepalive startNattKeepalive(
2427 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2428 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2429 final PacketKeepalive k = new PacketKeepalive(network, callback);
2430 try {
2431 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2432 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2433 } catch (RemoteException e) {
2434 Log.e(TAG, "Error starting packet keepalive: ", e);
2435 throw e.rethrowFromSystemServer();
2436 }
2437 return k;
2438 }
2439
2440 // Construct an invalid fd.
2441 private ParcelFileDescriptor createInvalidFd() {
2442 final int invalidFd = -1;
2443 return ParcelFileDescriptor.adoptFd(invalidFd);
2444 }
2445
2446 /**
2447 * Request that keepalives be started on a IPsec NAT-T socket.
2448 *
2449 * @param network The {@link Network} the socket is on.
2450 * @param socket The socket that needs to be kept alive.
2451 * @param source The source address of the {@link UdpEncapsulationSocket}.
2452 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2453 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2454 * must run callback sequentially, otherwise the order of callbacks cannot be
2455 * guaranteed.
2456 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2457 * changes. Must be extended by applications that use this API.
2458 *
2459 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2460 * given socket.
2461 **/
2462 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2463 @NonNull UdpEncapsulationSocket socket,
2464 @NonNull InetAddress source,
2465 @NonNull InetAddress destination,
2466 @NonNull @CallbackExecutor Executor executor,
2467 @NonNull Callback callback) {
2468 ParcelFileDescriptor dup;
2469 try {
2470 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2471 // which cannot be obtained by the app process.
2472 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2473 } catch (IOException ignored) {
2474 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2475 // ERROR_INVALID_SOCKET.
2476 dup = createInvalidFd();
2477 }
2478 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2479 destination, executor, callback);
2480 }
2481
2482 /**
2483 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2484 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2485 *
2486 * @param network The {@link Network} the socket is on.
2487 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2488 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2489 * from that port.
2490 * @param source The source address of the {@link UdpEncapsulationSocket}.
2491 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2492 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2493 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2494 * must run callback sequentially, otherwise the order of callbacks cannot be
2495 * guaranteed.
2496 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2497 * changes. Must be extended by applications that use this API.
2498 *
2499 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2500 * given socket.
2501 * @hide
2502 */
2503 @SystemApi
2504 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2505 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2506 @NonNull ParcelFileDescriptor pfd,
2507 @NonNull InetAddress source,
2508 @NonNull InetAddress destination,
2509 @NonNull @CallbackExecutor Executor executor,
2510 @NonNull Callback callback) {
2511 ParcelFileDescriptor dup;
2512 try {
2513 // TODO: Consider remove unnecessary dup.
2514 dup = pfd.dup();
2515 } catch (IOException ignored) {
2516 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2517 // ERROR_INVALID_SOCKET.
2518 dup = createInvalidFd();
2519 }
2520 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002521 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002522 }
2523
2524 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002525 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002526 *
2527 * @param network The {@link Network} the socket is on.
2528 * @param socket The socket that needs to be kept alive.
2529 * @param executor The executor on which callback will be invoked. This implementation assumes
2530 * the provided {@link Executor} runs the callbacks in sequence with no
2531 * concurrency. Failing this, no guarantee of correctness can be made. It is
2532 * the responsibility of the caller to ensure the executor provides this
2533 * guarantee. A simple way of creating such an executor is with the standard
2534 * tool {@code Executors.newSingleThreadExecutor}.
2535 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2536 * changes. Must be extended by applications that use this API.
2537 *
2538 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2539 * given socket.
2540 * @hide
2541 */
2542 @SystemApi
2543 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2544 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2545 @NonNull Socket socket,
Sherri Lin443b7182023-02-08 04:49:29 +01002546 @NonNull @CallbackExecutor Executor executor,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002547 @NonNull Callback callback) {
2548 ParcelFileDescriptor dup;
2549 try {
2550 dup = ParcelFileDescriptor.fromSocket(socket);
2551 } catch (UncheckedIOException ignored) {
2552 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2553 // ERROR_INVALID_SOCKET.
2554 dup = createInvalidFd();
2555 }
2556 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2557 }
2558
2559 /**
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +09002560 * Get the supported keepalive count for each transport configured in resource overlays.
2561 *
2562 * @return An array of supported keepalive count for each transport type.
2563 * @hide
2564 */
2565 @RequiresPermission(anyOf = { android.Manifest.permission.NETWORK_SETTINGS,
2566 // CTS 13 used QUERY_ALL_PACKAGES to get the resource value, which was implemented
2567 // as below in KeepaliveUtils. Also allow that permission so that KeepaliveUtils can
2568 // use this method and avoid breaking released CTS. Apps that have this permission
2569 // can query the resource themselves anyway.
2570 android.Manifest.permission.QUERY_ALL_PACKAGES })
2571 public int[] getSupportedKeepalives() {
2572 try {
2573 return mService.getSupportedKeepalives();
2574 } catch (RemoteException e) {
2575 throw e.rethrowFromSystemServer();
2576 }
2577 }
2578
2579 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002580 * Ensure that a network route exists to deliver traffic to the specified
2581 * host via the specified network interface. An attempt to add a route that
2582 * already exists is ignored, but treated as successful.
2583 *
2584 * <p>This method requires the caller to hold either the
2585 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2586 * or the ability to modify system settings as determined by
2587 * {@link android.provider.Settings.System#canWrite}.</p>
2588 *
2589 * @param networkType the type of the network over which traffic to the specified
2590 * host is to be routed
2591 * @param hostAddress the IP address of the host to which the route is desired
2592 * @return {@code true} on success, {@code false} on failure
2593 *
2594 * @deprecated Deprecated in favor of the
2595 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2596 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2597 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2598 * throw {@code UnsupportedOperationException} if called.
2599 * @removed
2600 */
2601 @Deprecated
2602 public boolean requestRouteToHost(int networkType, int hostAddress) {
2603 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2604 }
2605
2606 /**
2607 * Ensure that a network route exists to deliver traffic to the specified
2608 * host via the specified network interface. An attempt to add a route that
2609 * already exists is ignored, but treated as successful.
2610 *
2611 * <p>This method requires the caller to hold either the
2612 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2613 * or the ability to modify system settings as determined by
2614 * {@link android.provider.Settings.System#canWrite}.</p>
2615 *
2616 * @param networkType the type of the network over which traffic to the specified
2617 * host is to be routed
2618 * @param hostAddress the IP address of the host to which the route is desired
2619 * @return {@code true} on success, {@code false} on failure
2620 * @hide
2621 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2622 * {@link #bindProcessToNetwork} API.
2623 */
2624 @Deprecated
2625 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002626 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002627 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2628 checkLegacyRoutingApiAccess();
2629 try {
2630 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2631 mContext.getOpPackageName(), getAttributionTag());
2632 } catch (RemoteException e) {
2633 throw e.rethrowFromSystemServer();
2634 }
2635 }
2636
2637 /**
2638 * @return the context's attribution tag
2639 */
2640 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2641 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002642 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002643 }
2644
2645 /**
2646 * Returns the value of the setting for background data usage. If false,
2647 * applications should not use the network if the application is not in the
2648 * foreground. Developers should respect this setting, and check the value
2649 * of this before performing any background data operations.
2650 * <p>
2651 * All applications that have background services that use the network
2652 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2653 * <p>
2654 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2655 * background data depends on several combined factors, and this method will
2656 * always return {@code true}. Instead, when background data is unavailable,
2657 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2658 *
2659 * @return Whether background data usage is allowed.
2660 */
2661 @Deprecated
2662 public boolean getBackgroundDataSetting() {
2663 // assume that background data is allowed; final authority is
2664 // NetworkInfo which may be blocked.
2665 return true;
2666 }
2667
2668 /**
2669 * Sets the value of the setting for background data usage.
2670 *
2671 * @param allowBackgroundData Whether an application should use data while
2672 * it is in the background.
2673 *
2674 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2675 * @see #getBackgroundDataSetting()
2676 * @hide
2677 */
2678 @Deprecated
2679 @UnsupportedAppUsage
2680 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2681 // ignored
2682 }
2683
2684 /**
2685 * @hide
2686 * @deprecated Talk to TelephonyManager directly
2687 */
2688 @Deprecated
2689 @UnsupportedAppUsage
2690 public boolean getMobileDataEnabled() {
2691 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2692 if (tm != null) {
2693 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2694 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2695 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2696 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2697 + " retVal=" + retVal);
2698 return retVal;
2699 }
2700 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2701 return false;
2702 }
2703
2704 /**
2705 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2706 * to find out when the system default network has gone in to a high power state.
2707 */
2708 public interface OnNetworkActiveListener {
2709 /**
2710 * Called on the main thread of the process to report that the current data network
2711 * has become active, and it is now a good time to perform any pending network
2712 * operations. Note that this listener only tells you when the network becomes
2713 * active; if at any other time you want to know whether it is active (and thus okay
2714 * to initiate network traffic), you can retrieve its instantaneous state with
2715 * {@link ConnectivityManager#isDefaultNetworkActive}.
2716 */
2717 void onNetworkActive();
2718 }
2719
Chiachang Wang2de41682021-09-23 10:46:03 +08002720 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002721 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2722 mNetworkActivityListeners = new ArrayMap<>();
2723
2724 /**
2725 * Start listening to reports when the system's default data network is active, meaning it is
2726 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2727 * to determine the current state of the system's default network after registering the
2728 * listener.
2729 * <p>
2730 * If the process default network has been set with
2731 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2732 * reflect the process's default, but the system default.
2733 *
2734 * @param l The listener to be told when the network is active.
2735 */
2736 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002737 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002738 @Override
2739 public void onNetworkActive() throws RemoteException {
2740 l.onNetworkActive();
2741 }
2742 };
2743
Chiachang Wang2de41682021-09-23 10:46:03 +08002744 synchronized (mNetworkActivityListeners) {
2745 try {
2746 mService.registerNetworkActivityListener(rl);
2747 mNetworkActivityListeners.put(l, rl);
2748 } catch (RemoteException e) {
2749 throw e.rethrowFromSystemServer();
2750 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002751 }
2752 }
2753
2754 /**
2755 * Remove network active listener previously registered with
2756 * {@link #addDefaultNetworkActiveListener}.
2757 *
2758 * @param l Previously registered listener.
2759 */
2760 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002761 synchronized (mNetworkActivityListeners) {
2762 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2763 if (rl == null) {
2764 throw new IllegalArgumentException("Listener was not registered.");
2765 }
2766 try {
2767 mService.unregisterNetworkActivityListener(rl);
2768 mNetworkActivityListeners.remove(l);
2769 } catch (RemoteException e) {
2770 throw e.rethrowFromSystemServer();
2771 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002772 }
2773 }
2774
2775 /**
2776 * Return whether the data network is currently active. An active network means that
2777 * it is currently in a high power state for performing data transmission. On some
2778 * types of networks, it may be expensive to move and stay in such a state, so it is
2779 * more power efficient to batch network traffic together when the radio is already in
2780 * this state. This method tells you whether right now is currently a good time to
2781 * initiate network traffic, as the network is already active.
2782 */
2783 public boolean isDefaultNetworkActive() {
2784 try {
lucaslin709eb842021-01-21 02:04:15 +08002785 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002786 } catch (RemoteException e) {
2787 throw e.rethrowFromSystemServer();
2788 }
2789 }
2790
2791 /**
2792 * {@hide}
2793 */
2794 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002795 this(context, service, true /* newStatic */);
2796 }
2797
2798 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002799 mContext = Objects.requireNonNull(context, "missing context");
2800 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002801 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2802 // different ConnectivityManager, but that's still OK considering its usage.
2803 if (sInstance == null && newStatic) {
2804 final Context appContext = mContext.getApplicationContext();
2805 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2806 // If the application context is null, we're either in the system process or
2807 // it's the application context very early in app initialization. In both these
2808 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2809 // service. http://b/27532714 .
2810 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2811 false /* newStatic */);
2812 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002813 }
2814
2815 /** {@hide} */
2816 @UnsupportedAppUsage
2817 public static ConnectivityManager from(Context context) {
2818 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2819 }
2820
2821 /** @hide */
2822 public NetworkRequest getDefaultRequest() {
2823 try {
2824 // This is not racy as the default request is final in ConnectivityService.
2825 return mService.getDefaultRequest();
2826 } catch (RemoteException e) {
2827 throw e.rethrowFromSystemServer();
2828 }
2829 }
2830
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002831 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002832 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002833 * happened.
2834 *
2835 * @return {@code true} iff the package is allowed to write settings.
2836 */
2837 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2838 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2839 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2840 boolean throwException) {
2841 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002842 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002843 }
2844
2845 /**
2846 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2847 * situations where a Context pointer is unavailable.
2848 * @hide
2849 */
2850 @Deprecated
2851 static ConnectivityManager getInstanceOrNull() {
2852 return sInstance;
2853 }
2854
2855 /**
2856 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2857 * situations where a Context pointer is unavailable.
2858 * @hide
2859 */
2860 @Deprecated
2861 @UnsupportedAppUsage
2862 private static ConnectivityManager getInstance() {
2863 if (getInstanceOrNull() == null) {
2864 throw new IllegalStateException("No ConnectivityManager yet constructed");
2865 }
2866 return getInstanceOrNull();
2867 }
2868
2869 /**
2870 * Get the set of tetherable, available interfaces. This list is limited by
2871 * device configuration and current interface existence.
2872 *
2873 * @return an array of 0 or more Strings of tetherable interface names.
2874 *
2875 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2876 * {@hide}
2877 */
2878 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2879 @UnsupportedAppUsage
2880 @Deprecated
2881 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002882 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002883 }
2884
2885 /**
2886 * Get the set of tethered interfaces.
2887 *
2888 * @return an array of 0 or more String of currently tethered interface names.
2889 *
2890 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2891 * {@hide}
2892 */
2893 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2894 @UnsupportedAppUsage
2895 @Deprecated
2896 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002897 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002898 }
2899
2900 /**
2901 * Get the set of interface names which attempted to tether but
2902 * failed. Re-attempting to tether may cause them to reset to the Tethered
2903 * state. Alternatively, causing the interface to be destroyed and recreated
2904 * may cause them to reset to the available state.
2905 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2906 * information on the cause of the errors.
2907 *
2908 * @return an array of 0 or more String indicating the interface names
2909 * which failed to tether.
2910 *
2911 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2912 * {@hide}
2913 */
2914 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2915 @UnsupportedAppUsage
2916 @Deprecated
2917 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002918 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002919 }
2920
2921 /**
2922 * Get the set of tethered dhcp ranges.
2923 *
2924 * @deprecated This method is not supported.
2925 * TODO: remove this function when all of clients are removed.
2926 * {@hide}
2927 */
2928 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2929 @Deprecated
2930 public String[] getTetheredDhcpRanges() {
2931 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2932 }
2933
2934 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002935 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002936 * on the interface, forward and NAT IP packets and forward DNS requests
2937 * to the best active upstream network interface. Note that if no upstream
2938 * IP network interface is available, dhcp will still run and traffic will be
2939 * allowed between the tethered devices and this device, though upstream net
2940 * access will of course fail until an upstream network interface becomes
2941 * active.
2942 *
2943 * <p>This method requires the caller to hold either the
2944 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2945 * or the ability to modify system settings as determined by
2946 * {@link android.provider.Settings.System#canWrite}.</p>
2947 *
2948 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2949 * and WifiStateMachine which need direct access. All other clients should use
2950 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2951 * logic.</p>
2952 *
2953 * @param iface the interface name to tether.
2954 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2955 * @deprecated Use {@link TetheringManager#startTethering} instead
2956 *
2957 * {@hide}
2958 */
2959 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2960 @Deprecated
2961 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002962 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002963 }
2964
2965 /**
2966 * Stop tethering the named interface.
2967 *
2968 * <p>This method requires the caller to hold either the
2969 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2970 * or the ability to modify system settings as determined by
2971 * {@link android.provider.Settings.System#canWrite}.</p>
2972 *
2973 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2974 * and WifiStateMachine which need direct access. All other clients should use
2975 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2976 * logic.</p>
2977 *
2978 * @param iface the interface name to untether.
2979 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2980 *
2981 * {@hide}
2982 */
2983 @UnsupportedAppUsage
2984 @Deprecated
2985 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002986 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002987 }
2988
2989 /**
2990 * Check if the device allows for tethering. It may be disabled via
2991 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2992 * due to device configuration.
2993 *
2994 * <p>If this app does not have permission to use this API, it will always
2995 * return false rather than throw an exception.</p>
2996 *
2997 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2998 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2999 *
3000 * <p>Otherwise, this method requires the caller to hold the ability to modify system
3001 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
3002 *
3003 * @return a boolean - {@code true} indicating Tethering is supported.
3004 *
3005 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
3006 * {@hide}
3007 */
3008 @SystemApi
3009 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
3010 android.Manifest.permission.WRITE_SETTINGS})
3011 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003012 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003013 }
3014
3015 /**
3016 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
3017 *
3018 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
3019 * @hide
3020 */
3021 @SystemApi
3022 @Deprecated
3023 public static abstract class OnStartTetheringCallback {
3024 /**
3025 * Called when tethering has been successfully started.
3026 */
3027 public void onTetheringStarted() {}
3028
3029 /**
3030 * Called when starting tethering failed.
3031 */
3032 public void onTetheringFailed() {}
3033 }
3034
3035 /**
3036 * Convenient overload for
3037 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
3038 * handler to run on the current thread's {@link Looper}.
3039 *
3040 * @deprecated Use {@link TetheringManager#startTethering} instead.
3041 * @hide
3042 */
3043 @SystemApi
3044 @Deprecated
3045 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3046 public void startTethering(int type, boolean showProvisioningUi,
3047 final OnStartTetheringCallback callback) {
3048 startTethering(type, showProvisioningUi, callback, null);
3049 }
3050
3051 /**
3052 * Runs tether provisioning for the given type if needed and then starts tethering if
3053 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
3054 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
3055 * schedules tether provisioning re-checks if appropriate.
3056 *
3057 * @param type The type of tethering to start. Must be one of
3058 * {@link ConnectivityManager.TETHERING_WIFI},
3059 * {@link ConnectivityManager.TETHERING_USB}, or
3060 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3061 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
3062 * is one. This should be true the first time this function is called and also any time
3063 * the user can see this UI. It gives users information from their carrier about the
3064 * check failing and how they can sign up for tethering if possible.
3065 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
3066 * of the result of trying to tether.
3067 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3068 *
3069 * @deprecated Use {@link TetheringManager#startTethering} instead.
3070 * @hide
3071 */
3072 @SystemApi
3073 @Deprecated
3074 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3075 public void startTethering(int type, boolean showProvisioningUi,
3076 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003077 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003078
3079 final Executor executor = new Executor() {
3080 @Override
3081 public void execute(Runnable command) {
3082 if (handler == null) {
3083 command.run();
3084 } else {
3085 handler.post(command);
3086 }
3087 }
3088 };
3089
3090 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
3091 @Override
3092 public void onTetheringStarted() {
3093 callback.onTetheringStarted();
3094 }
3095
3096 @Override
3097 public void onTetheringFailed(final int error) {
3098 callback.onTetheringFailed();
3099 }
3100 };
3101
3102 final TetheringRequest request = new TetheringRequest.Builder(type)
3103 .setShouldShowEntitlementUi(showProvisioningUi).build();
3104
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003105 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003106 }
3107
3108 /**
3109 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
3110 * applicable.
3111 *
3112 * @param type The type of tethering to stop. Must be one of
3113 * {@link ConnectivityManager.TETHERING_WIFI},
3114 * {@link ConnectivityManager.TETHERING_USB}, or
3115 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3116 *
3117 * @deprecated Use {@link TetheringManager#stopTethering} instead.
3118 * @hide
3119 */
3120 @SystemApi
3121 @Deprecated
3122 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3123 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003124 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003125 }
3126
3127 /**
3128 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
3129 * upstream status.
3130 *
3131 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
3132 * @hide
3133 */
3134 @SystemApi
3135 @Deprecated
3136 public abstract static class OnTetheringEventCallback {
3137
3138 /**
3139 * Called when tethering upstream changed. This can be called multiple times and can be
3140 * called any time.
3141 *
3142 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
3143 * have any upstream.
3144 */
3145 public void onUpstreamChanged(@Nullable Network network) {}
3146 }
3147
3148 @GuardedBy("mTetheringEventCallbacks")
3149 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
3150 mTetheringEventCallbacks = new ArrayMap<>();
3151
3152 /**
3153 * Start listening to tethering change events. Any new added callback will receive the last
3154 * tethering status right away. If callback is registered when tethering has no upstream or
3155 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3156 * with a null argument. The same callback object cannot be registered twice.
3157 *
3158 * @param executor the executor on which callback will be invoked.
3159 * @param callback the callback to be called when tethering has change events.
3160 *
3161 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3162 * @hide
3163 */
3164 @SystemApi
3165 @Deprecated
3166 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3167 public void registerTetheringEventCallback(
3168 @NonNull @CallbackExecutor Executor executor,
3169 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003170 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003171
3172 final TetheringEventCallback tetherCallback =
3173 new TetheringEventCallback() {
3174 @Override
3175 public void onUpstreamChanged(@Nullable Network network) {
3176 callback.onUpstreamChanged(network);
3177 }
3178 };
3179
3180 synchronized (mTetheringEventCallbacks) {
3181 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003182 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003183 }
3184 }
3185
3186 /**
3187 * Remove tethering event callback previously registered with
3188 * {@link #registerTetheringEventCallback}.
3189 *
3190 * @param callback previously registered callback.
3191 *
3192 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3193 * @hide
3194 */
3195 @SystemApi
3196 @Deprecated
3197 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3198 public void unregisterTetheringEventCallback(
3199 @NonNull final OnTetheringEventCallback callback) {
3200 Objects.requireNonNull(callback, "The callback must be non-null");
3201 synchronized (mTetheringEventCallbacks) {
3202 final TetheringEventCallback tetherCallback =
3203 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003204 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003205 }
3206 }
3207
3208
3209 /**
3210 * Get the list of regular expressions that define any tetherable
3211 * USB network interfaces. If USB tethering is not supported by the
3212 * device, this list should be empty.
3213 *
3214 * @return an array of 0 or more regular expression Strings defining
3215 * what interfaces are considered tetherable usb interfaces.
3216 *
3217 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3218 * {@hide}
3219 */
3220 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3221 @UnsupportedAppUsage
3222 @Deprecated
3223 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003224 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003225 }
3226
3227 /**
3228 * Get the list of regular expressions that define any tetherable
3229 * Wifi network interfaces. If Wifi tethering is not supported by the
3230 * device, this list should be empty.
3231 *
3232 * @return an array of 0 or more regular expression Strings defining
3233 * what interfaces are considered tetherable wifi interfaces.
3234 *
3235 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3236 * {@hide}
3237 */
3238 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3239 @UnsupportedAppUsage
3240 @Deprecated
3241 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003242 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003243 }
3244
3245 /**
3246 * Get the list of regular expressions that define any tetherable
3247 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3248 * device, this list should be empty.
3249 *
3250 * @return an array of 0 or more regular expression Strings defining
3251 * what interfaces are considered tetherable bluetooth interfaces.
3252 *
3253 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3254 *TetheringManager.TetheringInterfaceRegexps)} instead.
3255 * {@hide}
3256 */
3257 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3258 @UnsupportedAppUsage
3259 @Deprecated
3260 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003261 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003262 }
3263
3264 /**
3265 * Attempt to both alter the mode of USB and Tethering of USB. A
3266 * utility method to deal with some of the complexity of USB - will
3267 * attempt to switch to Rndis and subsequently tether the resulting
3268 * interface on {@code true} or turn off tethering and switch off
3269 * Rndis on {@code false}.
3270 *
3271 * <p>This method requires the caller to hold either the
3272 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3273 * or the ability to modify system settings as determined by
3274 * {@link android.provider.Settings.System#canWrite}.</p>
3275 *
3276 * @param enable a boolean - {@code true} to enable tethering
3277 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3278 * @deprecated Use {@link TetheringManager#startTethering} instead
3279 *
3280 * {@hide}
3281 */
3282 @UnsupportedAppUsage
3283 @Deprecated
3284 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003285 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003286 }
3287
3288 /**
3289 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3290 * {@hide}
3291 */
3292 @SystemApi
3293 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003294 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003295 /**
3296 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3297 * {@hide}
3298 */
3299 @Deprecated
3300 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3301 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3302 /**
3303 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3304 * {@hide}
3305 */
3306 @Deprecated
3307 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3308 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3309 /**
3310 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3311 * {@hide}
3312 */
3313 @Deprecated
3314 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3315 /**
3316 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3317 * {@hide}
3318 */
3319 @Deprecated
3320 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3321 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3322 /**
3323 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3324 * {@hide}
3325 */
3326 @Deprecated
3327 public static final int TETHER_ERROR_MASTER_ERROR =
3328 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3329 /**
3330 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3331 * {@hide}
3332 */
3333 @Deprecated
3334 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3335 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3336 /**
3337 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3338 * {@hide}
3339 */
3340 @Deprecated
3341 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3342 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3343 /**
3344 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3345 * {@hide}
3346 */
3347 @Deprecated
3348 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3349 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3350 /**
3351 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3352 * {@hide}
3353 */
3354 @Deprecated
3355 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3356 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3357 /**
3358 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3359 * {@hide}
3360 */
3361 @Deprecated
3362 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3363 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3364 /**
3365 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3366 * {@hide}
3367 */
3368 @SystemApi
3369 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003370 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003371 /**
3372 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3373 * {@hide}
3374 */
3375 @Deprecated
3376 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3377 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3378 /**
3379 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3380 * {@hide}
3381 */
3382 @SystemApi
3383 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003384 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003385
3386 /**
3387 * Get a more detailed error code after a Tethering or Untethering
3388 * request asynchronously failed.
3389 *
3390 * @param iface The name of the interface of interest
3391 * @return error The error code of the last error tethering or untethering the named
3392 * interface
3393 *
3394 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3395 * {@hide}
3396 */
3397 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3398 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3399 @Deprecated
3400 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003401 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003402 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3403 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3404 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3405 // instead.
3406 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3407 }
3408 return error;
3409 }
3410
3411 /** @hide */
3412 @Retention(RetentionPolicy.SOURCE)
3413 @IntDef(value = {
3414 TETHER_ERROR_NO_ERROR,
3415 TETHER_ERROR_PROVISION_FAILED,
3416 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3417 })
3418 public @interface EntitlementResultCode {
3419 }
3420
3421 /**
3422 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3423 * entitlement succeeded.
3424 *
3425 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3426 * @hide
3427 */
3428 @SystemApi
3429 @Deprecated
3430 public interface OnTetheringEntitlementResultListener {
3431 /**
3432 * Called to notify entitlement result.
3433 *
3434 * @param resultCode an int value of entitlement result. It may be one of
3435 * {@link #TETHER_ERROR_NO_ERROR},
3436 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3437 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3438 */
3439 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3440 }
3441
3442 /**
3443 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003444 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3445 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003446 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003447 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003448 * any reason will update the cached value.
3449 *
3450 * @param type the downstream type of tethering. Must be one of
3451 * {@link #TETHERING_WIFI},
3452 * {@link #TETHERING_USB}, or
3453 * {@link #TETHERING_BLUETOOTH}.
3454 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3455 * @param executor the executor on which callback will be invoked.
3456 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3457 * notify the caller of the result of entitlement check. The listener may be called zero
3458 * or one time.
3459 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3460 * {@hide}
3461 */
3462 @SystemApi
3463 @Deprecated
3464 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3465 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3466 @NonNull @CallbackExecutor Executor executor,
3467 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003468 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003469 ResultReceiver wrappedListener = new ResultReceiver(null) {
3470 @Override
3471 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003472 final long token = Binder.clearCallingIdentity();
3473 try {
3474 executor.execute(() -> {
3475 listener.onTetheringEntitlementResult(resultCode);
3476 });
3477 } finally {
3478 Binder.restoreCallingIdentity(token);
3479 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003480 }
3481 };
3482
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003483 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003484 showEntitlementUi);
3485 }
3486
3487 /**
3488 * Report network connectivity status. This is currently used only
3489 * to alter status bar UI.
3490 * <p>This method requires the caller to hold the permission
3491 * {@link android.Manifest.permission#STATUS_BAR}.
3492 *
3493 * @param networkType The type of network you want to report on
3494 * @param percentage The quality of the connection 0 is bad, 100 is good
3495 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3496 * {@hide}
3497 */
3498 public void reportInetCondition(int networkType, int percentage) {
3499 printStackTrace();
3500 try {
3501 mService.reportInetCondition(networkType, percentage);
3502 } catch (RemoteException e) {
3503 throw e.rethrowFromSystemServer();
3504 }
3505 }
3506
3507 /**
3508 * Report a problem network to the framework. This provides a hint to the system
3509 * that there might be connectivity problems on this network and may cause
3510 * the framework to re-evaluate network connectivity and/or switch to another
3511 * network.
3512 *
3513 * @param network The {@link Network} the application was attempting to use
3514 * or {@code null} to indicate the current default network.
3515 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3516 * working and non-working connectivity.
3517 */
3518 @Deprecated
3519 public void reportBadNetwork(@Nullable Network network) {
3520 printStackTrace();
3521 try {
3522 // One of these will be ignored because it matches system's current state.
3523 // The other will trigger the necessary reevaluation.
3524 mService.reportNetworkConnectivity(network, true);
3525 mService.reportNetworkConnectivity(network, false);
3526 } catch (RemoteException e) {
3527 throw e.rethrowFromSystemServer();
3528 }
3529 }
3530
3531 /**
3532 * Report to the framework whether a network has working connectivity.
3533 * This provides a hint to the system that a particular network is providing
3534 * working connectivity or not. In response the framework may re-evaluate
3535 * the network's connectivity and might take further action thereafter.
3536 *
3537 * @param network The {@link Network} the application was attempting to use
3538 * or {@code null} to indicate the current default network.
3539 * @param hasConnectivity {@code true} if the application was able to successfully access the
3540 * Internet using {@code network} or {@code false} if not.
3541 */
3542 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3543 printStackTrace();
3544 try {
3545 mService.reportNetworkConnectivity(network, hasConnectivity);
3546 } catch (RemoteException e) {
3547 throw e.rethrowFromSystemServer();
3548 }
3549 }
3550
3551 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003552 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003553 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003554 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3555 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3556 * accessing any network, regardless of what the settings for that network are.
3557 *
3558 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3559 * proxy is likely to break networking on multiple networks. This method is only meant
3560 * for device policy clients looking to do general internal filtering or similar use cases.
3561 *
chiachangwang9473c592022-07-15 02:25:52 +00003562 * @see #getGlobalProxy
3563 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003564 *
3565 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3566 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003567 * @hide
3568 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003569 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003570 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003571 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003572 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003573 try {
3574 mService.setGlobalProxy(p);
3575 } catch (RemoteException e) {
3576 throw e.rethrowFromSystemServer();
3577 }
3578 }
3579
3580 /**
3581 * Retrieve any network-independent global HTTP proxy.
3582 *
3583 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3584 * if no global HTTP proxy is set.
3585 * @hide
3586 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003587 @SystemApi(client = MODULE_LIBRARIES)
3588 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003589 public ProxyInfo getGlobalProxy() {
3590 try {
3591 return mService.getGlobalProxy();
3592 } catch (RemoteException e) {
3593 throw e.rethrowFromSystemServer();
3594 }
3595 }
3596
3597 /**
3598 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3599 * network-specific HTTP proxy. If {@code network} is null, the
3600 * network-specific proxy returned is the proxy of the default active
3601 * network.
3602 *
3603 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3604 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3605 * or when {@code network} is {@code null},
3606 * the {@code ProxyInfo} for the default active network. Returns
3607 * {@code null} when no proxy applies or the caller doesn't have
3608 * permission to use {@code network}.
3609 * @hide
3610 */
3611 public ProxyInfo getProxyForNetwork(Network network) {
3612 try {
3613 return mService.getProxyForNetwork(network);
3614 } catch (RemoteException e) {
3615 throw e.rethrowFromSystemServer();
3616 }
3617 }
3618
3619 /**
3620 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3621 * otherwise if this process is bound to a {@link Network} using
3622 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3623 * the default network's proxy is returned.
3624 *
3625 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3626 * HTTP proxy is active.
3627 */
3628 @Nullable
3629 public ProxyInfo getDefaultProxy() {
3630 return getProxyForNetwork(getBoundNetworkForProcess());
3631 }
3632
3633 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003634 * Returns whether the hardware supports the given network type.
3635 *
3636 * This doesn't indicate there is coverage or such a network is available, just whether the
3637 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3638 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003639 *
3640 * @param networkType The network type we'd like to check
3641 * @return {@code true} if supported, else {@code false}
3642 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3643 * @hide
3644 */
3645 @Deprecated
3646 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3647 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3648 public boolean isNetworkSupported(int networkType) {
3649 try {
3650 return mService.isNetworkSupported(networkType);
3651 } catch (RemoteException e) {
3652 throw e.rethrowFromSystemServer();
3653 }
3654 }
3655
3656 /**
3657 * Returns if the currently active data network is metered. A network is
3658 * classified as metered when the user is sensitive to heavy data usage on
3659 * that connection due to monetary costs, data limitations or
3660 * battery/performance issues. You should check this before doing large
3661 * data transfers, and warn the user or delay the operation until another
3662 * network is available.
3663 *
3664 * @return {@code true} if large transfers should be avoided, otherwise
3665 * {@code false}.
3666 */
3667 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3668 public boolean isActiveNetworkMetered() {
3669 try {
3670 return mService.isActiveNetworkMetered();
3671 } catch (RemoteException e) {
3672 throw e.rethrowFromSystemServer();
3673 }
3674 }
3675
3676 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003677 * Set sign in error notification to visible or invisible
3678 *
3679 * @hide
3680 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3681 */
3682 @Deprecated
3683 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3684 String action) {
3685 try {
3686 mService.setProvisioningNotificationVisible(visible, networkType, action);
3687 } catch (RemoteException e) {
3688 throw e.rethrowFromSystemServer();
3689 }
3690 }
3691
3692 /**
3693 * Set the value for enabling/disabling airplane mode
3694 *
3695 * @param enable whether to enable airplane mode or not
3696 *
3697 * @hide
3698 */
3699 @RequiresPermission(anyOf = {
3700 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3701 android.Manifest.permission.NETWORK_SETTINGS,
3702 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3703 android.Manifest.permission.NETWORK_STACK})
3704 @SystemApi
3705 public void setAirplaneMode(boolean enable) {
3706 try {
3707 mService.setAirplaneMode(enable);
3708 } catch (RemoteException e) {
3709 throw e.rethrowFromSystemServer();
3710 }
3711 }
3712
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003713 /**
3714 * Registers the specified {@link NetworkProvider}.
3715 * Each listener must only be registered once. The listener can be unregistered with
3716 * {@link #unregisterNetworkProvider}.
3717 *
3718 * @param provider the provider to register
3719 * @return the ID of the provider. This ID must be used by the provider when registering
3720 * {@link android.net.NetworkAgent}s.
3721 * @hide
3722 */
3723 @SystemApi
3724 @RequiresPermission(anyOf = {
3725 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3726 android.Manifest.permission.NETWORK_FACTORY})
3727 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3728 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3729 throw new IllegalStateException("NetworkProviders can only be registered once");
3730 }
3731
3732 try {
3733 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3734 provider.getName());
3735 provider.setProviderId(providerId);
3736 } catch (RemoteException e) {
3737 throw e.rethrowFromSystemServer();
3738 }
3739 return provider.getProviderId();
3740 }
3741
3742 /**
3743 * Unregisters the specified NetworkProvider.
3744 *
3745 * @param provider the provider to unregister
3746 * @hide
3747 */
3748 @SystemApi
3749 @RequiresPermission(anyOf = {
3750 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3751 android.Manifest.permission.NETWORK_FACTORY})
3752 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3753 try {
3754 mService.unregisterNetworkProvider(provider.getMessenger());
3755 } catch (RemoteException e) {
3756 throw e.rethrowFromSystemServer();
3757 }
3758 provider.setProviderId(NetworkProvider.ID_NONE);
3759 }
3760
Chalard Jeand1b498b2021-01-05 08:40:09 +09003761 /**
3762 * Register or update a network offer with ConnectivityService.
3763 *
3764 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003765 * them to networking requests made by apps or the system. A callback identifies an offer
3766 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3767 * score and the capabilities of the network it might be able to bring up ; these act as
3768 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003769 * provider.
3770 *
3771 * The provider is under no obligation to be able to bring up the network it offers at any
3772 * given time. Instead, this mechanism is meant to limit requests received by providers
3773 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3774 * the quality of the network satisfying a given request to their own offer.
3775 *
3776 * An offer can be updated by calling this again with the same callback object. This is
3777 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3778 * provider with the changes caused by the changes in the offer.
3779 *
3780 * @param provider The provider making this offer.
3781 * @param score The prospective score of the network.
3782 * @param caps The prospective capabilities of the network.
3783 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003784 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003785 */
3786 @RequiresPermission(anyOf = {
3787 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3788 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003789 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003790 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3791 @NonNull final INetworkOfferCallback callback) {
3792 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003793 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003794 Objects.requireNonNull(score, "null score"),
3795 Objects.requireNonNull(caps, "null caps"),
3796 Objects.requireNonNull(callback, "null callback"));
3797 } catch (RemoteException e) {
3798 throw e.rethrowFromSystemServer();
3799 }
3800 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003801
Chalard Jeand1b498b2021-01-05 08:40:09 +09003802 /**
3803 * Withdraw a network offer made with {@link #offerNetwork}.
3804 *
3805 * @param callback The callback passed at registration time. This must be the same object
3806 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003807 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003808 */
3809 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3810 try {
3811 mService.unofferNetwork(Objects.requireNonNull(callback));
3812 } catch (RemoteException e) {
3813 throw e.rethrowFromSystemServer();
3814 }
3815 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003816 /** @hide exposed via the NetworkProvider class. */
3817 @RequiresPermission(anyOf = {
3818 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3819 android.Manifest.permission.NETWORK_FACTORY})
3820 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3821 try {
3822 mService.declareNetworkRequestUnfulfillable(request);
3823 } catch (RemoteException e) {
3824 throw e.rethrowFromSystemServer();
3825 }
3826 }
3827
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003828 /**
3829 * @hide
3830 * Register a NetworkAgent with ConnectivityService.
3831 * @return Network corresponding to NetworkAgent.
3832 */
3833 @RequiresPermission(anyOf = {
3834 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3835 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003836 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3837 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3838 @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId) {
3839 return registerNetworkAgent(na, ni, lp, nc, null /* localNetworkConfig */, score, config,
3840 providerId);
3841 }
3842
3843 /**
3844 * @hide
3845 * Register a NetworkAgent with ConnectivityService.
3846 * @return Network corresponding to NetworkAgent.
3847 */
3848 @RequiresPermission(anyOf = {
3849 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3850 android.Manifest.permission.NETWORK_FACTORY})
3851 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3852 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3853 @Nullable LocalNetworkConfig localNetworkConfig, @NonNull NetworkScore score,
3854 @NonNull NetworkAgentConfig config, int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003855 try {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003856 return mService.registerNetworkAgent(na, ni, lp, nc, score, localNetworkConfig, config,
3857 providerId);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003858 } catch (RemoteException e) {
3859 throw e.rethrowFromSystemServer();
3860 }
3861 }
3862
3863 /**
3864 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3865 * changes. Should be extended by applications wanting notifications.
3866 *
3867 * A {@code NetworkCallback} is registered by calling
3868 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3869 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3870 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3871 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3872 * A {@code NetworkCallback} should be registered at most once at any time.
3873 * A {@code NetworkCallback} that has been unregistered can be registered again.
3874 */
3875 public static class NetworkCallback {
3876 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003877 * No flags associated with this callback.
3878 * @hide
3879 */
3880 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003881
Roshan Piuse08bc182020-12-22 15:10:42 -08003882 /**
lucaslinc582d502022-01-27 09:07:00 +08003883 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3884 *
3885 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3886 * Prior to Android 12, this information is always returned to apps holding the appropriate
3887 * permission, possibly noting that the app has used location.
3888 * <p>In Android 12 and above, by default the sent objects do not contain any location
3889 * information, even if the app holds the necessary permissions, and the system does not
3890 * take note of location usage by the app. Apps can request that location information is
3891 * included, in which case the system will check location permission and the location
3892 * toggle state, and take note of location usage by the app if any such information is
3893 * returned.
3894 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003895 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3896 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3897 * <p>
3898 * These include:
3899 * <li> Some transport info instances (retrieved via
3900 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3901 * contain location sensitive information.
3902 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003903 * sensitive for wifi suggestor apps (i.e using
3904 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003905 * </p>
3906 * <p>
3907 * Note:
3908 * <li> Retrieving this location sensitive information (subject to app's location
3909 * permissions) will be noted by system. </li>
3910 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003911 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003912 */
Roshan Pius189d0092021-03-11 21:16:44 -08003913 // Note: Some existing fields which are location sensitive may still be included without
3914 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003915 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3916
3917 /** @hide */
3918 @Retention(RetentionPolicy.SOURCE)
3919 @IntDef(flag = true, prefix = "FLAG_", value = {
3920 FLAG_NONE,
3921 FLAG_INCLUDE_LOCATION_INFO
3922 })
3923 public @interface Flag { }
3924
3925 /**
3926 * All the valid flags for error checking.
3927 */
3928 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3929
3930 public NetworkCallback() {
3931 this(FLAG_NONE);
3932 }
3933
3934 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003935 if ((flags & VALID_FLAGS) != flags) {
3936 throw new IllegalArgumentException("Invalid flags");
3937 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003938 mFlags = flags;
3939 }
3940
3941 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003942 * Called when the framework connects to a new network to evaluate whether it satisfies this
3943 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3944 * callback. There is no guarantee that this new network will satisfy any requests, or that
3945 * the network will stay connected for longer than the time necessary to evaluate it.
3946 * <p>
3947 * Most applications <b>should not</b> act on this callback, and should instead use
3948 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3949 * the framework in properly evaluating the network &mdash; for example, an application that
3950 * can automatically log in to a captive portal without user intervention.
3951 *
3952 * @param network The {@link Network} of the network that is being evaluated.
3953 *
3954 * @hide
3955 */
3956 public void onPreCheck(@NonNull Network network) {}
3957
3958 /**
3959 * Called when the framework connects and has declared a new network ready for use.
3960 * This callback may be called more than once if the {@link Network} that is
3961 * satisfying the request changes.
3962 *
3963 * @param network The {@link Network} of the satisfying network.
3964 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3965 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3966 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3967 * @hide
3968 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003969 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003970 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003971 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003972 // Internally only this method is called when a new network is available, and
3973 // it calls the callback in the same way and order that older versions used
3974 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003975 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3976 onBlockedStatusChanged(network, blocked);
3977 }
3978
3979 /**
3980 * Legacy variant of onAvailable that takes a boolean blocked reason.
3981 *
3982 * This method has never been public API, but it's not final, so there may be apps that
3983 * implemented it and rely on it being called. Do our best not to break them.
3984 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3985 * this method is called. There does not seem to be a way to avoid this.
3986 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3987 *
3988 * @hide
3989 */
3990 public void onAvailable(@NonNull Network network,
3991 @NonNull NetworkCapabilities networkCapabilities,
3992 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003993 onAvailable(network);
3994 if (!networkCapabilities.hasCapability(
3995 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3996 onNetworkSuspended(network);
3997 }
3998 onCapabilitiesChanged(network, networkCapabilities);
3999 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004000 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004001 }
4002
4003 /**
4004 * Called when the framework connects and has declared a new network ready for use.
4005 *
4006 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
4007 * be available at the same time, and onAvailable will be called for each of these as they
4008 * appear.
4009 *
4010 * <p>For callbacks registered with {@link #requestNetwork} and
4011 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
4012 * is the new best network for this request and is now tracked by this callback ; this
4013 * callback will no longer receive method calls about other networks that may have been
4014 * passed to this method previously. The previously-best network may have disconnected, or
4015 * it may still be around and the newly-best network may simply be better.
4016 *
4017 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
4018 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
4019 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
4020 * to {@link #onBlockedStatusChanged(Network, boolean)}.
4021 *
4022 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4023 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4024 * this callback as this is prone to race conditions (there is no guarantee the objects
4025 * returned by these methods will be current). Instead, wait for a call to
4026 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
4027 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
4028 * to be well-ordered with respect to other callbacks.
4029 *
4030 * @param network The {@link Network} of the satisfying network.
4031 */
4032 public void onAvailable(@NonNull Network network) {}
4033
4034 /**
4035 * Called when the network is about to be lost, typically because there are no outstanding
4036 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
4037 * with the new replacement network for graceful handover. This method is not guaranteed
4038 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
4039 * network is suddenly disconnected.
4040 *
4041 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4042 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4043 * this callback as this is prone to race conditions ; calling these methods while in a
4044 * callback may return an outdated or even a null object.
4045 *
4046 * @param network The {@link Network} that is about to be lost.
4047 * @param maxMsToLive The time in milliseconds the system intends to keep the network
4048 * connected for graceful handover; note that the network may still
4049 * suffer a hard loss at any time.
4050 */
4051 public void onLosing(@NonNull Network network, int maxMsToLive) {}
4052
4053 /**
4054 * Called when a network disconnects or otherwise no longer satisfies this request or
4055 * callback.
4056 *
4057 * <p>If the callback was registered with requestNetwork() or
4058 * registerDefaultNetworkCallback(), it will only be invoked against the last network
4059 * returned by onAvailable() when that network is lost and no other network satisfies
4060 * the criteria of the request.
4061 *
4062 * <p>If the callback was registered with registerNetworkCallback() it will be called for
4063 * each network which no longer satisfies the criteria of the callback.
4064 *
4065 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4066 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4067 * this callback as this is prone to race conditions ; calling these methods while in a
4068 * callback may return an outdated or even a null object.
4069 *
4070 * @param network The {@link Network} lost.
4071 */
4072 public void onLost(@NonNull Network network) {}
4073
4074 /**
4075 * Called if no network is found within the timeout time specified in
4076 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
4077 * requested network request cannot be fulfilled (whether or not a timeout was
4078 * specified). When this callback is invoked the associated
4079 * {@link NetworkRequest} will have already been removed and released, as if
4080 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
4081 */
4082 public void onUnavailable() {}
4083
4084 /**
4085 * Called when the network corresponding to this request changes capabilities but still
4086 * satisfies the requested criteria.
4087 *
4088 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4089 * to be called immediately after {@link #onAvailable}.
4090 *
4091 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
4092 * ConnectivityManager methods in this callback as this is prone to race conditions :
4093 * calling these methods while in a callback may return an outdated or even a null object.
4094 *
4095 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08004096 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004097 * network.
4098 */
4099 public void onCapabilitiesChanged(@NonNull Network network,
4100 @NonNull NetworkCapabilities networkCapabilities) {}
4101
4102 /**
4103 * Called when the network corresponding to this request changes {@link LinkProperties}.
4104 *
4105 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4106 * to be called immediately after {@link #onAvailable}.
4107 *
4108 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
4109 * ConnectivityManager methods in this callback as this is prone to race conditions :
4110 * calling these methods while in a callback may return an outdated or even a null object.
4111 *
4112 * @param network The {@link Network} whose link properties have changed.
4113 * @param linkProperties The new {@link LinkProperties} for this network.
4114 */
4115 public void onLinkPropertiesChanged(@NonNull Network network,
4116 @NonNull LinkProperties linkProperties) {}
4117
4118 /**
4119 * Called when the network the framework connected to for this request suspends data
4120 * transmission temporarily.
4121 *
4122 * <p>This generally means that while the TCP connections are still live temporarily
4123 * network data fails to transfer. To give a specific example, this is used on cellular
4124 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4125 * means read operations on sockets on this network will block once the buffers are
4126 * drained, and write operations will block once the buffers are full.
4127 *
4128 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4129 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4130 * this callback as this is prone to race conditions (there is no guarantee the objects
4131 * returned by these methods will be current).
4132 *
4133 * @hide
4134 */
4135 public void onNetworkSuspended(@NonNull Network network) {}
4136
4137 /**
4138 * Called when the network the framework connected to for this request
4139 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4140 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4141
4142 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4143 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4144 * this callback as this is prone to race conditions : calling these methods while in a
4145 * callback may return an outdated or even a null object.
4146 *
4147 * @hide
4148 */
4149 public void onNetworkResumed(@NonNull Network network) {}
4150
4151 /**
4152 * Called when access to the specified network is blocked or unblocked.
4153 *
4154 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4155 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4156 * this callback as this is prone to race conditions : calling these methods while in a
4157 * callback may return an outdated or even a null object.
4158 *
4159 * @param network The {@link Network} whose blocked status has changed.
4160 * @param blocked The blocked status of this {@link Network}.
4161 */
4162 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4163
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004164 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004165 * Called when access to the specified network is blocked or unblocked, or the reason for
4166 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004167 *
4168 * If a NetworkCallback object implements this method,
4169 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4170 *
4171 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4172 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4173 * this callback as this is prone to race conditions : calling these methods while in a
4174 * callback may return an outdated or even a null object.
4175 *
4176 * @param network The {@link Network} whose blocked status has changed.
4177 * @param blocked The blocked status of this {@link Network}.
4178 * @hide
4179 */
4180 @SystemApi(client = MODULE_LIBRARIES)
4181 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4182 onBlockedStatusChanged(network, blocked != 0);
4183 }
4184
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004185 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004186 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004187 }
4188
4189 /**
4190 * Constant error codes used by ConnectivityService to communicate about failures and errors
4191 * across a Binder boundary.
4192 * @hide
4193 */
4194 public interface Errors {
4195 int TOO_MANY_REQUESTS = 1;
4196 }
4197
4198 /** @hide */
4199 public static class TooManyRequestsException extends RuntimeException {}
4200
4201 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4202 switch (e.errorCode) {
4203 case Errors.TOO_MANY_REQUESTS:
4204 return new TooManyRequestsException();
4205 default:
4206 Log.w(TAG, "Unknown service error code " + e.errorCode);
4207 return new RuntimeException(e);
4208 }
4209 }
4210
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004211 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004212 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004213 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004214 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004215 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004216 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004217 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004218 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004219 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004220 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004221 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004222 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004223 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004224 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004225 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004226 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004227 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004228 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004229 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004230 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004231 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004232 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004233
4234 /** @hide */
4235 public static String getCallbackName(int whichCallback) {
4236 switch (whichCallback) {
4237 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4238 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4239 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4240 case CALLBACK_LOST: return "CALLBACK_LOST";
4241 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4242 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4243 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4244 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4245 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4246 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4247 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4248 default:
4249 return Integer.toString(whichCallback);
4250 }
4251 }
4252
zhujiatai79b0de92022-09-22 15:44:02 +08004253 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004254 private static final String TAG = "ConnectivityManager.CallbackHandler";
4255 private static final boolean DBG = false;
4256
4257 CallbackHandler(Looper looper) {
4258 super(looper);
4259 }
4260
4261 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004262 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004263 }
4264
4265 @Override
4266 public void handleMessage(Message message) {
4267 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004268 // the sInstance can't be null because to send this message a ConnectivityManager
4269 // instance must have been created prior to creating the thread on which this
4270 // Handler is running.
4271 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004272 return;
4273 }
4274
4275 final NetworkRequest request = getObject(message, NetworkRequest.class);
4276 final Network network = getObject(message, Network.class);
4277 final NetworkCallback callback;
4278 synchronized (sCallbacks) {
4279 callback = sCallbacks.get(request);
4280 if (callback == null) {
4281 Log.w(TAG,
4282 "callback not found for " + getCallbackName(message.what) + " message");
4283 return;
4284 }
4285 if (message.what == CALLBACK_UNAVAIL) {
4286 sCallbacks.remove(request);
4287 callback.networkRequest = ALREADY_UNREGISTERED;
4288 }
4289 }
4290 if (DBG) {
4291 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4292 }
4293
4294 switch (message.what) {
4295 case CALLBACK_PRECHECK: {
4296 callback.onPreCheck(network);
4297 break;
4298 }
4299 case CALLBACK_AVAILABLE: {
4300 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4301 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004302 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004303 break;
4304 }
4305 case CALLBACK_LOSING: {
4306 callback.onLosing(network, message.arg1);
4307 break;
4308 }
4309 case CALLBACK_LOST: {
4310 callback.onLost(network);
4311 break;
4312 }
4313 case CALLBACK_UNAVAIL: {
4314 callback.onUnavailable();
4315 break;
4316 }
4317 case CALLBACK_CAP_CHANGED: {
4318 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4319 callback.onCapabilitiesChanged(network, cap);
4320 break;
4321 }
4322 case CALLBACK_IP_CHANGED: {
4323 LinkProperties lp = getObject(message, LinkProperties.class);
4324 callback.onLinkPropertiesChanged(network, lp);
4325 break;
4326 }
4327 case CALLBACK_SUSPENDED: {
4328 callback.onNetworkSuspended(network);
4329 break;
4330 }
4331 case CALLBACK_RESUMED: {
4332 callback.onNetworkResumed(network);
4333 break;
4334 }
4335 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004336 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004337 }
4338 }
4339 }
4340
4341 private <T> T getObject(Message msg, Class<T> c) {
4342 return (T) msg.getData().getParcelable(c.getSimpleName());
4343 }
4344 }
4345
4346 private CallbackHandler getDefaultHandler() {
4347 synchronized (sCallbacks) {
4348 if (sCallbackHandler == null) {
4349 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4350 }
4351 return sCallbackHandler;
4352 }
4353 }
4354
4355 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4356 private static CallbackHandler sCallbackHandler;
4357
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004358 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4359 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4360 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004361 printStackTrace();
4362 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004363 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4364 throw new IllegalArgumentException("null NetworkCapabilities");
4365 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004366 final NetworkRequest request;
4367 final String callingPackageName = mContext.getOpPackageName();
4368 try {
4369 synchronized(sCallbacks) {
4370 if (callback.networkRequest != null
4371 && callback.networkRequest != ALREADY_UNREGISTERED) {
4372 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4373 // and requests (http://b/20701525).
4374 Log.e(TAG, "NetworkCallback was already registered");
4375 }
4376 Messenger messenger = new Messenger(handler);
4377 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004378 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004379 if (reqType == LISTEN) {
4380 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004381 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004382 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004383 } else {
4384 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004385 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4386 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004387 }
4388 if (request != null) {
4389 sCallbacks.put(request, callback);
4390 }
4391 callback.networkRequest = request;
4392 }
4393 } catch (RemoteException e) {
4394 throw e.rethrowFromSystemServer();
4395 } catch (ServiceSpecificException e) {
4396 throw convertServiceException(e);
4397 }
4398 return request;
4399 }
4400
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004401 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4402 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4403 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4404 legacyType, handler);
4405 }
4406
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004407 /**
4408 * Helper function to request a network with a particular legacy type.
4409 *
4410 * This API is only for use in internal system code that requests networks with legacy type and
4411 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4412 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4413 *
4414 * @param request {@link NetworkRequest} describing this request.
4415 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4416 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4417 * be a positive value (i.e. >0).
4418 * @param legacyType to specify the network type(#TYPE_*).
4419 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4420 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4421 * the callback must not be shared - it uniquely specifies this request.
4422 *
4423 * @hide
4424 */
4425 @SystemApi
4426 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4427 public void requestNetwork(@NonNull NetworkRequest request,
4428 int timeoutMs, int legacyType, @NonNull Handler handler,
4429 @NonNull NetworkCallback networkCallback) {
4430 if (legacyType == TYPE_NONE) {
4431 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4432 }
4433 CallbackHandler cbHandler = new CallbackHandler(handler);
4434 NetworkCapabilities nc = request.networkCapabilities;
4435 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4436 }
4437
4438 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004439 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004440 *
4441 * <p>This method will attempt to find the best network that matches the passed
4442 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4443 * criteria. The platform will evaluate which network is the best at its own discretion.
4444 * Throughput, latency, cost per byte, policy, user preference and other considerations
4445 * may be factored in the decision of what is considered the best network.
4446 *
4447 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4448 * matching this request, while always attempting to match the request to a better network if
4449 * possible. If a better match is found, the platform will switch this request to the now-best
4450 * network and inform the app of the newly best network by invoking
4451 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4452 * will not try to maintain any other network than the best one currently matching the request:
4453 * a network not matching any network request may be disconnected at any time.
4454 *
4455 * <p>For example, an application could use this method to obtain a connected cellular network
4456 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4457 * radio to consume additional power. Or, an application could inform the system that it wants
4458 * a network supporting sending MMSes and have the system let it know about the currently best
4459 * MMS-supporting network through the provided {@link NetworkCallback}.
4460 *
4461 * <p>The status of the request can be followed by listening to the various callbacks described
4462 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4463 * used to direct traffic to the network (although accessing some networks may be subject to
4464 * holding specific permissions). Callers will learn about the specific characteristics of the
4465 * network through
4466 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4467 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4468 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4469 * matching the request at any given time; therefore when a better network matching the request
4470 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4471 * with the new network after which no further updates are given about the previously-best
4472 * network, unless it becomes the best again at some later time. All callbacks are invoked
4473 * in order on the same thread, which by default is a thread created by the framework running
4474 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004475 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004476 * callbacks are invoked.
4477 *
4478 * <p>This{@link NetworkRequest} will live until released via
4479 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4480 * which point the system may let go of the network at any time.
4481 *
4482 * <p>A version of this method which takes a timeout is
4483 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4484 * wait for a limited amount of time for the network to become unavailable.
4485 *
4486 * <p>It is presently unsupported to request a network with mutable
4487 * {@link NetworkCapabilities} such as
4488 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4489 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4490 * as these {@code NetworkCapabilities} represent states that a particular
4491 * network may never attain, and whether a network will attain these states
4492 * is unknown prior to bringing up the network so the framework does not
4493 * know how to go about satisfying a request with these capabilities.
4494 *
4495 * <p>This method requires the caller to hold either the
4496 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4497 * or the ability to modify system settings as determined by
4498 * {@link android.provider.Settings.System#canWrite}.</p>
4499 *
4500 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4501 * number of outstanding requests to 100 per app (identified by their UID), shared with
4502 * all variants of this method, of {@link #registerNetworkCallback} as well as
4503 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4504 * Requesting a network with this method will count toward this limit. If this limit is
4505 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4506 * make sure to unregister the callbacks with
4507 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4508 *
4509 * @param request {@link NetworkRequest} describing this request.
4510 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4511 * the callback must not be shared - it uniquely specifies this request.
4512 * The callback is invoked on the default internal Handler.
4513 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4514 * @throws SecurityException if missing the appropriate permissions.
4515 * @throws RuntimeException if the app already has too many callbacks registered.
4516 */
4517 public void requestNetwork(@NonNull NetworkRequest request,
4518 @NonNull NetworkCallback networkCallback) {
4519 requestNetwork(request, networkCallback, getDefaultHandler());
4520 }
4521
4522 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004523 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004524 *
4525 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4526 * but runs all the callbacks on the passed Handler.
4527 *
4528 * <p>This method has the same permission requirements as
4529 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4530 * and throws the same exceptions in the same conditions.
4531 *
4532 * @param request {@link NetworkRequest} describing this request.
4533 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4534 * the callback must not be shared - it uniquely specifies this request.
4535 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4536 */
4537 public void requestNetwork(@NonNull NetworkRequest request,
4538 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4539 CallbackHandler cbHandler = new CallbackHandler(handler);
4540 NetworkCapabilities nc = request.networkCapabilities;
4541 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4542 }
4543
4544 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004545 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004546 * by a timeout.
4547 *
4548 * This function behaves identically to the non-timed-out version
4549 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4550 * is not found within the given time (in milliseconds) the
4551 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4552 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4553 * not have to be released if timed-out (it is automatically released). Unregistering a
4554 * request that timed out is not an error.
4555 *
4556 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4557 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4558 * for that purpose. Calling this method will attempt to bring up the requested network.
4559 *
4560 * <p>This method has the same permission requirements as
4561 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4562 * and throws the same exceptions in the same conditions.
4563 *
4564 * @param request {@link NetworkRequest} describing this request.
4565 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4566 * the callback must not be shared - it uniquely specifies this request.
4567 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4568 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4569 * be a positive value (i.e. >0).
4570 */
4571 public void requestNetwork(@NonNull NetworkRequest request,
4572 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4573 checkTimeout(timeoutMs);
4574 NetworkCapabilities nc = request.networkCapabilities;
4575 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4576 getDefaultHandler());
4577 }
4578
4579 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004580 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004581 * by a timeout.
4582 *
4583 * This method behaves identically to
4584 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4585 * on the passed Handler.
4586 *
4587 * <p>This method has the same permission requirements as
4588 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4589 * and throws the same exceptions in the same conditions.
4590 *
4591 * @param request {@link NetworkRequest} describing this request.
4592 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4593 * the callback must not be shared - it uniquely specifies this request.
4594 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4595 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4596 * before {@link NetworkCallback#onUnavailable} is called.
4597 */
4598 public void requestNetwork(@NonNull NetworkRequest request,
4599 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4600 checkTimeout(timeoutMs);
4601 CallbackHandler cbHandler = new CallbackHandler(handler);
4602 NetworkCapabilities nc = request.networkCapabilities;
4603 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4604 }
4605
4606 /**
4607 * The lookup key for a {@link Network} object included with the intent after
4608 * successfully finding a network for the applications request. Retrieve it with
4609 * {@link android.content.Intent#getParcelableExtra(String)}.
4610 * <p>
4611 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4612 * then you must get a ConnectivityManager instance before doing so.
4613 */
4614 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4615
4616 /**
4617 * The lookup key for a {@link NetworkRequest} object included with the intent after
4618 * successfully finding a network for the applications request. Retrieve it with
4619 * {@link android.content.Intent#getParcelableExtra(String)}.
4620 */
4621 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4622
4623
4624 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004625 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004626 *
4627 * This function behaves identically to the version that takes a NetworkCallback, but instead
4628 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4629 * the request may outlive the calling application and get called back when a suitable
4630 * network is found.
4631 * <p>
4632 * The operation is an Intent broadcast that goes to a broadcast receiver that
4633 * you registered with {@link Context#registerReceiver} or through the
4634 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4635 * <p>
4636 * The operation Intent is delivered with two extras, a {@link Network} typed
4637 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4638 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4639 * the original requests parameters. It is important to create a new,
4640 * {@link NetworkCallback} based request before completing the processing of the
4641 * Intent to reserve the network or it will be released shortly after the Intent
4642 * is processed.
4643 * <p>
4644 * If there is already a request for this Intent registered (with the equality of
4645 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4646 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4647 * <p>
4648 * The request may be released normally by calling
4649 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4650 * <p>It is presently unsupported to request a network with either
4651 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4652 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4653 * as these {@code NetworkCapabilities} represent states that a particular
4654 * network may never attain, and whether a network will attain these states
4655 * is unknown prior to bringing up the network so the framework does not
4656 * know how to go about satisfying a request with these capabilities.
4657 *
4658 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4659 * number of outstanding requests to 100 per app (identified by their UID), shared with
4660 * all variants of this method, of {@link #registerNetworkCallback} as well as
4661 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4662 * Requesting a network with this method will count toward this limit. If this limit is
4663 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4664 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4665 * or {@link #releaseNetworkRequest(PendingIntent)}.
4666 *
4667 * <p>This method requires the caller to hold either the
4668 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4669 * or the ability to modify system settings as determined by
4670 * {@link android.provider.Settings.System#canWrite}.</p>
4671 *
4672 * @param request {@link NetworkRequest} describing this request.
4673 * @param operation Action to perform when the network is available (corresponds
4674 * to the {@link NetworkCallback#onAvailable} call. Typically
4675 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4676 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4677 * @throws SecurityException if missing the appropriate permissions.
4678 * @throws RuntimeException if the app already has too many callbacks registered.
4679 */
4680 public void requestNetwork(@NonNull NetworkRequest request,
4681 @NonNull PendingIntent operation) {
4682 printStackTrace();
4683 checkPendingIntentNotNull(operation);
4684 try {
4685 mService.pendingRequestForNetwork(
4686 request.networkCapabilities, operation, mContext.getOpPackageName(),
4687 getAttributionTag());
4688 } catch (RemoteException e) {
4689 throw e.rethrowFromSystemServer();
4690 } catch (ServiceSpecificException e) {
4691 throw convertServiceException(e);
4692 }
4693 }
4694
4695 /**
4696 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4697 * <p>
4698 * This method has the same behavior as
4699 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4700 * releasing network resources and disconnecting.
4701 *
4702 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4703 * PendingIntent passed to
4704 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4705 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4706 */
4707 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4708 printStackTrace();
4709 checkPendingIntentNotNull(operation);
4710 try {
4711 mService.releasePendingNetworkRequest(operation);
4712 } catch (RemoteException e) {
4713 throw e.rethrowFromSystemServer();
4714 }
4715 }
4716
4717 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004718 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004719 }
4720
4721 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004722 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004723 }
4724
4725 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004726 if (timeoutMs <= 0) {
4727 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4728 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004729 }
4730
4731 /**
4732 * Registers to receive notifications about all networks which satisfy the given
4733 * {@link NetworkRequest}. The callbacks will continue to be called until
4734 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4735 * called.
4736 *
4737 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4738 * number of outstanding requests to 100 per app (identified by their UID), shared with
4739 * all variants of this method, of {@link #requestNetwork} as well as
4740 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4741 * Requesting a network with this method will count toward this limit. If this limit is
4742 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4743 * make sure to unregister the callbacks with
4744 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4745 *
4746 * @param request {@link NetworkRequest} describing this request.
4747 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4748 * networks change state.
4749 * The callback is invoked on the default internal Handler.
4750 * @throws RuntimeException if the app already has too many callbacks registered.
4751 */
4752 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4753 public void registerNetworkCallback(@NonNull NetworkRequest request,
4754 @NonNull NetworkCallback networkCallback) {
4755 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4756 }
4757
4758 /**
4759 * Registers to receive notifications about all networks which satisfy the given
4760 * {@link NetworkRequest}. The callbacks will continue to be called until
4761 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4762 * called.
4763 *
4764 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4765 * number of outstanding requests to 100 per app (identified by their UID), shared with
4766 * all variants of this method, of {@link #requestNetwork} as well as
4767 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4768 * Requesting a network with this method will count toward this limit. If this limit is
4769 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4770 * make sure to unregister the callbacks with
4771 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4772 *
4773 *
4774 * @param request {@link NetworkRequest} describing this request.
4775 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4776 * networks change state.
4777 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4778 * @throws RuntimeException if the app already has too many callbacks registered.
4779 */
4780 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4781 public void registerNetworkCallback(@NonNull NetworkRequest request,
4782 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4783 CallbackHandler cbHandler = new CallbackHandler(handler);
4784 NetworkCapabilities nc = request.networkCapabilities;
4785 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4786 }
4787
4788 /**
4789 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4790 * {@link NetworkRequest}.
4791 *
4792 * This function behaves identically to the version that takes a NetworkCallback, but instead
4793 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4794 * the request may outlive the calling application and get called back when a suitable
4795 * network is found.
4796 * <p>
4797 * The operation is an Intent broadcast that goes to a broadcast receiver that
4798 * you registered with {@link Context#registerReceiver} or through the
4799 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4800 * <p>
4801 * The operation Intent is delivered with two extras, a {@link Network} typed
4802 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4803 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4804 * the original requests parameters.
4805 * <p>
4806 * If there is already a request for this Intent registered (with the equality of
4807 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4808 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4809 * <p>
4810 * The request may be released normally by calling
4811 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4812 *
4813 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4814 * number of outstanding requests to 100 per app (identified by their UID), shared with
4815 * all variants of this method, of {@link #requestNetwork} as well as
4816 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4817 * Requesting a network with this method will count toward this limit. If this limit is
4818 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4819 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4820 * or {@link #releaseNetworkRequest(PendingIntent)}.
4821 *
4822 * @param request {@link NetworkRequest} describing this request.
4823 * @param operation Action to perform when the network is available (corresponds
4824 * to the {@link NetworkCallback#onAvailable} call. Typically
4825 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4826 * @throws RuntimeException if the app already has too many callbacks registered.
4827 */
4828 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4829 public void registerNetworkCallback(@NonNull NetworkRequest request,
4830 @NonNull PendingIntent operation) {
4831 printStackTrace();
4832 checkPendingIntentNotNull(operation);
4833 try {
4834 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004835 request.networkCapabilities, operation, mContext.getOpPackageName(),
4836 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004837 } catch (RemoteException e) {
4838 throw e.rethrowFromSystemServer();
4839 } catch (ServiceSpecificException e) {
4840 throw convertServiceException(e);
4841 }
4842 }
4843
4844 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004845 * Registers to receive notifications about changes in the application's default network. This
4846 * may be a physical network or a virtual network, such as a VPN that applies to the
4847 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004848 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4849 *
4850 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4851 * number of outstanding requests to 100 per app (identified by their UID), shared with
4852 * all variants of this method, of {@link #requestNetwork} as well as
4853 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4854 * Requesting a network with this method will count toward this limit. If this limit is
4855 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4856 * make sure to unregister the callbacks with
4857 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4858 *
4859 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004860 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004861 * The callback is invoked on the default internal Handler.
4862 * @throws RuntimeException if the app already has too many callbacks registered.
4863 */
4864 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4865 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4866 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4867 }
4868
4869 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004870 * Registers to receive notifications about changes in the application's default network. This
4871 * may be a physical network or a virtual network, such as a VPN that applies to the
4872 * application. The callbacks will continue to be called until either the application exits or
4873 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4874 *
4875 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4876 * number of outstanding requests to 100 per app (identified by their UID), shared with
4877 * all variants of this method, of {@link #requestNetwork} as well as
4878 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4879 * Requesting a network with this method will count toward this limit. If this limit is
4880 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4881 * make sure to unregister the callbacks with
4882 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4883 *
4884 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4885 * application's default network changes.
4886 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4887 * @throws RuntimeException if the app already has too many callbacks registered.
4888 */
4889 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4890 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4891 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004892 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004893 }
4894
4895 /**
4896 * Registers to receive notifications about changes in the default network for the specified
4897 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4898 * UID. The callbacks will continue to be called until either the application exits or
4899 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4900 *
4901 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4902 * number of outstanding requests to 100 per app (identified by their UID), shared with
4903 * all variants of this method, of {@link #requestNetwork} as well as
4904 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4905 * Requesting a network with this method will count toward this limit. If this limit is
4906 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4907 * make sure to unregister the callbacks with
4908 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4909 *
4910 * @param uid the UID for which to track default network changes.
4911 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4912 * UID's default network changes.
4913 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4914 * @throws RuntimeException if the app already has too many callbacks registered.
4915 * @hide
4916 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004917 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004918 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4919 @RequiresPermission(anyOf = {
4920 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4921 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004922 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004923 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004924 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004925 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004926 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4927 }
4928
4929 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004930 * Registers to receive notifications about changes in the system default network. The callbacks
4931 * will continue to be called until either the application exits or
4932 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4933 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004934 * This method should not be used to determine networking state seen by applications, because in
4935 * many cases, most or even all application traffic may not use the default network directly,
4936 * and traffic from different applications may go on different networks by default. As an
4937 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4938 * and not onto the system default network. Applications or system components desiring to do
4939 * determine network state as seen by applications should use other methods such as
4940 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4941 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004942 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4943 * number of outstanding requests to 100 per app (identified by their UID), shared with
4944 * all variants of this method, of {@link #requestNetwork} as well as
4945 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4946 * Requesting a network with this method will count toward this limit. If this limit is
4947 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4948 * make sure to unregister the callbacks with
4949 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4950 *
4951 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4952 * system default network changes.
4953 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4954 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004955 *
4956 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004957 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004958 @SystemApi(client = MODULE_LIBRARIES)
4959 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4960 @RequiresPermission(anyOf = {
4961 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004962 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00004963 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004964 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004965 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004966 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004967 CallbackHandler cbHandler = new CallbackHandler(handler);
4968 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004969 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004970 }
4971
4972 /**
junyulaibd123062021-03-15 11:48:48 +08004973 * Registers to receive notifications about the best matching network which satisfy the given
4974 * {@link NetworkRequest}. The callbacks will continue to be called until
4975 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4976 * called.
4977 *
4978 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4979 * number of outstanding requests to 100 per app (identified by their UID), shared with
4980 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4981 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4982 * Requesting a network with this method will count toward this limit. If this limit is
4983 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4984 * make sure to unregister the callbacks with
4985 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4986 *
4987 *
4988 * @param request {@link NetworkRequest} describing this request.
4989 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4990 * networks change state.
4991 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4992 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004993 */
junyulai5a5c99b2021-03-05 15:51:17 +08004994 @SuppressLint("ExecutorRegistration")
4995 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4996 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4997 final NetworkCapabilities nc = request.networkCapabilities;
4998 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004999 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08005000 }
5001
5002 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005003 * Requests bandwidth update for a given {@link Network} and returns whether the update request
5004 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
5005 * network connection for updated bandwidth information. The caller will be notified via
5006 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
5007 * method assumes that the caller has previously called
5008 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
5009 * changes.
5010 *
5011 * @param network {@link Network} specifying which network you're interested.
5012 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5013 */
5014 public boolean requestBandwidthUpdate(@NonNull Network network) {
5015 try {
5016 return mService.requestBandwidthUpdate(network);
5017 } catch (RemoteException e) {
5018 throw e.rethrowFromSystemServer();
5019 }
5020 }
5021
5022 /**
5023 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
5024 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
5025 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005026 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
5027 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005028 *
5029 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
5030 * triggering it as soon as this call returns.
5031 *
5032 * @param networkCallback The {@link NetworkCallback} used when making the request.
5033 */
5034 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
5035 printStackTrace();
5036 checkCallbackNotNull(networkCallback);
5037 final List<NetworkRequest> reqs = new ArrayList<>();
5038 // Find all requests associated to this callback and stop callback triggers immediately.
5039 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
5040 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00005041 if (networkCallback.networkRequest == null) {
5042 throw new IllegalArgumentException("NetworkCallback was not registered");
5043 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005044 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
5045 Log.d(TAG, "NetworkCallback was already unregistered");
5046 return;
5047 }
5048 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
5049 if (e.getValue() == networkCallback) {
5050 reqs.add(e.getKey());
5051 }
5052 }
5053 // TODO: throw exception if callback was registered more than once (http://b/20701525).
5054 for (NetworkRequest r : reqs) {
5055 try {
5056 mService.releaseNetworkRequest(r);
5057 } catch (RemoteException e) {
5058 throw e.rethrowFromSystemServer();
5059 }
5060 // Only remove mapping if rpc was successful.
5061 sCallbacks.remove(r);
5062 }
5063 networkCallback.networkRequest = ALREADY_UNREGISTERED;
5064 }
5065 }
5066
5067 /**
5068 * Unregisters a callback previously registered via
5069 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5070 *
5071 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
5072 * PendingIntent passed to
5073 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5074 * Cannot be null.
5075 */
5076 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
5077 releaseNetworkRequest(operation);
5078 }
5079
5080 /**
5081 * Informs the system whether it should switch to {@code network} regardless of whether it is
5082 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
5083 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
5084 * the system default network regardless of any other network that's currently connected. If
5085 * {@code always} is true, then the choice is remembered, so that the next time the user
5086 * connects to this network, the system will switch to it.
5087 *
5088 * @param network The network to accept.
5089 * @param accept Whether to accept the network even if unvalidated.
5090 * @param always Whether to remember this choice in the future.
5091 *
5092 * @hide
5093 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005094 @SystemApi(client = MODULE_LIBRARIES)
5095 @RequiresPermission(anyOf = {
5096 android.Manifest.permission.NETWORK_SETTINGS,
5097 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5098 android.Manifest.permission.NETWORK_STACK,
5099 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5100 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005101 try {
5102 mService.setAcceptUnvalidated(network, accept, always);
5103 } catch (RemoteException e) {
5104 throw e.rethrowFromSystemServer();
5105 }
5106 }
5107
5108 /**
5109 * Informs the system whether it should consider the network as validated even if it only has
5110 * partial connectivity. If {@code accept} is true, then the network will be considered as
5111 * validated even if connectivity is only partial. If {@code always} is true, then the choice
5112 * is remembered, so that the next time the user connects to this network, the system will
5113 * switch to it.
5114 *
5115 * @param network The network to accept.
5116 * @param accept Whether to consider the network as validated even if it has partial
5117 * connectivity.
5118 * @param always Whether to remember this choice in the future.
5119 *
5120 * @hide
5121 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005122 @SystemApi(client = MODULE_LIBRARIES)
5123 @RequiresPermission(anyOf = {
5124 android.Manifest.permission.NETWORK_SETTINGS,
5125 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5126 android.Manifest.permission.NETWORK_STACK,
5127 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5128 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5129 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005130 try {
5131 mService.setAcceptPartialConnectivity(network, accept, always);
5132 } catch (RemoteException e) {
5133 throw e.rethrowFromSystemServer();
5134 }
5135 }
5136
5137 /**
5138 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5139 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5140 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5141 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5142 *
5143 * @param network The network to accept.
5144 *
5145 * @hide
5146 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005147 @SystemApi(client = MODULE_LIBRARIES)
5148 @RequiresPermission(anyOf = {
5149 android.Manifest.permission.NETWORK_SETTINGS,
5150 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5151 android.Manifest.permission.NETWORK_STACK,
5152 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5153 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005154 try {
5155 mService.setAvoidUnvalidated(network);
5156 } catch (RemoteException e) {
5157 throw e.rethrowFromSystemServer();
5158 }
5159 }
5160
5161 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005162 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005163 *
5164 * @param timeMs The expired current time. The value should be set within a limited time from
5165 * now.
5166 *
5167 * @hide
5168 */
5169 public void setTestAllowBadWifiUntil(long timeMs) {
5170 try {
5171 mService.setTestAllowBadWifiUntil(timeMs);
5172 } catch (RemoteException e) {
5173 throw e.rethrowFromSystemServer();
5174 }
5175 }
5176
5177 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005178 * Requests that the system open the captive portal app on the specified network.
5179 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005180 * <p>This is to be used on networks where a captive portal was detected, as per
5181 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5182 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005183 * @param network The network to log into.
5184 *
5185 * @hide
5186 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005187 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5188 @RequiresPermission(anyOf = {
5189 android.Manifest.permission.NETWORK_SETTINGS,
5190 android.Manifest.permission.NETWORK_STACK,
5191 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5192 })
5193 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005194 try {
5195 mService.startCaptivePortalApp(network);
5196 } catch (RemoteException e) {
5197 throw e.rethrowFromSystemServer();
5198 }
5199 }
5200
5201 /**
5202 * Requests that the system open the captive portal app with the specified extras.
5203 *
5204 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5205 * corresponding permission.
5206 * @param network Network on which the captive portal was detected.
5207 * @param appExtras Extras to include in the app start intent.
5208 * @hide
5209 */
5210 @SystemApi
5211 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5212 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5213 try {
5214 mService.startCaptivePortalAppInternal(network, appExtras);
5215 } catch (RemoteException e) {
5216 throw e.rethrowFromSystemServer();
5217 }
5218 }
5219
5220 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005221 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005222 * @hide
5223 */
5224 @SystemApi
5225 @RequiresPermission(anyOf = {
5226 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5227 android.Manifest.permission.NETWORK_STACK})
5228 public boolean shouldAvoidBadWifi() {
5229 try {
5230 return mService.shouldAvoidBadWifi();
5231 } catch (RemoteException e) {
5232 throw e.rethrowFromSystemServer();
5233 }
5234 }
5235
5236 /**
5237 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5238 * time-sensitive user-facing operations when the system default network is temporarily
5239 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5240 * this method), and the operation should be infrequent to ensure that data usage is limited.
5241 *
5242 * An example of such an operation might be a time-sensitive foreground activity, such as a
5243 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5244 */
5245 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5246
5247 /**
5248 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5249 * a backup channel for traffic that is primarily going over another network.
5250 *
5251 * An example might be maintaining backup connections to peers or servers for the purpose of
5252 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5253 * on backup paths should be negligible compared to the traffic on the main path.
5254 */
5255 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5256
5257 /**
5258 * It is acceptable to use metered data to improve network latency and performance.
5259 */
5260 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5261
5262 /**
5263 * Return value to use for unmetered networks. On such networks we currently set all the flags
5264 * to true.
5265 * @hide
5266 */
5267 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5268 MULTIPATH_PREFERENCE_HANDOVER |
5269 MULTIPATH_PREFERENCE_RELIABILITY |
5270 MULTIPATH_PREFERENCE_PERFORMANCE;
5271
Aaron Huangcff22942021-05-27 16:31:26 +08005272 /** @hide */
5273 @Retention(RetentionPolicy.SOURCE)
5274 @IntDef(flag = true, value = {
5275 MULTIPATH_PREFERENCE_HANDOVER,
5276 MULTIPATH_PREFERENCE_RELIABILITY,
5277 MULTIPATH_PREFERENCE_PERFORMANCE,
5278 })
5279 public @interface MultipathPreference {
5280 }
5281
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005282 /**
5283 * Provides a hint to the calling application on whether it is desirable to use the
5284 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5285 * for multipath data transfer on this network when it is not the system default network.
5286 * Applications desiring to use multipath network protocols should call this method before
5287 * each such operation.
5288 *
5289 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005290 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005291 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005292 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005293 */
5294 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5295 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5296 try {
5297 return mService.getMultipathPreference(network);
5298 } catch (RemoteException e) {
5299 throw e.rethrowFromSystemServer();
5300 }
5301 }
5302
5303 /**
5304 * Resets all connectivity manager settings back to factory defaults.
5305 * @hide
5306 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005307 @SystemApi(client = MODULE_LIBRARIES)
5308 @RequiresPermission(anyOf = {
5309 android.Manifest.permission.NETWORK_SETTINGS,
5310 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005311 public void factoryReset() {
5312 try {
5313 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005314 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005315 } catch (RemoteException e) {
5316 throw e.rethrowFromSystemServer();
5317 }
5318 }
5319
5320 /**
5321 * Binds the current process to {@code network}. All Sockets created in the future
5322 * (and not explicitly bound via a bound SocketFactory from
5323 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5324 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5325 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5326 * work and all host name resolutions will fail. This is by design so an application doesn't
5327 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5328 * To clear binding pass {@code null} for {@code network}. Using individually bound
5329 * Sockets created by Network.getSocketFactory().createSocket() and
5330 * performing network-specific host name resolutions via
5331 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5332 * {@code bindProcessToNetwork}.
5333 *
5334 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5335 * the current binding.
5336 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5337 */
5338 public boolean bindProcessToNetwork(@Nullable Network network) {
5339 // Forcing callers to call through non-static function ensures ConnectivityManager
5340 // instantiated.
5341 return setProcessDefaultNetwork(network);
5342 }
5343
5344 /**
5345 * Binds the current process to {@code network}. All Sockets created in the future
5346 * (and not explicitly bound via a bound SocketFactory from
5347 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5348 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5349 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5350 * work and all host name resolutions will fail. This is by design so an application doesn't
5351 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5352 * To clear binding pass {@code null} for {@code network}. Using individually bound
5353 * Sockets created by Network.getSocketFactory().createSocket() and
5354 * performing network-specific host name resolutions via
5355 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5356 * {@code setProcessDefaultNetwork}.
5357 *
5358 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5359 * the current binding.
5360 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5361 * @deprecated This function can throw {@link IllegalStateException}. Use
5362 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5363 * is a direct replacement.
5364 */
5365 @Deprecated
5366 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5367 int netId = (network == null) ? NETID_UNSET : network.netId;
5368 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5369
5370 if (netId != NETID_UNSET) {
5371 netId = network.getNetIdForResolv();
5372 }
5373
5374 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5375 return false;
5376 }
5377
5378 if (!isSameNetId) {
5379 // Set HTTP proxy system properties to match network.
5380 // TODO: Deprecate this static method and replace it with a non-static version.
5381 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005382 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005383 } catch (SecurityException e) {
5384 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5385 Log.e(TAG, "Can't set proxy properties", e);
5386 }
5387 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005388 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005389 // Must flush socket pool as idle sockets will be bound to previous network and may
5390 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005391 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005392 }
5393
5394 return true;
5395 }
5396
5397 /**
5398 * Returns the {@link Network} currently bound to this process via
5399 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5400 *
5401 * @return {@code Network} to which this process is bound, or {@code null}.
5402 */
5403 @Nullable
5404 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005405 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005406 // instantiated.
5407 return getProcessDefaultNetwork();
5408 }
5409
5410 /**
5411 * Returns the {@link Network} currently bound to this process via
5412 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5413 *
5414 * @return {@code Network} to which this process is bound, or {@code null}.
5415 * @deprecated Using this function can lead to other functions throwing
5416 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5417 * {@code getBoundNetworkForProcess} is a direct replacement.
5418 */
5419 @Deprecated
5420 @Nullable
5421 public static Network getProcessDefaultNetwork() {
5422 int netId = NetworkUtils.getBoundNetworkForProcess();
5423 if (netId == NETID_UNSET) return null;
5424 return new Network(netId);
5425 }
5426
5427 private void unsupportedStartingFrom(int version) {
5428 if (Process.myUid() == Process.SYSTEM_UID) {
5429 // The getApplicationInfo() call we make below is not supported in system context. Let
5430 // the call through here, and rely on the fact that ConnectivityService will refuse to
5431 // allow the system to use these APIs anyway.
5432 return;
5433 }
5434
5435 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5436 throw new UnsupportedOperationException(
5437 "This method is not supported in target SDK version " + version + " and above");
5438 }
5439 }
5440
5441 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5442 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5443 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5444 // remove these exemptions. Note that this check is not secure, and apps can still access these
5445 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5446 // so is unsupported and may break in the future. http://b/22728205
5447 private void checkLegacyRoutingApiAccess() {
5448 unsupportedStartingFrom(VERSION_CODES.M);
5449 }
5450
5451 /**
5452 * Binds host resolutions performed by this process to {@code network}.
5453 * {@link #bindProcessToNetwork} takes precedence over this setting.
5454 *
5455 * @param network The {@link Network} to bind host resolutions from the current process to, or
5456 * {@code null} to clear the current binding.
5457 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5458 * @hide
5459 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5460 */
5461 @Deprecated
5462 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5463 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5464 return NetworkUtils.bindProcessToNetworkForHostResolution(
5465 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5466 }
5467
5468 /**
5469 * Device is not restricting metered network activity while application is running on
5470 * background.
5471 */
5472 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5473
5474 /**
5475 * Device is restricting metered network activity while application is running on background,
5476 * but application is allowed to bypass it.
5477 * <p>
5478 * In this state, application should take action to mitigate metered network access.
5479 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5480 */
5481 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5482
5483 /**
5484 * Device is restricting metered network activity while application is running on background.
5485 * <p>
5486 * In this state, application should not try to use the network while running on background,
5487 * because it would be denied.
5488 */
5489 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5490
5491 /**
5492 * A change in the background metered network activity restriction has occurred.
5493 * <p>
5494 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5495 * applies to them.
5496 * <p>
5497 * This is only sent to registered receivers, not manifest receivers.
5498 */
5499 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5500 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5501 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5502
Aaron Huangcff22942021-05-27 16:31:26 +08005503 /** @hide */
5504 @Retention(RetentionPolicy.SOURCE)
5505 @IntDef(flag = false, value = {
5506 RESTRICT_BACKGROUND_STATUS_DISABLED,
5507 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5508 RESTRICT_BACKGROUND_STATUS_ENABLED,
5509 })
5510 public @interface RestrictBackgroundStatus {
5511 }
5512
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005513 /**
5514 * Determines if the calling application is subject to metered network restrictions while
5515 * running on background.
5516 *
5517 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5518 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5519 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5520 */
5521 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5522 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005523 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005524 } catch (RemoteException e) {
5525 throw e.rethrowFromSystemServer();
5526 }
5527 }
5528
5529 /**
5530 * The network watchlist is a list of domains and IP addresses that are associated with
5531 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5532 * currently used by the system for validation purposes.
5533 *
5534 * @return Hash of network watchlist config file. Null if config does not exist.
5535 */
5536 @Nullable
5537 public byte[] getNetworkWatchlistConfigHash() {
5538 try {
5539 return mService.getNetworkWatchlistConfigHash();
5540 } catch (RemoteException e) {
5541 Log.e(TAG, "Unable to get watchlist config hash");
5542 throw e.rethrowFromSystemServer();
5543 }
5544 }
5545
5546 /**
5547 * Returns the {@code uid} of the owner of a network connection.
5548 *
5549 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5550 * IPPROTO_UDP} currently supported.
5551 * @param local The local {@link InetSocketAddress} of a connection.
5552 * @param remote The remote {@link InetSocketAddress} of a connection.
5553 * @return {@code uid} if the connection is found and the app has permission to observe it
5554 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5555 * android.os.Process#INVALID_UID} if the connection is not found.
Sherri Lin443b7182023-02-08 04:49:29 +01005556 * @throws SecurityException if the caller is not the active VpnService for the current
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005557 * user.
Sherri Lin443b7182023-02-08 04:49:29 +01005558 * @throws IllegalArgumentException if an unsupported protocol is requested.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005559 */
5560 public int getConnectionOwnerUid(
5561 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5562 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5563 try {
5564 return mService.getConnectionOwnerUid(connectionInfo);
5565 } catch (RemoteException e) {
5566 throw e.rethrowFromSystemServer();
5567 }
5568 }
5569
5570 private void printStackTrace() {
5571 if (DEBUG) {
5572 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5573 final StringBuffer sb = new StringBuffer();
5574 for (int i = 3; i < callStack.length; i++) {
5575 final String stackTrace = callStack[i].toString();
5576 if (stackTrace == null || stackTrace.contains("android.os")) {
5577 break;
5578 }
5579 sb.append(" [").append(stackTrace).append("]");
5580 }
5581 Log.d(TAG, "StackLog:" + sb.toString());
5582 }
5583 }
5584
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005585 /** @hide */
5586 public TestNetworkManager startOrGetTestNetworkManager() {
5587 final IBinder tnBinder;
5588 try {
5589 tnBinder = mService.startOrGetTestNetworkService();
5590 } catch (RemoteException e) {
5591 throw e.rethrowFromSystemServer();
5592 }
5593
5594 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5595 }
5596
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005597 /** @hide */
5598 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5599 return new ConnectivityDiagnosticsManager(mContext, mService);
5600 }
5601
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005602 /**
5603 * Simulates a Data Stall for the specified Network.
5604 *
5605 * <p>This method should only be used for tests.
5606 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005607 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5608 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005609 *
5610 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005611 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5612 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5613 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005614 * @param network The Network for which a Data Stall is being simluated.
5615 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5616 * @throws SecurityException if the caller is not the owner of the given network.
5617 * @hide
5618 */
5619 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5620 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5621 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005622 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005623 @NonNull Network network, @NonNull PersistableBundle extras) {
5624 try {
5625 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5626 } catch (RemoteException e) {
5627 e.rethrowFromSystemServer();
5628 }
5629 }
5630
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005631 @NonNull
5632 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5633
5634 /**
5635 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5636 * receive available QoS events related to the {@link Network} and local ip + port
5637 * specified within socketInfo.
5638 * <p/>
5639 * The same {@link QosCallback} must be unregistered before being registered a second time,
5640 * otherwise {@link QosCallbackRegistrationException} is thrown.
5641 * <p/>
5642 * This API does not, in itself, require any permission if called with a network that is not
5643 * restricted. However, the underlying implementation currently only supports the IMS network,
5644 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5645 * useful, because they'd never be called back on networks that they would have access to.
5646 *
5647 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5648 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5649 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5650 * @throws RuntimeException if the app already has too many callbacks registered.
5651 *
5652 * Exceptions after the time of registration is passed through
5653 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5654 *
5655 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005656 * @param executor The executor on which the callback will be invoked. The provided
5657 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005658 * callbacks cannot be guaranteed.onQosCallbackRegistered
5659 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005660 *
5661 * @hide
5662 */
5663 @SystemApi
5664 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005665 @CallbackExecutor @NonNull final Executor executor,
5666 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005667 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005668 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005669 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005670
5671 try {
5672 synchronized (mQosCallbackConnections) {
5673 if (getQosCallbackConnection(callback) == null) {
5674 final QosCallbackConnection connection =
5675 new QosCallbackConnection(this, callback, executor);
5676 mQosCallbackConnections.add(connection);
5677 mService.registerQosSocketCallback(socketInfo, connection);
5678 } else {
5679 Log.e(TAG, "registerQosCallback: Callback already registered");
5680 throw new QosCallbackRegistrationException();
5681 }
5682 }
5683 } catch (final RemoteException e) {
5684 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5685
5686 // The same unregister method method is called for consistency even though nothing
5687 // will be sent to the ConnectivityService since the callback was never successfully
5688 // registered.
5689 unregisterQosCallback(callback);
5690 e.rethrowFromSystemServer();
5691 } catch (final ServiceSpecificException e) {
5692 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5693 unregisterQosCallback(callback);
5694 throw convertServiceException(e);
5695 }
5696 }
5697
5698 /**
5699 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5700 * events once unregistered and can be registered a second time.
5701 * <p/>
5702 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5703 *
5704 * @param callback the callback being unregistered
5705 *
5706 * @hide
5707 */
5708 @SystemApi
5709 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5710 Objects.requireNonNull(callback, "The callback must be non-null");
5711 try {
5712 synchronized (mQosCallbackConnections) {
5713 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5714 if (connection != null) {
5715 connection.stopReceivingMessages();
5716 mService.unregisterQosCallback(connection);
5717 mQosCallbackConnections.remove(connection);
5718 } else {
5719 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5720 }
5721 }
5722 } catch (final RemoteException e) {
5723 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5724 e.rethrowFromSystemServer();
5725 }
5726 }
5727
5728 /**
5729 * Gets the connection related to the callback.
5730 *
5731 * @param callback the callback to look up
5732 * @return the related connection
5733 */
5734 @Nullable
5735 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5736 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5737 // Checking by reference here is intentional
5738 if (connection.getCallback() == callback) {
5739 return connection;
5740 }
5741 }
5742 return null;
5743 }
5744
5745 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005746 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005747 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5748 * be used to request that the system provide a network without causing the network to be
5749 * in the foreground.
5750 *
5751 * <p>This method will attempt to find the best network that matches the passed
5752 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5753 * criteria. The platform will evaluate which network is the best at its own discretion.
5754 * Throughput, latency, cost per byte, policy, user preference and other considerations
5755 * may be factored in the decision of what is considered the best network.
5756 *
5757 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5758 * matching this request, while always attempting to match the request to a better network if
5759 * possible. If a better match is found, the platform will switch this request to the now-best
5760 * network and inform the app of the newly best network by invoking
5761 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5762 * will not try to maintain any other network than the best one currently matching the request:
5763 * a network not matching any network request may be disconnected at any time.
5764 *
5765 * <p>For example, an application could use this method to obtain a connected cellular network
5766 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5767 * radio to consume additional power. Or, an application could inform the system that it wants
5768 * a network supporting sending MMSes and have the system let it know about the currently best
5769 * MMS-supporting network through the provided {@link NetworkCallback}.
5770 *
5771 * <p>The status of the request can be followed by listening to the various callbacks described
5772 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5773 * used to direct traffic to the network (although accessing some networks may be subject to
5774 * holding specific permissions). Callers will learn about the specific characteristics of the
5775 * network through
5776 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5777 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5778 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5779 * matching the request at any given time; therefore when a better network matching the request
5780 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5781 * with the new network after which no further updates are given about the previously-best
5782 * network, unless it becomes the best again at some later time. All callbacks are invoked
5783 * in order on the same thread, which by default is a thread created by the framework running
5784 * in the app.
5785 *
5786 * <p>This{@link NetworkRequest} will live until released via
5787 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5788 * which point the system may let go of the network at any time.
5789 *
5790 * <p>It is presently unsupported to request a network with mutable
5791 * {@link NetworkCapabilities} such as
5792 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5793 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5794 * as these {@code NetworkCapabilities} represent states that a particular
5795 * network may never attain, and whether a network will attain these states
5796 * is unknown prior to bringing up the network so the framework does not
5797 * know how to go about satisfying a request with these capabilities.
5798 *
5799 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5800 * number of outstanding requests to 100 per app (identified by their UID), shared with
5801 * all variants of this method, of {@link #registerNetworkCallback} as well as
5802 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5803 * Requesting a network with this method will count toward this limit. If this limit is
5804 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5805 * make sure to unregister the callbacks with
5806 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5807 *
5808 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005809 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5810 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005811 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5812 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005813 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5814 * @throws SecurityException if missing the appropriate permissions.
5815 * @throws RuntimeException if the app already has too many callbacks registered.
5816 *
5817 * @hide
5818 */
5819 @SystemApi(client = MODULE_LIBRARIES)
5820 @SuppressLint("ExecutorRegistration")
5821 @RequiresPermission(anyOf = {
5822 android.Manifest.permission.NETWORK_SETTINGS,
5823 android.Manifest.permission.NETWORK_STACK,
5824 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5825 })
5826 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005827 @NonNull NetworkCallback networkCallback,
5828 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005829 final NetworkCapabilities nc = request.networkCapabilities;
5830 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005831 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005832 }
James Mattis12aeab82021-01-10 14:24:24 -08005833
5834 /**
James Mattis12aeab82021-01-10 14:24:24 -08005835 * Used by automotive devices to set the network preferences used to direct traffic at an
5836 * application level as per the given OemNetworkPreferences. An example use-case would be an
5837 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5838 * vehicle via a particular network.
5839 *
5840 * Calling this will overwrite the existing preference.
5841 *
5842 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5843 * @param executor the executor on which listener will be invoked.
5844 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5845 * communicate completion of setOemNetworkPreference(). This will only be
5846 * called once upon successful completion of setOemNetworkPreference().
5847 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5848 * @throws SecurityException if missing the appropriate permissions.
5849 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005850 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005851 */
James Mattis6e2d7022021-01-26 16:23:52 -08005852 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005853 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005854 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005855 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005856 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005857 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5858 if (null != listener) {
5859 Objects.requireNonNull(executor, "Executor must be non-null");
5860 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005861 final IOnCompleteListener listenerInternal = listener == null ? null :
5862 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005863 @Override
5864 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005865 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005866 }
5867 };
5868
5869 try {
5870 mService.setOemNetworkPreference(preference, listenerInternal);
5871 } catch (RemoteException e) {
5872 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5873 throw e.rethrowFromSystemServer();
5874 }
5875 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005876
Chalard Jeanad565e22021-02-25 17:23:40 +09005877 /**
5878 * Request that a user profile is put by default on a network matching a given preference.
5879 *
5880 * See the documentation for the individual preferences for a description of the supported
5881 * behaviors.
5882 *
5883 * @param profile the profile concerned.
5884 * @param preference the preference for this profile.
5885 * @param executor an executor to execute the listener on. Optional if listener is null.
5886 * @param listener an optional listener to listen for completion of the operation.
5887 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5888 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005889 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5890 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005891 * @hide
5892 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005893 // This function is for establishing per-profile default networking and can only be called by
5894 // the device policy manager, running as the system server. It would make no sense to call it
5895 // on a context for a user because it does not establish a setting on behalf of a user, rather
5896 // it establishes a setting for a user on behalf of the DPM.
5897 @SuppressLint({"UserHandle"})
5898 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005899 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005900 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005901 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005902 @ProfileNetworkPreferencePolicy final int preference,
5903 @Nullable @CallbackExecutor final Executor executor,
5904 @Nullable final Runnable listener) {
5905
5906 ProfileNetworkPreference.Builder preferenceBuilder =
5907 new ProfileNetworkPreference.Builder();
5908 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005909 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5910 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5911 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005912 setProfileNetworkPreferences(profile,
5913 List.of(preferenceBuilder.build()), executor, listener);
5914 }
5915
5916 /**
5917 * Set a list of default network selection policies for a user profile.
5918 *
5919 * Calling this API with a user handle defines the entire policy for that user handle.
5920 * It will overwrite any setting previously set for the same user profile,
5921 * and not affect previously set settings for other handles.
5922 *
5923 * Call this API with an empty list to remove settings for this user profile.
5924 *
5925 * See {@link ProfileNetworkPreference} for more details on each preference
5926 * parameter.
5927 *
5928 * @param profile the user profile for which the preference is being set.
5929 * @param profileNetworkPreferences the list of profile network preferences for the
5930 * provided profile.
5931 * @param executor an executor to execute the listener on. Optional if listener is null.
5932 * @param listener an optional listener to listen for completion of the operation.
5933 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5934 * @throws SecurityException if missing the appropriate permissions.
5935 * @hide
5936 */
5937 @SystemApi(client = MODULE_LIBRARIES)
5938 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5939 public void setProfileNetworkPreferences(
5940 @NonNull final UserHandle profile,
5941 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005942 @Nullable @CallbackExecutor final Executor executor,
5943 @Nullable final Runnable listener) {
5944 if (null != listener) {
5945 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5946 }
5947 final IOnCompleteListener proxy;
5948 if (null == listener) {
5949 proxy = null;
5950 } else {
5951 proxy = new IOnCompleteListener.Stub() {
5952 @Override
5953 public void onComplete() {
5954 executor.execute(listener::run);
5955 }
5956 };
5957 }
5958 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005959 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005960 } catch (RemoteException e) {
5961 throw e.rethrowFromSystemServer();
5962 }
5963 }
5964
lucaslin5cdbcfb2021-03-12 00:46:33 +08005965 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005966 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005967 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005968 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005969
5970 /**
5971 * Get the network ID range reserved for IPSec tunnel interfaces.
5972 *
5973 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5974 * @hide
5975 */
5976 @SystemApi(client = MODULE_LIBRARIES)
5977 @NonNull
5978 public static Range<Integer> getIpSecNetIdRange() {
5979 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5980 }
markchien738ad912021-12-09 18:15:45 +08005981
5982 /**
Junyu Laidf210362023-10-24 02:47:50 +00005983 * Sets data saver switch.
5984 *
5985 * @param enable True if enable.
5986 * @throws IllegalStateException if failed.
5987 * @hide
5988 */
5989 @FlaggedApi(Flags.SET_DATA_SAVER_VIA_CM)
5990 @SystemApi(client = MODULE_LIBRARIES)
5991 @RequiresPermission(anyOf = {
5992 android.Manifest.permission.NETWORK_SETTINGS,
5993 android.Manifest.permission.NETWORK_STACK,
5994 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5995 })
5996 public void setDataSaverEnabled(final boolean enable) {
5997 try {
5998 mService.setDataSaverEnabled(enable);
5999 } catch (RemoteException e) {
6000 throw e.rethrowFromSystemServer();
6001 }
6002 }
6003
6004 /**
markchiene46042b2022-03-02 18:07:35 +08006005 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
6006 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08006007 *
6008 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006009 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08006010 * @hide
6011 */
6012 @SystemApi(client = MODULE_LIBRARIES)
6013 @RequiresPermission(anyOf = {
6014 android.Manifest.permission.NETWORK_SETTINGS,
6015 android.Manifest.permission.NETWORK_STACK,
6016 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6017 })
markchiene46042b2022-03-02 18:07:35 +08006018 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006019 try {
markchiene46042b2022-03-02 18:07:35 +08006020 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08006021 } catch (RemoteException e) {
6022 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006023 }
6024 }
6025
6026 /**
markchiene46042b2022-03-02 18:07:35 +08006027 * Removes the specified UID from the list of UIDs that are allowed to use background data on
6028 * metered networks when background data is restricted. The deny list takes precedence over
6029 * the allow list.
6030 *
6031 * @param uid uid of target app
6032 * @throws IllegalStateException if updating allow list failed.
6033 * @hide
6034 */
6035 @SystemApi(client = MODULE_LIBRARIES)
6036 @RequiresPermission(anyOf = {
6037 android.Manifest.permission.NETWORK_SETTINGS,
6038 android.Manifest.permission.NETWORK_STACK,
6039 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6040 })
6041 public void removeUidFromMeteredNetworkAllowList(final int uid) {
6042 try {
6043 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
6044 } catch (RemoteException e) {
6045 throw e.rethrowFromSystemServer();
6046 }
6047 }
6048
6049 /**
6050 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
6051 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08006052 *
6053 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006054 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08006055 * @hide
6056 */
6057 @SystemApi(client = MODULE_LIBRARIES)
6058 @RequiresPermission(anyOf = {
6059 android.Manifest.permission.NETWORK_SETTINGS,
6060 android.Manifest.permission.NETWORK_STACK,
6061 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6062 })
markchiene46042b2022-03-02 18:07:35 +08006063 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006064 try {
markchiene46042b2022-03-02 18:07:35 +08006065 mService.updateMeteredNetworkDenyList(uid, true /* add */);
6066 } catch (RemoteException e) {
6067 throw e.rethrowFromSystemServer();
6068 }
6069 }
6070
6071 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09006072 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08006073 * networks if background data is not restricted. The deny list takes precedence over the
6074 * allow list.
6075 *
6076 * @param uid uid of target app
6077 * @throws IllegalStateException if updating deny list failed.
6078 * @hide
6079 */
6080 @SystemApi(client = MODULE_LIBRARIES)
6081 @RequiresPermission(anyOf = {
6082 android.Manifest.permission.NETWORK_SETTINGS,
6083 android.Manifest.permission.NETWORK_STACK,
6084 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6085 })
6086 public void removeUidFromMeteredNetworkDenyList(final int uid) {
6087 try {
6088 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08006089 } catch (RemoteException e) {
6090 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08006091 }
6092 }
6093
6094 /**
6095 * Sets a firewall rule for the specified UID on the specified chain.
6096 *
6097 * @param chain target chain.
6098 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08006099 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08006100 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08006101 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08006102 * @hide
6103 */
6104 @SystemApi(client = MODULE_LIBRARIES)
6105 @RequiresPermission(anyOf = {
6106 android.Manifest.permission.NETWORK_SETTINGS,
6107 android.Manifest.permission.NETWORK_STACK,
6108 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6109 })
markchien3c04e662022-03-22 16:29:56 +08006110 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
6111 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08006112 try {
markchien3c04e662022-03-22 16:29:56 +08006113 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08006114 } catch (RemoteException e) {
6115 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006116 }
6117 }
markchien98a6f952022-01-13 23:43:53 +08006118
6119 /**
Motomu Utsumi900b8062023-01-19 16:16:49 +09006120 * Get firewall rule of specified firewall chain on specified uid.
6121 *
6122 * @param chain target chain.
6123 * @param uid target uid
6124 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
6125 * @throws UnsupportedOperationException if called on pre-T devices.
6126 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6127 * cause of the failure.
6128 * @hide
6129 */
6130 @RequiresPermission(anyOf = {
6131 android.Manifest.permission.NETWORK_SETTINGS,
6132 android.Manifest.permission.NETWORK_STACK,
6133 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6134 })
6135 public int getUidFirewallRule(@FirewallChain final int chain, final int uid) {
6136 try {
6137 return mService.getUidFirewallRule(chain, uid);
6138 } catch (RemoteException e) {
6139 throw e.rethrowFromSystemServer();
6140 }
6141 }
6142
6143 /**
markchien98a6f952022-01-13 23:43:53 +08006144 * Enables or disables the specified firewall chain.
6145 *
6146 * @param chain target chain.
6147 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00006148 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08006149 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08006150 * @hide
6151 */
6152 @SystemApi(client = MODULE_LIBRARIES)
6153 @RequiresPermission(anyOf = {
6154 android.Manifest.permission.NETWORK_SETTINGS,
6155 android.Manifest.permission.NETWORK_STACK,
6156 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6157 })
6158 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
6159 try {
6160 mService.setFirewallChainEnabled(chain, enable);
6161 } catch (RemoteException e) {
6162 throw e.rethrowFromSystemServer();
6163 }
6164 }
markchien00a0bed2022-01-13 23:46:13 +08006165
6166 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00006167 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006168 *
6169 * @param chain target chain.
6170 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6171 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006172 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6173 * cause of the failure.
6174 * @hide
6175 */
6176 @RequiresPermission(anyOf = {
6177 android.Manifest.permission.NETWORK_SETTINGS,
6178 android.Manifest.permission.NETWORK_STACK,
6179 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6180 })
6181 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6182 try {
6183 return mService.getFirewallChainEnabled(chain);
6184 } catch (RemoteException e) {
6185 throw e.rethrowFromSystemServer();
6186 }
6187 }
6188
6189 /**
markchien00a0bed2022-01-13 23:46:13 +08006190 * Replaces the contents of the specified UID-based firewall chain.
6191 *
6192 * @param chain target chain to replace.
6193 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006194 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006195 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6196 * @hide
6197 */
6198 @SystemApi(client = MODULE_LIBRARIES)
6199 @RequiresPermission(anyOf = {
6200 android.Manifest.permission.NETWORK_SETTINGS,
6201 android.Manifest.permission.NETWORK_STACK,
6202 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6203 })
6204 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6205 Objects.requireNonNull(uids);
6206 try {
6207 mService.replaceFirewallChain(chain, uids);
6208 } catch (RemoteException e) {
6209 throw e.rethrowFromSystemServer();
6210 }
6211 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006212
Junyu Laie0031522023-08-29 18:32:57 +08006213 /**
Junyu Laic3dc5b62023-09-06 19:10:02 +08006214 * Helper class to track data saver status.
6215 *
6216 * The class will fetch current data saver status from {@link NetworkPolicyManager} when
6217 * initialized, and listening for status changed intent to cache the latest status.
6218 *
6219 * @hide
6220 */
6221 @TargetApi(Build.VERSION_CODES.TIRAMISU) // RECEIVER_NOT_EXPORTED requires T.
6222 @VisibleForTesting(visibility = PRIVATE)
6223 public static class DataSaverStatusTracker extends BroadcastReceiver {
6224 private static final Object sDataSaverStatusTrackerLock = new Object();
6225
6226 private static volatile DataSaverStatusTracker sInstance;
6227
6228 /**
6229 * Gets a static instance of the class.
6230 *
6231 * @param context A {@link Context} for initialization. Note that since the data saver
6232 * status is global on a device, passing any context is equivalent.
6233 * @return The static instance of a {@link DataSaverStatusTracker}.
6234 */
6235 public static DataSaverStatusTracker getInstance(@NonNull Context context) {
6236 if (sInstance == null) {
6237 synchronized (sDataSaverStatusTrackerLock) {
6238 if (sInstance == null) {
6239 sInstance = new DataSaverStatusTracker(context);
6240 }
6241 }
6242 }
6243 return sInstance;
6244 }
6245
6246 private final NetworkPolicyManager mNpm;
6247 // The value updates on the caller's binder thread or UI thread.
6248 private final AtomicBoolean mIsDataSaverEnabled;
6249
6250 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6251 public DataSaverStatusTracker(final Context context) {
6252 // To avoid leaks, take the application context.
6253 final Context appContext;
6254 if (context instanceof Application) {
6255 appContext = context;
6256 } else {
6257 appContext = context.getApplicationContext();
6258 }
6259
6260 if ((appContext.getApplicationInfo().flags & FLAG_PERSISTENT) == 0
6261 && (appContext.getApplicationInfo().flags & FLAG_SYSTEM) == 0) {
6262 throw new IllegalStateException("Unexpected caller: "
6263 + appContext.getApplicationInfo().packageName);
6264 }
6265
6266 mNpm = appContext.getSystemService(NetworkPolicyManager.class);
6267 final IntentFilter filter = new IntentFilter(
6268 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
6269 // The receiver should not receive broadcasts from other Apps.
6270 appContext.registerReceiver(this, filter, Context.RECEIVER_NOT_EXPORTED);
6271 mIsDataSaverEnabled = new AtomicBoolean();
6272 updateDataSaverEnabled();
6273 }
6274
6275 // Runs on caller's UI thread.
6276 @Override
6277 public void onReceive(Context context, Intent intent) {
6278 if (intent.getAction().equals(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED)) {
6279 updateDataSaverEnabled();
6280 } else {
6281 throw new IllegalStateException("Unexpected intent " + intent);
6282 }
6283 }
6284
6285 public boolean getDataSaverEnabled() {
6286 return mIsDataSaverEnabled.get();
6287 }
6288
6289 private void updateDataSaverEnabled() {
6290 // Uid doesn't really matter, but use a fixed UID to make things clearer.
6291 final int dataSaverForCallerUid = mNpm.getRestrictBackgroundStatus(Process.SYSTEM_UID);
6292 mIsDataSaverEnabled.set(dataSaverForCallerUid
6293 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
6294 }
6295 }
6296
6297 /**
6298 * Return whether the network is blocked for the given uid and metered condition.
Junyu Laie0031522023-08-29 18:32:57 +08006299 *
6300 * Similar to {@link NetworkPolicyManager#isUidNetworkingBlocked}, but directly reads the BPF
6301 * maps and therefore considerably faster. For use by the NetworkStack process only.
6302 *
6303 * @param uid The target uid.
Junyu Laic3dc5b62023-09-06 19:10:02 +08006304 * @param isNetworkMetered Whether the target network is metered.
6305 *
6306 * @return True if all networking with the given condition is blocked. Otherwise, false.
Junyu Laie0031522023-08-29 18:32:57 +08006307 * @throws IllegalStateException if the map cannot be opened.
6308 * @throws ServiceSpecificException if the read fails.
6309 * @hide
6310 */
6311 // This isn't protected by a standard Android permission since it can't
6312 // afford to do IPC for performance reasons. Instead, the access control
6313 // is provided by linux file group permission AID_NET_BW_ACCT and the
6314 // selinux context fs_bpf_net*.
6315 // Only the system server process and the network stack have access.
Junyu Laibb594802023-09-04 11:37:03 +08006316 @FlaggedApi(Flags.SUPPORT_IS_UID_NETWORKING_BLOCKED)
6317 @SystemApi(client = MODULE_LIBRARIES)
Junyu Laie0031522023-08-29 18:32:57 +08006318 @RequiresApi(Build.VERSION_CODES.TIRAMISU) // BPF maps were only mainlined in T
6319 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Junyu Laic3dc5b62023-09-06 19:10:02 +08006320 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Junyu Laie0031522023-08-29 18:32:57 +08006321 final BpfNetMapsReader reader = BpfNetMapsReader.getInstance();
6322
Junyu Laic3dc5b62023-09-06 19:10:02 +08006323 final boolean isDataSaverEnabled;
6324 // TODO: For U-QPR3+ devices, get data saver status from bpf configuration map directly.
6325 final DataSaverStatusTracker dataSaverStatusTracker =
6326 DataSaverStatusTracker.getInstance(mContext);
6327 isDataSaverEnabled = dataSaverStatusTracker.getDataSaverEnabled();
Junyu Laie0031522023-08-29 18:32:57 +08006328
Junyu Laic3dc5b62023-09-06 19:10:02 +08006329 return reader.isUidNetworkingBlocked(uid, isNetworkMetered, isDataSaverEnabled);
Junyu Laie0031522023-08-29 18:32:57 +08006330 }
6331
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006332 /** @hide */
6333 public IBinder getCompanionDeviceManagerProxyService() {
6334 try {
6335 return mService.getCompanionDeviceManagerProxyService();
6336 } catch (RemoteException e) {
6337 throw e.rethrowFromSystemServer();
6338 }
6339 }
Chalard Jean2fb66f12023-08-25 12:50:37 +09006340
6341 private static final Object sRoutingCoordinatorManagerLock = new Object();
6342 @GuardedBy("sRoutingCoordinatorManagerLock")
6343 private static RoutingCoordinatorManager sRoutingCoordinatorManager = null;
6344 /** @hide */
6345 @RequiresApi(Build.VERSION_CODES.S)
6346 public RoutingCoordinatorManager getRoutingCoordinatorManager() {
6347 try {
6348 synchronized (sRoutingCoordinatorManagerLock) {
6349 if (null == sRoutingCoordinatorManager) {
6350 sRoutingCoordinatorManager = new RoutingCoordinatorManager(mContext,
6351 IRoutingCoordinator.Stub.asInterface(
6352 mService.getRoutingCoordinatorService()));
6353 }
6354 return sRoutingCoordinatorManager;
6355 }
6356 } catch (RemoteException e) {
6357 throw e.rethrowFromSystemServer();
6358 }
6359 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006360}