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