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