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