blob: a94db27505abd725c4b2fe82526d9188886773aa [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 /**
Chalard Jeanad565e22021-02-25 17:23:40 +09001123 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1124 * Specify that the traffic for this user should by follow the default rules.
1125 * @hide
1126 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001127 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001128 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1129
1130 /**
1131 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1132 * Specify that the traffic for this user should by default go on a network with
1133 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1134 * if no such network is available.
1135 * @hide
1136 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001137 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001138 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1139
1140 /** @hide */
1141 @Retention(RetentionPolicy.SOURCE)
1142 @IntDef(value = {
1143 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1144 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1145 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001146 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001147 }
1148
1149 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001150 * Specifies the preferred network type. When the device has more
1151 * than one type available the preferred network type will be used.
1152 *
1153 * @param preference the network type to prefer over all others. It is
1154 * unspecified what happens to the old preferred network in the
1155 * overall ordering.
1156 * @deprecated Functionality has been removed as it no longer makes sense,
1157 * with many more than two networks - we'd need an array to express
1158 * preference. Instead we use dynamic network properties of
1159 * the networks to describe their precedence.
1160 */
1161 @Deprecated
1162 public void setNetworkPreference(int preference) {
1163 }
1164
1165 /**
1166 * Retrieves the current preferred network type.
1167 *
1168 * @return an integer representing the preferred network type
1169 *
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 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1177 public int getNetworkPreference() {
1178 return TYPE_NONE;
1179 }
1180
1181 /**
1182 * Returns details about the currently active default data network. When
1183 * connected, this network is the default route for outgoing connections.
1184 * You should always check {@link NetworkInfo#isConnected()} before initiating
1185 * network traffic. This may return {@code null} when there is no default
1186 * network.
1187 * Note that if the default network is a VPN, this method will return the
1188 * NetworkInfo for one of its underlying networks instead, or null if the
1189 * VPN agent did not specify any. Apps interested in learning about VPNs
1190 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1191 *
1192 * @return a {@link NetworkInfo} object for the current default network
1193 * or {@code null} if no default network is currently active
1194 * @deprecated See {@link NetworkInfo}.
1195 */
1196 @Deprecated
1197 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1198 @Nullable
1199 public NetworkInfo getActiveNetworkInfo() {
1200 try {
1201 return mService.getActiveNetworkInfo();
1202 } catch (RemoteException e) {
1203 throw e.rethrowFromSystemServer();
1204 }
1205 }
1206
1207 /**
1208 * Returns a {@link Network} object corresponding to the currently active
1209 * default data network. In the event that the current active default data
1210 * network disconnects, the returned {@code Network} object will no longer
1211 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001212 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001213 *
1214 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001215 * {@code null} if no default network is currently active or if
1216 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001217 */
1218 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1219 @Nullable
1220 public Network getActiveNetwork() {
1221 try {
1222 return mService.getActiveNetwork();
1223 } catch (RemoteException e) {
1224 throw e.rethrowFromSystemServer();
1225 }
1226 }
1227
1228 /**
1229 * Returns a {@link Network} object corresponding to the currently active
1230 * default data network for a specific UID. In the event that the default data
1231 * network disconnects, the returned {@code Network} object will no longer
1232 * be usable. This will return {@code null} when there is no default
1233 * network for the UID.
1234 *
1235 * @return a {@link Network} object for the current default network for the
1236 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001237 *
1238 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001239 */
1240 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1241 @Nullable
1242 public Network getActiveNetworkForUid(int uid) {
1243 return getActiveNetworkForUid(uid, false);
1244 }
1245
1246 /** {@hide} */
1247 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1248 try {
1249 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1250 } catch (RemoteException e) {
1251 throw e.rethrowFromSystemServer();
1252 }
1253 }
1254
1255 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001256 * Adds or removes a requirement for given UID ranges to use the VPN.
1257 *
1258 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1259 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1260 * otherwise have permission to bypass the VPN (e.g., because they have the
1261 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1262 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1263 * set to {@code false}, a previously-added restriction is removed.
1264 * <p>
1265 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1266 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1267 * remove a previously-added range, the exact range must be removed as is.
1268 * <p>
1269 * The changes are applied asynchronously and may not have been applied by the time the method
1270 * returns. Apps will be notified about any changes that apply to them via
1271 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1272 * effect.
1273 * <p>
1274 * This method should be called only by the VPN code.
1275 *
1276 * @param ranges the UID ranges to restrict
1277 * @param requireVpn whether the specified UID ranges must use a VPN
1278 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001279 * @hide
1280 */
1281 @RequiresPermission(anyOf = {
1282 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001283 android.Manifest.permission.NETWORK_STACK,
1284 android.Manifest.permission.NETWORK_SETTINGS})
1285 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001286 public void setRequireVpnForUids(boolean requireVpn,
1287 @NonNull Collection<Range<Integer>> ranges) {
1288 Objects.requireNonNull(ranges);
1289 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1290 // This method is not necessarily expected to be used outside the system server, so
1291 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1292 // stack process, or by tests.
1293 UidRange[] rangesArray = new UidRange[ranges.size()];
1294 int index = 0;
1295 for (Range<Integer> range : ranges) {
1296 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1297 }
1298 try {
1299 mService.setRequireVpnForUids(requireVpn, rangesArray);
1300 } catch (RemoteException e) {
1301 throw e.rethrowFromSystemServer();
1302 }
1303 }
1304
1305 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001306 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1307 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1308 * but is still supported for backwards compatibility.
1309 * <p>
1310 * This type of VPN is assumed always to use the system default network, and must always declare
1311 * exactly one underlying network, which is the network that was the default when the VPN
1312 * connected.
1313 * <p>
1314 * Calling this method with {@code true} enables legacy behaviour, specifically:
1315 * <ul>
1316 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1317 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1318 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1319 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1320 * underlying the VPN.</li>
1321 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1322 * similarly replaced by the VPN network state.</li>
1323 * <li>Information on current network interfaces passed to NetworkStatsService will not
1324 * include any VPN interfaces.</li>
1325 * </ul>
1326 *
1327 * @param enabled whether legacy lockdown VPN is enabled or disabled
1328 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001329 * @hide
1330 */
1331 @RequiresPermission(anyOf = {
1332 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001333 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001334 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001335 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001336 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1337 try {
1338 mService.setLegacyLockdownVpnEnabled(enabled);
1339 } catch (RemoteException e) {
1340 throw e.rethrowFromSystemServer();
1341 }
1342 }
1343
1344 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001345 * Returns details about the currently active default data network
1346 * for a given uid. This is for internal use only to avoid spying
1347 * other apps.
1348 *
1349 * @return a {@link NetworkInfo} object for the current default network
1350 * for the given uid or {@code null} if no default network is
1351 * available for the specified uid.
1352 *
1353 * {@hide}
1354 */
1355 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1356 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1357 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1358 return getActiveNetworkInfoForUid(uid, false);
1359 }
1360
1361 /** {@hide} */
1362 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1363 try {
1364 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1365 } catch (RemoteException e) {
1366 throw e.rethrowFromSystemServer();
1367 }
1368 }
1369
1370 /**
1371 * Returns connection status information about a particular
1372 * network type.
1373 *
1374 * @param networkType integer specifying which networkType in
1375 * which you're interested.
1376 * @return a {@link NetworkInfo} object for the requested
1377 * network type or {@code null} if the type is not
1378 * supported by the device. If {@code networkType} is
1379 * TYPE_VPN and a VPN is active for the calling app,
1380 * then this method will try to return one of the
1381 * underlying networks for the VPN or null if the
1382 * VPN agent didn't specify any.
1383 *
1384 * @deprecated This method does not support multiple connected networks
1385 * of the same type. Use {@link #getAllNetworks} and
1386 * {@link #getNetworkInfo(android.net.Network)} instead.
1387 */
1388 @Deprecated
1389 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1390 @Nullable
1391 public NetworkInfo getNetworkInfo(int networkType) {
1392 try {
1393 return mService.getNetworkInfo(networkType);
1394 } catch (RemoteException e) {
1395 throw e.rethrowFromSystemServer();
1396 }
1397 }
1398
1399 /**
1400 * Returns connection status information about a particular
1401 * Network.
1402 *
1403 * @param network {@link Network} specifying which network
1404 * in which you're interested.
1405 * @return a {@link NetworkInfo} object for the requested
1406 * network or {@code null} if the {@code Network}
1407 * is not valid.
1408 * @deprecated See {@link NetworkInfo}.
1409 */
1410 @Deprecated
1411 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1412 @Nullable
1413 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1414 return getNetworkInfoForUid(network, Process.myUid(), false);
1415 }
1416
1417 /** {@hide} */
1418 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1419 try {
1420 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1421 } catch (RemoteException e) {
1422 throw e.rethrowFromSystemServer();
1423 }
1424 }
1425
1426 /**
1427 * Returns connection status information about all network
1428 * types supported by the device.
1429 *
1430 * @return an array of {@link NetworkInfo} objects. Check each
1431 * {@link NetworkInfo#getType} for which type each applies.
1432 *
1433 * @deprecated This method does not support multiple connected networks
1434 * of the same type. Use {@link #getAllNetworks} and
1435 * {@link #getNetworkInfo(android.net.Network)} instead.
1436 */
1437 @Deprecated
1438 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1439 @NonNull
1440 public NetworkInfo[] getAllNetworkInfo() {
1441 try {
1442 return mService.getAllNetworkInfo();
1443 } catch (RemoteException e) {
1444 throw e.rethrowFromSystemServer();
1445 }
1446 }
1447
1448 /**
junyulaib1211372021-03-03 12:09:05 +08001449 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1450 * connected.
1451 * @hide
1452 */
1453 @SystemApi(client = MODULE_LIBRARIES)
1454 @RequiresPermission(anyOf = {
1455 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1456 android.Manifest.permission.NETWORK_STACK,
1457 android.Manifest.permission.NETWORK_SETTINGS})
1458 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001459 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001460 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001461 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001462 } catch (RemoteException e) {
1463 throw e.rethrowFromSystemServer();
1464 }
1465 }
1466
1467 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001468 * Returns the {@link Network} object currently serving a given type, or
1469 * null if the given type is not connected.
1470 *
1471 * @hide
1472 * @deprecated This method does not support multiple connected networks
1473 * of the same type. Use {@link #getAllNetworks} and
1474 * {@link #getNetworkInfo(android.net.Network)} instead.
1475 */
1476 @Deprecated
1477 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1478 @UnsupportedAppUsage
1479 public Network getNetworkForType(int networkType) {
1480 try {
1481 return mService.getNetworkForType(networkType);
1482 } catch (RemoteException e) {
1483 throw e.rethrowFromSystemServer();
1484 }
1485 }
1486
1487 /**
1488 * Returns an array of all {@link Network} currently tracked by the
1489 * framework.
1490 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001491 * @deprecated This method does not provide any notification of network state changes, forcing
1492 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1493 * Apps should use methods such as
1494 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1495 * Apps that desire to obtain information about networks that do not apply to them
1496 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1497 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001498 * @return an array of {@link Network} objects.
1499 */
1500 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1501 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001502 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001503 public Network[] getAllNetworks() {
1504 try {
1505 return mService.getAllNetworks();
1506 } catch (RemoteException e) {
1507 throw e.rethrowFromSystemServer();
1508 }
1509 }
1510
1511 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001512 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001513 * the Networks that applications run by the given user will use by default.
1514 * @hide
1515 */
1516 @UnsupportedAppUsage
1517 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1518 try {
1519 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001520 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001521 } catch (RemoteException e) {
1522 throw e.rethrowFromSystemServer();
1523 }
1524 }
1525
1526 /**
1527 * Returns the IP information for the current default network.
1528 *
1529 * @return a {@link LinkProperties} object describing the IP info
1530 * for the current default network, or {@code null} if there
1531 * is no current default network.
1532 *
1533 * {@hide}
1534 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1535 * value of {@link #getActiveNetwork()} instead. In particular,
1536 * this method will return non-null LinkProperties even if the
1537 * app is blocked by policy from using this network.
1538 */
1539 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1540 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1541 public LinkProperties getActiveLinkProperties() {
1542 try {
1543 return mService.getActiveLinkProperties();
1544 } catch (RemoteException e) {
1545 throw e.rethrowFromSystemServer();
1546 }
1547 }
1548
1549 /**
1550 * Returns the IP information for a given network type.
1551 *
1552 * @param networkType the network type of interest.
1553 * @return a {@link LinkProperties} object describing the IP info
1554 * for the given networkType, or {@code null} if there is
1555 * no current default network.
1556 *
1557 * {@hide}
1558 * @deprecated This method does not support multiple connected networks
1559 * of the same type. Use {@link #getAllNetworks},
1560 * {@link #getNetworkInfo(android.net.Network)}, and
1561 * {@link #getLinkProperties(android.net.Network)} instead.
1562 */
1563 @Deprecated
1564 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1565 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1566 public LinkProperties getLinkProperties(int networkType) {
1567 try {
1568 return mService.getLinkPropertiesForType(networkType);
1569 } catch (RemoteException e) {
1570 throw e.rethrowFromSystemServer();
1571 }
1572 }
1573
1574 /**
1575 * Get the {@link LinkProperties} for the given {@link Network}. This
1576 * will return {@code null} if the network is unknown.
1577 *
1578 * @param network The {@link Network} object identifying the network in question.
1579 * @return The {@link LinkProperties} for the network, or {@code null}.
1580 */
1581 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1582 @Nullable
1583 public LinkProperties getLinkProperties(@Nullable Network network) {
1584 try {
1585 return mService.getLinkProperties(network);
1586 } catch (RemoteException e) {
1587 throw e.rethrowFromSystemServer();
1588 }
1589 }
1590
1591 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001592 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Chalard Jean070bdd42021-04-30 20:22:10 +09001593 * will return {@code null} if the network is unknown or if the |network| argument is null.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001594 *
Roshan Piuse08bc182020-12-22 15:10:42 -08001595 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1596 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1597 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1598 * this location sensitive information (subject to app's location permissions) will be
1599 * noted by system. To include any location sensitive data in {@link TransportInfo},
1600 * use a {@link NetworkCallback} with
1601 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1602 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001603 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001604 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001605 */
1606 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1607 @Nullable
1608 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1609 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001610 return mService.getNetworkCapabilities(
1611 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001612 } catch (RemoteException e) {
1613 throw e.rethrowFromSystemServer();
1614 }
1615 }
1616
1617 /**
1618 * Gets a URL that can be used for resolving whether a captive portal is present.
1619 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1620 * portal is present.
1621 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1622 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1623 *
1624 * The system network validation may be using different strategies to detect captive portals,
1625 * so this method does not necessarily return a URL used by the system. It only returns a URL
1626 * that may be relevant for other components trying to detect captive portals.
1627 *
1628 * @hide
1629 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1630 * system.
1631 */
1632 @Deprecated
1633 @SystemApi
1634 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1635 public String getCaptivePortalServerUrl() {
1636 try {
1637 return mService.getCaptivePortalServerUrl();
1638 } catch (RemoteException e) {
1639 throw e.rethrowFromSystemServer();
1640 }
1641 }
1642
1643 /**
1644 * Tells the underlying networking system that the caller wants to
1645 * begin using the named feature. The interpretation of {@code feature}
1646 * is completely up to each networking implementation.
1647 *
1648 * <p>This method requires the caller to hold either the
1649 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1650 * or the ability to modify system settings as determined by
1651 * {@link android.provider.Settings.System#canWrite}.</p>
1652 *
1653 * @param networkType specifies which network the request pertains to
1654 * @param feature the name of the feature to be used
1655 * @return an integer value representing the outcome of the request.
1656 * The interpretation of this value is specific to each networking
1657 * implementation+feature combination, except that the value {@code -1}
1658 * always indicates failure.
1659 *
1660 * @deprecated Deprecated in favor of the cleaner
1661 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1662 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1663 * throw {@code UnsupportedOperationException} if called.
1664 * @removed
1665 */
1666 @Deprecated
1667 public int startUsingNetworkFeature(int networkType, String feature) {
1668 checkLegacyRoutingApiAccess();
1669 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1670 if (netCap == null) {
1671 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1672 feature);
1673 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1674 }
1675
1676 NetworkRequest request = null;
1677 synchronized (sLegacyRequests) {
1678 LegacyRequest l = sLegacyRequests.get(netCap);
1679 if (l != null) {
1680 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1681 renewRequestLocked(l);
1682 if (l.currentNetwork != null) {
1683 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1684 } else {
1685 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1686 }
1687 }
1688
1689 request = requestNetworkForFeatureLocked(netCap);
1690 }
1691 if (request != null) {
1692 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1693 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1694 } else {
1695 Log.d(TAG, " request Failed");
1696 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1697 }
1698 }
1699
1700 /**
1701 * Tells the underlying networking system that the caller is finished
1702 * using the named feature. The interpretation of {@code feature}
1703 * is completely up to each networking implementation.
1704 *
1705 * <p>This method requires the caller to hold either the
1706 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1707 * or the ability to modify system settings as determined by
1708 * {@link android.provider.Settings.System#canWrite}.</p>
1709 *
1710 * @param networkType specifies which network the request pertains to
1711 * @param feature the name of the feature that is no longer needed
1712 * @return an integer value representing the outcome of the request.
1713 * The interpretation of this value is specific to each networking
1714 * implementation+feature combination, except that the value {@code -1}
1715 * always indicates failure.
1716 *
1717 * @deprecated Deprecated in favor of the cleaner
1718 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1719 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1720 * throw {@code UnsupportedOperationException} if called.
1721 * @removed
1722 */
1723 @Deprecated
1724 public int stopUsingNetworkFeature(int networkType, String feature) {
1725 checkLegacyRoutingApiAccess();
1726 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1727 if (netCap == null) {
1728 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1729 feature);
1730 return -1;
1731 }
1732
1733 if (removeRequestForFeature(netCap)) {
1734 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1735 }
1736 return 1;
1737 }
1738
1739 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1740 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1741 if (networkType == TYPE_MOBILE) {
1742 switch (feature) {
1743 case "enableCBS":
1744 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1745 case "enableDUN":
1746 case "enableDUNAlways":
1747 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1748 case "enableFOTA":
1749 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1750 case "enableHIPRI":
1751 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1752 case "enableIMS":
1753 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1754 case "enableMMS":
1755 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1756 case "enableSUPL":
1757 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1758 default:
1759 return null;
1760 }
1761 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1762 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1763 }
1764 return null;
1765 }
1766
1767 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1768 if (netCap == null) return TYPE_NONE;
1769 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1770 return TYPE_MOBILE_CBS;
1771 }
1772 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1773 return TYPE_MOBILE_IMS;
1774 }
1775 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1776 return TYPE_MOBILE_FOTA;
1777 }
1778 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1779 return TYPE_MOBILE_DUN;
1780 }
1781 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1782 return TYPE_MOBILE_SUPL;
1783 }
1784 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1785 return TYPE_MOBILE_MMS;
1786 }
1787 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1788 return TYPE_MOBILE_HIPRI;
1789 }
1790 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1791 return TYPE_WIFI_P2P;
1792 }
1793 return TYPE_NONE;
1794 }
1795
1796 private static class LegacyRequest {
1797 NetworkCapabilities networkCapabilities;
1798 NetworkRequest networkRequest;
1799 int expireSequenceNumber;
1800 Network currentNetwork;
1801 int delay = -1;
1802
1803 private void clearDnsBinding() {
1804 if (currentNetwork != null) {
1805 currentNetwork = null;
1806 setProcessDefaultNetworkForHostResolution(null);
1807 }
1808 }
1809
1810 NetworkCallback networkCallback = new NetworkCallback() {
1811 @Override
1812 public void onAvailable(Network network) {
1813 currentNetwork = network;
1814 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1815 setProcessDefaultNetworkForHostResolution(network);
1816 }
1817 @Override
1818 public void onLost(Network network) {
1819 if (network.equals(currentNetwork)) clearDnsBinding();
1820 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1821 }
1822 };
1823 }
1824
1825 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1826 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1827 new HashMap<>();
1828
1829 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1830 synchronized (sLegacyRequests) {
1831 LegacyRequest l = sLegacyRequests.get(netCap);
1832 if (l != null) return l.networkRequest;
1833 }
1834 return null;
1835 }
1836
1837 private void renewRequestLocked(LegacyRequest l) {
1838 l.expireSequenceNumber++;
1839 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1840 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1841 }
1842
1843 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1844 int ourSeqNum = -1;
1845 synchronized (sLegacyRequests) {
1846 LegacyRequest l = sLegacyRequests.get(netCap);
1847 if (l == null) return;
1848 ourSeqNum = l.expireSequenceNumber;
1849 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
1850 }
1851 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1852 }
1853
1854 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1855 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1856 int delay = -1;
1857 int type = legacyTypeForNetworkCapabilities(netCap);
1858 try {
1859 delay = mService.getRestoreDefaultNetworkDelay(type);
1860 } catch (RemoteException e) {
1861 throw e.rethrowFromSystemServer();
1862 }
1863 LegacyRequest l = new LegacyRequest();
1864 l.networkCapabilities = netCap;
1865 l.delay = delay;
1866 l.expireSequenceNumber = 0;
1867 l.networkRequest = sendRequestForNetwork(
1868 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
1869 if (l.networkRequest == null) return null;
1870 sLegacyRequests.put(netCap, l);
1871 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1872 return l.networkRequest;
1873 }
1874
1875 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1876 if (delay >= 0) {
1877 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
1878 CallbackHandler handler = getDefaultHandler();
1879 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1880 handler.sendMessageDelayed(msg, delay);
1881 }
1882 }
1883
1884 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1885 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1886 final LegacyRequest l;
1887 synchronized (sLegacyRequests) {
1888 l = sLegacyRequests.remove(netCap);
1889 }
1890 if (l == null) return false;
1891 unregisterNetworkCallback(l.networkCallback);
1892 l.clearDnsBinding();
1893 return true;
1894 }
1895
1896 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1897 static {
1898 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1899 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1900 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1901 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1902 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1903 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1904 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1905 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1906 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1907 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1908 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1909 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1910 }
1911
1912 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1913 static {
1914 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1915 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1916 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1917 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1918 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1919 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1920 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1921 }
1922
1923 /**
1924 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1925 * instance suitable for registering a request or callback. Throws an
1926 * IllegalArgumentException if no mapping from the legacy type to
1927 * NetworkCapabilities is known.
1928 *
1929 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1930 * to find the network instead.
1931 * @hide
1932 */
1933 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1934 final NetworkCapabilities nc = new NetworkCapabilities();
1935
1936 // Map from type to transports.
1937 final int NOT_FOUND = -1;
1938 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00001939 if (transport == NOT_FOUND) {
1940 throw new IllegalArgumentException("unknown legacy type: " + type);
1941 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001942 nc.addTransportType(transport);
1943
1944 // Map from type to capabilities.
1945 nc.addCapability(sLegacyTypeToCapability.get(
1946 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1947 nc.maybeMarkCapabilitiesRestricted();
1948 return nc;
1949 }
1950
1951 /** @hide */
1952 public static class PacketKeepaliveCallback {
1953 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1954 public PacketKeepaliveCallback() {
1955 }
1956 /** The requested keepalive was successfully started. */
1957 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1958 public void onStarted() {}
1959 /** The keepalive was successfully stopped. */
1960 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1961 public void onStopped() {}
1962 /** An error occurred. */
1963 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1964 public void onError(int error) {}
1965 }
1966
1967 /**
1968 * Allows applications to request that the system periodically send specific packets on their
1969 * behalf, using hardware offload to save battery power.
1970 *
1971 * To request that the system send keepalives, call one of the methods that return a
1972 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1973 * passing in a non-null callback. If the callback is successfully started, the callback's
1974 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1975 * specifying one of the {@code ERROR_*} constants in this class.
1976 *
1977 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1978 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1979 * {@link PacketKeepaliveCallback#onError} if an error occurred.
1980 *
1981 * @deprecated Use {@link SocketKeepalive} instead.
1982 *
1983 * @hide
1984 */
1985 public class PacketKeepalive {
1986
1987 private static final String TAG = "PacketKeepalive";
1988
1989 /** @hide */
1990 public static final int SUCCESS = 0;
1991
1992 /** @hide */
1993 public static final int NO_KEEPALIVE = -1;
1994
1995 /** @hide */
1996 public static final int BINDER_DIED = -10;
1997
1998 /** The specified {@code Network} is not connected. */
1999 public static final int ERROR_INVALID_NETWORK = -20;
2000 /** The specified IP addresses are invalid. For example, the specified source IP address is
2001 * not configured on the specified {@code Network}. */
2002 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2003 /** The requested port is invalid. */
2004 public static final int ERROR_INVALID_PORT = -22;
2005 /** The packet length is invalid (e.g., too long). */
2006 public static final int ERROR_INVALID_LENGTH = -23;
2007 /** The packet transmission interval is invalid (e.g., too short). */
2008 public static final int ERROR_INVALID_INTERVAL = -24;
2009
2010 /** The hardware does not support this request. */
2011 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2012 /** The hardware returned an error. */
2013 public static final int ERROR_HARDWARE_ERROR = -31;
2014
2015 /** The NAT-T destination port for IPsec */
2016 public static final int NATT_PORT = 4500;
2017
2018 /** The minimum interval in seconds between keepalive packet transmissions */
2019 public static final int MIN_INTERVAL = 10;
2020
2021 private final Network mNetwork;
2022 private final ISocketKeepaliveCallback mCallback;
2023 private final ExecutorService mExecutor;
2024
2025 private volatile Integer mSlot;
2026
2027 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2028 public void stop() {
2029 try {
2030 mExecutor.execute(() -> {
2031 try {
2032 if (mSlot != null) {
2033 mService.stopKeepalive(mNetwork, mSlot);
2034 }
2035 } catch (RemoteException e) {
2036 Log.e(TAG, "Error stopping packet keepalive: ", e);
2037 throw e.rethrowFromSystemServer();
2038 }
2039 });
2040 } catch (RejectedExecutionException e) {
2041 // The internal executor has already stopped due to previous event.
2042 }
2043 }
2044
2045 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002046 Objects.requireNonNull(network, "network cannot be null");
2047 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002048 mNetwork = network;
2049 mExecutor = Executors.newSingleThreadExecutor();
2050 mCallback = new ISocketKeepaliveCallback.Stub() {
2051 @Override
2052 public void onStarted(int slot) {
2053 final long token = Binder.clearCallingIdentity();
2054 try {
2055 mExecutor.execute(() -> {
2056 mSlot = slot;
2057 callback.onStarted();
2058 });
2059 } finally {
2060 Binder.restoreCallingIdentity(token);
2061 }
2062 }
2063
2064 @Override
2065 public void onStopped() {
2066 final long token = Binder.clearCallingIdentity();
2067 try {
2068 mExecutor.execute(() -> {
2069 mSlot = null;
2070 callback.onStopped();
2071 });
2072 } finally {
2073 Binder.restoreCallingIdentity(token);
2074 }
2075 mExecutor.shutdown();
2076 }
2077
2078 @Override
2079 public void onError(int error) {
2080 final long token = Binder.clearCallingIdentity();
2081 try {
2082 mExecutor.execute(() -> {
2083 mSlot = null;
2084 callback.onError(error);
2085 });
2086 } finally {
2087 Binder.restoreCallingIdentity(token);
2088 }
2089 mExecutor.shutdown();
2090 }
2091
2092 @Override
2093 public void onDataReceived() {
2094 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2095 // this callback when data is received.
2096 }
2097 };
2098 }
2099 }
2100
2101 /**
2102 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2103 *
2104 * @deprecated Use {@link #createSocketKeepalive} instead.
2105 *
2106 * @hide
2107 */
2108 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2109 public PacketKeepalive startNattKeepalive(
2110 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2111 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2112 final PacketKeepalive k = new PacketKeepalive(network, callback);
2113 try {
2114 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2115 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2116 } catch (RemoteException e) {
2117 Log.e(TAG, "Error starting packet keepalive: ", e);
2118 throw e.rethrowFromSystemServer();
2119 }
2120 return k;
2121 }
2122
2123 // Construct an invalid fd.
2124 private ParcelFileDescriptor createInvalidFd() {
2125 final int invalidFd = -1;
2126 return ParcelFileDescriptor.adoptFd(invalidFd);
2127 }
2128
2129 /**
2130 * Request that keepalives be started on a IPsec NAT-T socket.
2131 *
2132 * @param network The {@link Network} the socket is on.
2133 * @param socket The socket that needs to be kept alive.
2134 * @param source The source address of the {@link UdpEncapsulationSocket}.
2135 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2136 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2137 * must run callback sequentially, otherwise the order of callbacks cannot be
2138 * guaranteed.
2139 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2140 * changes. Must be extended by applications that use this API.
2141 *
2142 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2143 * given socket.
2144 **/
2145 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2146 @NonNull UdpEncapsulationSocket socket,
2147 @NonNull InetAddress source,
2148 @NonNull InetAddress destination,
2149 @NonNull @CallbackExecutor Executor executor,
2150 @NonNull Callback callback) {
2151 ParcelFileDescriptor dup;
2152 try {
2153 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2154 // which cannot be obtained by the app process.
2155 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2156 } catch (IOException ignored) {
2157 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2158 // ERROR_INVALID_SOCKET.
2159 dup = createInvalidFd();
2160 }
2161 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2162 destination, executor, callback);
2163 }
2164
2165 /**
2166 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2167 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2168 *
2169 * @param network The {@link Network} the socket is on.
2170 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2171 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2172 * from that port.
2173 * @param source The source address of the {@link UdpEncapsulationSocket}.
2174 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2175 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2176 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2177 * must run callback sequentially, otherwise the order of callbacks cannot be
2178 * guaranteed.
2179 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2180 * changes. Must be extended by applications that use this API.
2181 *
2182 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2183 * given socket.
2184 * @hide
2185 */
2186 @SystemApi
2187 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2188 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2189 @NonNull ParcelFileDescriptor pfd,
2190 @NonNull InetAddress source,
2191 @NonNull InetAddress destination,
2192 @NonNull @CallbackExecutor Executor executor,
2193 @NonNull Callback callback) {
2194 ParcelFileDescriptor dup;
2195 try {
2196 // TODO: Consider remove unnecessary dup.
2197 dup = pfd.dup();
2198 } catch (IOException ignored) {
2199 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2200 // ERROR_INVALID_SOCKET.
2201 dup = createInvalidFd();
2202 }
2203 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002204 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002205 }
2206
2207 /**
2208 * Request that keepalives be started on a TCP socket.
2209 * The socket must be established.
2210 *
2211 * @param network The {@link Network} the socket is on.
2212 * @param socket The socket that needs to be kept alive.
2213 * @param executor The executor on which callback will be invoked. This implementation assumes
2214 * the provided {@link Executor} runs the callbacks in sequence with no
2215 * concurrency. Failing this, no guarantee of correctness can be made. It is
2216 * the responsibility of the caller to ensure the executor provides this
2217 * guarantee. A simple way of creating such an executor is with the standard
2218 * tool {@code Executors.newSingleThreadExecutor}.
2219 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2220 * changes. Must be extended by applications that use this API.
2221 *
2222 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2223 * given socket.
2224 * @hide
2225 */
2226 @SystemApi
2227 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2228 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2229 @NonNull Socket socket,
2230 @NonNull Executor executor,
2231 @NonNull Callback callback) {
2232 ParcelFileDescriptor dup;
2233 try {
2234 dup = ParcelFileDescriptor.fromSocket(socket);
2235 } catch (UncheckedIOException ignored) {
2236 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2237 // ERROR_INVALID_SOCKET.
2238 dup = createInvalidFd();
2239 }
2240 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2241 }
2242
2243 /**
2244 * Ensure that a network route exists to deliver traffic to the specified
2245 * host via the specified network interface. An attempt to add a route that
2246 * already exists is ignored, but treated as successful.
2247 *
2248 * <p>This method requires the caller to hold either the
2249 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2250 * or the ability to modify system settings as determined by
2251 * {@link android.provider.Settings.System#canWrite}.</p>
2252 *
2253 * @param networkType the type of the network over which traffic to the specified
2254 * host is to be routed
2255 * @param hostAddress the IP address of the host to which the route is desired
2256 * @return {@code true} on success, {@code false} on failure
2257 *
2258 * @deprecated Deprecated in favor of the
2259 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2260 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2261 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2262 * throw {@code UnsupportedOperationException} if called.
2263 * @removed
2264 */
2265 @Deprecated
2266 public boolean requestRouteToHost(int networkType, int hostAddress) {
2267 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2268 }
2269
2270 /**
2271 * Ensure that a network route exists to deliver traffic to the specified
2272 * host via the specified network interface. An attempt to add a route that
2273 * already exists is ignored, but treated as successful.
2274 *
2275 * <p>This method requires the caller to hold either the
2276 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2277 * or the ability to modify system settings as determined by
2278 * {@link android.provider.Settings.System#canWrite}.</p>
2279 *
2280 * @param networkType the type of the network over which traffic to the specified
2281 * host is to be routed
2282 * @param hostAddress the IP address of the host to which the route is desired
2283 * @return {@code true} on success, {@code false} on failure
2284 * @hide
2285 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2286 * {@link #bindProcessToNetwork} API.
2287 */
2288 @Deprecated
2289 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002290 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002291 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2292 checkLegacyRoutingApiAccess();
2293 try {
2294 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2295 mContext.getOpPackageName(), getAttributionTag());
2296 } catch (RemoteException e) {
2297 throw e.rethrowFromSystemServer();
2298 }
2299 }
2300
2301 /**
2302 * @return the context's attribution tag
2303 */
2304 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2305 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002306 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002307 }
2308
2309 /**
2310 * Returns the value of the setting for background data usage. If false,
2311 * applications should not use the network if the application is not in the
2312 * foreground. Developers should respect this setting, and check the value
2313 * of this before performing any background data operations.
2314 * <p>
2315 * All applications that have background services that use the network
2316 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2317 * <p>
2318 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2319 * background data depends on several combined factors, and this method will
2320 * always return {@code true}. Instead, when background data is unavailable,
2321 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2322 *
2323 * @return Whether background data usage is allowed.
2324 */
2325 @Deprecated
2326 public boolean getBackgroundDataSetting() {
2327 // assume that background data is allowed; final authority is
2328 // NetworkInfo which may be blocked.
2329 return true;
2330 }
2331
2332 /**
2333 * Sets the value of the setting for background data usage.
2334 *
2335 * @param allowBackgroundData Whether an application should use data while
2336 * it is in the background.
2337 *
2338 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2339 * @see #getBackgroundDataSetting()
2340 * @hide
2341 */
2342 @Deprecated
2343 @UnsupportedAppUsage
2344 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2345 // ignored
2346 }
2347
2348 /**
2349 * @hide
2350 * @deprecated Talk to TelephonyManager directly
2351 */
2352 @Deprecated
2353 @UnsupportedAppUsage
2354 public boolean getMobileDataEnabled() {
2355 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2356 if (tm != null) {
2357 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2358 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2359 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2360 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2361 + " retVal=" + retVal);
2362 return retVal;
2363 }
2364 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2365 return false;
2366 }
2367
2368 /**
2369 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2370 * to find out when the system default network has gone in to a high power state.
2371 */
2372 public interface OnNetworkActiveListener {
2373 /**
2374 * Called on the main thread of the process to report that the current data network
2375 * has become active, and it is now a good time to perform any pending network
2376 * operations. Note that this listener only tells you when the network becomes
2377 * active; if at any other time you want to know whether it is active (and thus okay
2378 * to initiate network traffic), you can retrieve its instantaneous state with
2379 * {@link ConnectivityManager#isDefaultNetworkActive}.
2380 */
2381 void onNetworkActive();
2382 }
2383
Chiachang Wang2de41682021-09-23 10:46:03 +08002384 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002385 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2386 mNetworkActivityListeners = new ArrayMap<>();
2387
2388 /**
2389 * Start listening to reports when the system's default data network is active, meaning it is
2390 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2391 * to determine the current state of the system's default network after registering the
2392 * listener.
2393 * <p>
2394 * If the process default network has been set with
2395 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2396 * reflect the process's default, but the system default.
2397 *
2398 * @param l The listener to be told when the network is active.
2399 */
2400 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002401 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002402 @Override
2403 public void onNetworkActive() throws RemoteException {
2404 l.onNetworkActive();
2405 }
2406 };
2407
Chiachang Wang2de41682021-09-23 10:46:03 +08002408 synchronized (mNetworkActivityListeners) {
2409 try {
2410 mService.registerNetworkActivityListener(rl);
2411 mNetworkActivityListeners.put(l, rl);
2412 } catch (RemoteException e) {
2413 throw e.rethrowFromSystemServer();
2414 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002415 }
2416 }
2417
2418 /**
2419 * Remove network active listener previously registered with
2420 * {@link #addDefaultNetworkActiveListener}.
2421 *
2422 * @param l Previously registered listener.
2423 */
2424 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002425 synchronized (mNetworkActivityListeners) {
2426 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2427 if (rl == null) {
2428 throw new IllegalArgumentException("Listener was not registered.");
2429 }
2430 try {
2431 mService.unregisterNetworkActivityListener(rl);
2432 mNetworkActivityListeners.remove(l);
2433 } catch (RemoteException e) {
2434 throw e.rethrowFromSystemServer();
2435 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002436 }
2437 }
2438
2439 /**
2440 * Return whether the data network is currently active. An active network means that
2441 * it is currently in a high power state for performing data transmission. On some
2442 * types of networks, it may be expensive to move and stay in such a state, so it is
2443 * more power efficient to batch network traffic together when the radio is already in
2444 * this state. This method tells you whether right now is currently a good time to
2445 * initiate network traffic, as the network is already active.
2446 */
2447 public boolean isDefaultNetworkActive() {
2448 try {
lucaslin709eb842021-01-21 02:04:15 +08002449 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002450 } catch (RemoteException e) {
2451 throw e.rethrowFromSystemServer();
2452 }
2453 }
2454
2455 /**
2456 * {@hide}
2457 */
2458 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002459 mContext = Objects.requireNonNull(context, "missing context");
2460 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002461 sInstance = this;
2462 }
2463
2464 /** {@hide} */
2465 @UnsupportedAppUsage
2466 public static ConnectivityManager from(Context context) {
2467 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2468 }
2469
2470 /** @hide */
2471 public NetworkRequest getDefaultRequest() {
2472 try {
2473 // This is not racy as the default request is final in ConnectivityService.
2474 return mService.getDefaultRequest();
2475 } catch (RemoteException e) {
2476 throw e.rethrowFromSystemServer();
2477 }
2478 }
2479
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002480 /**
2481 * Check if the package is a allowed to write settings. This also accounts that such an access
2482 * happened.
2483 *
2484 * @return {@code true} iff the package is allowed to write settings.
2485 */
2486 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2487 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2488 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2489 boolean throwException) {
2490 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002491 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002492 }
2493
2494 /**
2495 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2496 * situations where a Context pointer is unavailable.
2497 * @hide
2498 */
2499 @Deprecated
2500 static ConnectivityManager getInstanceOrNull() {
2501 return sInstance;
2502 }
2503
2504 /**
2505 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2506 * situations where a Context pointer is unavailable.
2507 * @hide
2508 */
2509 @Deprecated
2510 @UnsupportedAppUsage
2511 private static ConnectivityManager getInstance() {
2512 if (getInstanceOrNull() == null) {
2513 throw new IllegalStateException("No ConnectivityManager yet constructed");
2514 }
2515 return getInstanceOrNull();
2516 }
2517
2518 /**
2519 * Get the set of tetherable, available interfaces. This list is limited by
2520 * device configuration and current interface existence.
2521 *
2522 * @return an array of 0 or more Strings of tetherable interface names.
2523 *
2524 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2525 * {@hide}
2526 */
2527 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2528 @UnsupportedAppUsage
2529 @Deprecated
2530 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002531 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002532 }
2533
2534 /**
2535 * Get the set of tethered interfaces.
2536 *
2537 * @return an array of 0 or more String of currently tethered interface names.
2538 *
2539 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2540 * {@hide}
2541 */
2542 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2543 @UnsupportedAppUsage
2544 @Deprecated
2545 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002546 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002547 }
2548
2549 /**
2550 * Get the set of interface names which attempted to tether but
2551 * failed. Re-attempting to tether may cause them to reset to the Tethered
2552 * state. Alternatively, causing the interface to be destroyed and recreated
2553 * may cause them to reset to the available state.
2554 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2555 * information on the cause of the errors.
2556 *
2557 * @return an array of 0 or more String indicating the interface names
2558 * which failed to tether.
2559 *
2560 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2561 * {@hide}
2562 */
2563 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2564 @UnsupportedAppUsage
2565 @Deprecated
2566 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002567 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002568 }
2569
2570 /**
2571 * Get the set of tethered dhcp ranges.
2572 *
2573 * @deprecated This method is not supported.
2574 * TODO: remove this function when all of clients are removed.
2575 * {@hide}
2576 */
2577 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2578 @Deprecated
2579 public String[] getTetheredDhcpRanges() {
2580 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2581 }
2582
2583 /**
2584 * Attempt to tether the named interface. This will setup a dhcp server
2585 * on the interface, forward and NAT IP packets and forward DNS requests
2586 * to the best active upstream network interface. Note that if no upstream
2587 * IP network interface is available, dhcp will still run and traffic will be
2588 * allowed between the tethered devices and this device, though upstream net
2589 * access will of course fail until an upstream network interface becomes
2590 * active.
2591 *
2592 * <p>This method requires the caller to hold either the
2593 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2594 * or the ability to modify system settings as determined by
2595 * {@link android.provider.Settings.System#canWrite}.</p>
2596 *
2597 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2598 * and WifiStateMachine which need direct access. All other clients should use
2599 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2600 * logic.</p>
2601 *
2602 * @param iface the interface name to tether.
2603 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2604 * @deprecated Use {@link TetheringManager#startTethering} instead
2605 *
2606 * {@hide}
2607 */
2608 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2609 @Deprecated
2610 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002611 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002612 }
2613
2614 /**
2615 * Stop tethering the named interface.
2616 *
2617 * <p>This method requires the caller to hold either the
2618 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2619 * or the ability to modify system settings as determined by
2620 * {@link android.provider.Settings.System#canWrite}.</p>
2621 *
2622 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2623 * and WifiStateMachine which need direct access. All other clients should use
2624 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2625 * logic.</p>
2626 *
2627 * @param iface the interface name to untether.
2628 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2629 *
2630 * {@hide}
2631 */
2632 @UnsupportedAppUsage
2633 @Deprecated
2634 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002635 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002636 }
2637
2638 /**
2639 * Check if the device allows for tethering. It may be disabled via
2640 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2641 * due to device configuration.
2642 *
2643 * <p>If this app does not have permission to use this API, it will always
2644 * return false rather than throw an exception.</p>
2645 *
2646 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2647 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2648 *
2649 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2650 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2651 *
2652 * @return a boolean - {@code true} indicating Tethering is supported.
2653 *
2654 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2655 * {@hide}
2656 */
2657 @SystemApi
2658 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2659 android.Manifest.permission.WRITE_SETTINGS})
2660 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002661 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002662 }
2663
2664 /**
2665 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2666 *
2667 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2668 * @hide
2669 */
2670 @SystemApi
2671 @Deprecated
2672 public static abstract class OnStartTetheringCallback {
2673 /**
2674 * Called when tethering has been successfully started.
2675 */
2676 public void onTetheringStarted() {}
2677
2678 /**
2679 * Called when starting tethering failed.
2680 */
2681 public void onTetheringFailed() {}
2682 }
2683
2684 /**
2685 * Convenient overload for
2686 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2687 * handler to run on the current thread's {@link Looper}.
2688 *
2689 * @deprecated Use {@link TetheringManager#startTethering} instead.
2690 * @hide
2691 */
2692 @SystemApi
2693 @Deprecated
2694 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2695 public void startTethering(int type, boolean showProvisioningUi,
2696 final OnStartTetheringCallback callback) {
2697 startTethering(type, showProvisioningUi, callback, null);
2698 }
2699
2700 /**
2701 * Runs tether provisioning for the given type if needed and then starts tethering if
2702 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2703 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2704 * schedules tether provisioning re-checks if appropriate.
2705 *
2706 * @param type The type of tethering to start. Must be one of
2707 * {@link ConnectivityManager.TETHERING_WIFI},
2708 * {@link ConnectivityManager.TETHERING_USB}, or
2709 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2710 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2711 * is one. This should be true the first time this function is called and also any time
2712 * the user can see this UI. It gives users information from their carrier about the
2713 * check failing and how they can sign up for tethering if possible.
2714 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2715 * of the result of trying to tether.
2716 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2717 *
2718 * @deprecated Use {@link TetheringManager#startTethering} instead.
2719 * @hide
2720 */
2721 @SystemApi
2722 @Deprecated
2723 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2724 public void startTethering(int type, boolean showProvisioningUi,
2725 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002726 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002727
2728 final Executor executor = new Executor() {
2729 @Override
2730 public void execute(Runnable command) {
2731 if (handler == null) {
2732 command.run();
2733 } else {
2734 handler.post(command);
2735 }
2736 }
2737 };
2738
2739 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2740 @Override
2741 public void onTetheringStarted() {
2742 callback.onTetheringStarted();
2743 }
2744
2745 @Override
2746 public void onTetheringFailed(final int error) {
2747 callback.onTetheringFailed();
2748 }
2749 };
2750
2751 final TetheringRequest request = new TetheringRequest.Builder(type)
2752 .setShouldShowEntitlementUi(showProvisioningUi).build();
2753
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002754 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002755 }
2756
2757 /**
2758 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2759 * applicable.
2760 *
2761 * @param type The type of tethering to stop. Must be one of
2762 * {@link ConnectivityManager.TETHERING_WIFI},
2763 * {@link ConnectivityManager.TETHERING_USB}, or
2764 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2765 *
2766 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2767 * @hide
2768 */
2769 @SystemApi
2770 @Deprecated
2771 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2772 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002773 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002774 }
2775
2776 /**
2777 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2778 * upstream status.
2779 *
2780 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2781 * @hide
2782 */
2783 @SystemApi
2784 @Deprecated
2785 public abstract static class OnTetheringEventCallback {
2786
2787 /**
2788 * Called when tethering upstream changed. This can be called multiple times and can be
2789 * called any time.
2790 *
2791 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2792 * have any upstream.
2793 */
2794 public void onUpstreamChanged(@Nullable Network network) {}
2795 }
2796
2797 @GuardedBy("mTetheringEventCallbacks")
2798 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2799 mTetheringEventCallbacks = new ArrayMap<>();
2800
2801 /**
2802 * Start listening to tethering change events. Any new added callback will receive the last
2803 * tethering status right away. If callback is registered when tethering has no upstream or
2804 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2805 * with a null argument. The same callback object cannot be registered twice.
2806 *
2807 * @param executor the executor on which callback will be invoked.
2808 * @param callback the callback to be called when tethering has change events.
2809 *
2810 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2811 * @hide
2812 */
2813 @SystemApi
2814 @Deprecated
2815 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2816 public void registerTetheringEventCallback(
2817 @NonNull @CallbackExecutor Executor executor,
2818 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002819 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002820
2821 final TetheringEventCallback tetherCallback =
2822 new TetheringEventCallback() {
2823 @Override
2824 public void onUpstreamChanged(@Nullable Network network) {
2825 callback.onUpstreamChanged(network);
2826 }
2827 };
2828
2829 synchronized (mTetheringEventCallbacks) {
2830 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002831 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002832 }
2833 }
2834
2835 /**
2836 * Remove tethering event callback previously registered with
2837 * {@link #registerTetheringEventCallback}.
2838 *
2839 * @param callback previously registered callback.
2840 *
2841 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
2842 * @hide
2843 */
2844 @SystemApi
2845 @Deprecated
2846 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2847 public void unregisterTetheringEventCallback(
2848 @NonNull final OnTetheringEventCallback callback) {
2849 Objects.requireNonNull(callback, "The callback must be non-null");
2850 synchronized (mTetheringEventCallbacks) {
2851 final TetheringEventCallback tetherCallback =
2852 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002853 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002854 }
2855 }
2856
2857
2858 /**
2859 * Get the list of regular expressions that define any tetherable
2860 * USB network interfaces. If USB tethering is not supported by the
2861 * device, this list should be empty.
2862 *
2863 * @return an array of 0 or more regular expression Strings defining
2864 * what interfaces are considered tetherable usb interfaces.
2865 *
2866 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2867 * {@hide}
2868 */
2869 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2870 @UnsupportedAppUsage
2871 @Deprecated
2872 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002873 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002874 }
2875
2876 /**
2877 * Get the list of regular expressions that define any tetherable
2878 * Wifi network interfaces. If Wifi tethering is not supported by the
2879 * device, this list should be empty.
2880 *
2881 * @return an array of 0 or more regular expression Strings defining
2882 * what interfaces are considered tetherable wifi interfaces.
2883 *
2884 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2885 * {@hide}
2886 */
2887 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2888 @UnsupportedAppUsage
2889 @Deprecated
2890 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002891 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002892 }
2893
2894 /**
2895 * Get the list of regular expressions that define any tetherable
2896 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2897 * device, this list should be empty.
2898 *
2899 * @return an array of 0 or more regular expression Strings defining
2900 * what interfaces are considered tetherable bluetooth interfaces.
2901 *
2902 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2903 *TetheringManager.TetheringInterfaceRegexps)} instead.
2904 * {@hide}
2905 */
2906 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2907 @UnsupportedAppUsage
2908 @Deprecated
2909 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002910 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002911 }
2912
2913 /**
2914 * Attempt to both alter the mode of USB and Tethering of USB. A
2915 * utility method to deal with some of the complexity of USB - will
2916 * attempt to switch to Rndis and subsequently tether the resulting
2917 * interface on {@code true} or turn off tethering and switch off
2918 * Rndis on {@code false}.
2919 *
2920 * <p>This method requires the caller to hold either the
2921 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2922 * or the ability to modify system settings as determined by
2923 * {@link android.provider.Settings.System#canWrite}.</p>
2924 *
2925 * @param enable a boolean - {@code true} to enable tethering
2926 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2927 * @deprecated Use {@link TetheringManager#startTethering} instead
2928 *
2929 * {@hide}
2930 */
2931 @UnsupportedAppUsage
2932 @Deprecated
2933 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002934 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002935 }
2936
2937 /**
2938 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2939 * {@hide}
2940 */
2941 @SystemApi
2942 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002943 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002944 /**
2945 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2946 * {@hide}
2947 */
2948 @Deprecated
2949 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2950 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2951 /**
2952 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2953 * {@hide}
2954 */
2955 @Deprecated
2956 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2957 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2958 /**
2959 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2960 * {@hide}
2961 */
2962 @Deprecated
2963 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2964 /**
2965 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2966 * {@hide}
2967 */
2968 @Deprecated
2969 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2970 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2971 /**
2972 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
2973 * {@hide}
2974 */
2975 @Deprecated
2976 public static final int TETHER_ERROR_MASTER_ERROR =
2977 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
2978 /**
2979 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2980 * {@hide}
2981 */
2982 @Deprecated
2983 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2984 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2985 /**
2986 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2987 * {@hide}
2988 */
2989 @Deprecated
2990 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2991 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2992 /**
2993 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
2994 * {@hide}
2995 */
2996 @Deprecated
2997 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
2998 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
2999 /**
3000 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3001 * {@hide}
3002 */
3003 @Deprecated
3004 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3005 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3006 /**
3007 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3008 * {@hide}
3009 */
3010 @Deprecated
3011 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3012 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3013 /**
3014 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3015 * {@hide}
3016 */
3017 @SystemApi
3018 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003019 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003020 /**
3021 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3022 * {@hide}
3023 */
3024 @Deprecated
3025 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3026 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3027 /**
3028 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3029 * {@hide}
3030 */
3031 @SystemApi
3032 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003033 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003034
3035 /**
3036 * Get a more detailed error code after a Tethering or Untethering
3037 * request asynchronously failed.
3038 *
3039 * @param iface The name of the interface of interest
3040 * @return error The error code of the last error tethering or untethering the named
3041 * interface
3042 *
3043 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3044 * {@hide}
3045 */
3046 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3047 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3048 @Deprecated
3049 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003050 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003051 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3052 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3053 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3054 // instead.
3055 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3056 }
3057 return error;
3058 }
3059
3060 /** @hide */
3061 @Retention(RetentionPolicy.SOURCE)
3062 @IntDef(value = {
3063 TETHER_ERROR_NO_ERROR,
3064 TETHER_ERROR_PROVISION_FAILED,
3065 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3066 })
3067 public @interface EntitlementResultCode {
3068 }
3069
3070 /**
3071 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3072 * entitlement succeeded.
3073 *
3074 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3075 * @hide
3076 */
3077 @SystemApi
3078 @Deprecated
3079 public interface OnTetheringEntitlementResultListener {
3080 /**
3081 * Called to notify entitlement result.
3082 *
3083 * @param resultCode an int value of entitlement result. It may be one of
3084 * {@link #TETHER_ERROR_NO_ERROR},
3085 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3086 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3087 */
3088 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3089 }
3090
3091 /**
3092 * Get the last value of the entitlement check on this downstream. If the cached value is
3093 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3094 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3095 * guaranteed that the UI-based entitlement check will complete in any specific time period
3096 * and may in fact never complete. Any successful entitlement check the platform performs for
3097 * any reason will update the cached value.
3098 *
3099 * @param type the downstream type of tethering. Must be one of
3100 * {@link #TETHERING_WIFI},
3101 * {@link #TETHERING_USB}, or
3102 * {@link #TETHERING_BLUETOOTH}.
3103 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3104 * @param executor the executor on which callback will be invoked.
3105 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3106 * notify the caller of the result of entitlement check. The listener may be called zero
3107 * or one time.
3108 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3109 * {@hide}
3110 */
3111 @SystemApi
3112 @Deprecated
3113 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3114 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3115 @NonNull @CallbackExecutor Executor executor,
3116 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003117 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003118 ResultReceiver wrappedListener = new ResultReceiver(null) {
3119 @Override
3120 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003121 final long token = Binder.clearCallingIdentity();
3122 try {
3123 executor.execute(() -> {
3124 listener.onTetheringEntitlementResult(resultCode);
3125 });
3126 } finally {
3127 Binder.restoreCallingIdentity(token);
3128 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003129 }
3130 };
3131
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003132 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003133 showEntitlementUi);
3134 }
3135
3136 /**
3137 * Report network connectivity status. This is currently used only
3138 * to alter status bar UI.
3139 * <p>This method requires the caller to hold the permission
3140 * {@link android.Manifest.permission#STATUS_BAR}.
3141 *
3142 * @param networkType The type of network you want to report on
3143 * @param percentage The quality of the connection 0 is bad, 100 is good
3144 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3145 * {@hide}
3146 */
3147 public void reportInetCondition(int networkType, int percentage) {
3148 printStackTrace();
3149 try {
3150 mService.reportInetCondition(networkType, percentage);
3151 } catch (RemoteException e) {
3152 throw e.rethrowFromSystemServer();
3153 }
3154 }
3155
3156 /**
3157 * Report a problem network to the framework. This provides a hint to the system
3158 * that there might be connectivity problems on this network and may cause
3159 * the framework to re-evaluate network connectivity and/or switch to another
3160 * network.
3161 *
3162 * @param network The {@link Network} the application was attempting to use
3163 * or {@code null} to indicate the current default network.
3164 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3165 * working and non-working connectivity.
3166 */
3167 @Deprecated
3168 public void reportBadNetwork(@Nullable Network network) {
3169 printStackTrace();
3170 try {
3171 // One of these will be ignored because it matches system's current state.
3172 // The other will trigger the necessary reevaluation.
3173 mService.reportNetworkConnectivity(network, true);
3174 mService.reportNetworkConnectivity(network, false);
3175 } catch (RemoteException e) {
3176 throw e.rethrowFromSystemServer();
3177 }
3178 }
3179
3180 /**
3181 * Report to the framework whether a network has working connectivity.
3182 * This provides a hint to the system that a particular network is providing
3183 * working connectivity or not. In response the framework may re-evaluate
3184 * the network's connectivity and might take further action thereafter.
3185 *
3186 * @param network The {@link Network} the application was attempting to use
3187 * or {@code null} to indicate the current default network.
3188 * @param hasConnectivity {@code true} if the application was able to successfully access the
3189 * Internet using {@code network} or {@code false} if not.
3190 */
3191 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3192 printStackTrace();
3193 try {
3194 mService.reportNetworkConnectivity(network, hasConnectivity);
3195 } catch (RemoteException e) {
3196 throw e.rethrowFromSystemServer();
3197 }
3198 }
3199
3200 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003201 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003202 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003203 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3204 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3205 * accessing any network, regardless of what the settings for that network are.
3206 *
3207 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3208 * proxy is likely to break networking on multiple networks. This method is only meant
3209 * for device policy clients looking to do general internal filtering or similar use cases.
3210 *
3211 * {@see #getGlobalProxy}
3212 * {@see LinkProperties#getHttpProxy}
3213 *
3214 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3215 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003216 * @hide
3217 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003218 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003219 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003220 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003221 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003222 try {
3223 mService.setGlobalProxy(p);
3224 } catch (RemoteException e) {
3225 throw e.rethrowFromSystemServer();
3226 }
3227 }
3228
3229 /**
3230 * Retrieve any network-independent global HTTP proxy.
3231 *
3232 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3233 * if no global HTTP proxy is set.
3234 * @hide
3235 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003236 @SystemApi(client = MODULE_LIBRARIES)
3237 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003238 public ProxyInfo getGlobalProxy() {
3239 try {
3240 return mService.getGlobalProxy();
3241 } catch (RemoteException e) {
3242 throw e.rethrowFromSystemServer();
3243 }
3244 }
3245
3246 /**
3247 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3248 * network-specific HTTP proxy. If {@code network} is null, the
3249 * network-specific proxy returned is the proxy of the default active
3250 * network.
3251 *
3252 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3253 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3254 * or when {@code network} is {@code null},
3255 * the {@code ProxyInfo} for the default active network. Returns
3256 * {@code null} when no proxy applies or the caller doesn't have
3257 * permission to use {@code network}.
3258 * @hide
3259 */
3260 public ProxyInfo getProxyForNetwork(Network network) {
3261 try {
3262 return mService.getProxyForNetwork(network);
3263 } catch (RemoteException e) {
3264 throw e.rethrowFromSystemServer();
3265 }
3266 }
3267
3268 /**
3269 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3270 * otherwise if this process is bound to a {@link Network} using
3271 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3272 * the default network's proxy is returned.
3273 *
3274 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3275 * HTTP proxy is active.
3276 */
3277 @Nullable
3278 public ProxyInfo getDefaultProxy() {
3279 return getProxyForNetwork(getBoundNetworkForProcess());
3280 }
3281
3282 /**
3283 * Returns true if the hardware supports the given network type
3284 * else it returns false. This doesn't indicate we have coverage
3285 * or are authorized onto a network, just whether or not the
3286 * hardware supports it. For example a GSM phone without a SIM
3287 * should still return {@code true} for mobile data, but a wifi only
3288 * tablet would return {@code false}.
3289 *
3290 * @param networkType The network type we'd like to check
3291 * @return {@code true} if supported, else {@code false}
3292 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3293 * @hide
3294 */
3295 @Deprecated
3296 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3297 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3298 public boolean isNetworkSupported(int networkType) {
3299 try {
3300 return mService.isNetworkSupported(networkType);
3301 } catch (RemoteException e) {
3302 throw e.rethrowFromSystemServer();
3303 }
3304 }
3305
3306 /**
3307 * Returns if the currently active data network is metered. A network is
3308 * classified as metered when the user is sensitive to heavy data usage on
3309 * that connection due to monetary costs, data limitations or
3310 * battery/performance issues. You should check this before doing large
3311 * data transfers, and warn the user or delay the operation until another
3312 * network is available.
3313 *
3314 * @return {@code true} if large transfers should be avoided, otherwise
3315 * {@code false}.
3316 */
3317 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3318 public boolean isActiveNetworkMetered() {
3319 try {
3320 return mService.isActiveNetworkMetered();
3321 } catch (RemoteException e) {
3322 throw e.rethrowFromSystemServer();
3323 }
3324 }
3325
3326 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003327 * Set sign in error notification to visible or invisible
3328 *
3329 * @hide
3330 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3331 */
3332 @Deprecated
3333 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3334 String action) {
3335 try {
3336 mService.setProvisioningNotificationVisible(visible, networkType, action);
3337 } catch (RemoteException e) {
3338 throw e.rethrowFromSystemServer();
3339 }
3340 }
3341
3342 /**
3343 * Set the value for enabling/disabling airplane mode
3344 *
3345 * @param enable whether to enable airplane mode or not
3346 *
3347 * @hide
3348 */
3349 @RequiresPermission(anyOf = {
3350 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3351 android.Manifest.permission.NETWORK_SETTINGS,
3352 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3353 android.Manifest.permission.NETWORK_STACK})
3354 @SystemApi
3355 public void setAirplaneMode(boolean enable) {
3356 try {
3357 mService.setAirplaneMode(enable);
3358 } catch (RemoteException e) {
3359 throw e.rethrowFromSystemServer();
3360 }
3361 }
3362
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003363 /**
3364 * Registers the specified {@link NetworkProvider}.
3365 * Each listener must only be registered once. The listener can be unregistered with
3366 * {@link #unregisterNetworkProvider}.
3367 *
3368 * @param provider the provider to register
3369 * @return the ID of the provider. This ID must be used by the provider when registering
3370 * {@link android.net.NetworkAgent}s.
3371 * @hide
3372 */
3373 @SystemApi
3374 @RequiresPermission(anyOf = {
3375 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3376 android.Manifest.permission.NETWORK_FACTORY})
3377 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3378 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3379 throw new IllegalStateException("NetworkProviders can only be registered once");
3380 }
3381
3382 try {
3383 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3384 provider.getName());
3385 provider.setProviderId(providerId);
3386 } catch (RemoteException e) {
3387 throw e.rethrowFromSystemServer();
3388 }
3389 return provider.getProviderId();
3390 }
3391
3392 /**
3393 * Unregisters the specified NetworkProvider.
3394 *
3395 * @param provider the provider to unregister
3396 * @hide
3397 */
3398 @SystemApi
3399 @RequiresPermission(anyOf = {
3400 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3401 android.Manifest.permission.NETWORK_FACTORY})
3402 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3403 try {
3404 mService.unregisterNetworkProvider(provider.getMessenger());
3405 } catch (RemoteException e) {
3406 throw e.rethrowFromSystemServer();
3407 }
3408 provider.setProviderId(NetworkProvider.ID_NONE);
3409 }
3410
Chalard Jeand1b498b2021-01-05 08:40:09 +09003411 /**
3412 * Register or update a network offer with ConnectivityService.
3413 *
3414 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003415 * them to networking requests made by apps or the system. A callback identifies an offer
3416 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3417 * score and the capabilities of the network it might be able to bring up ; these act as
3418 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003419 * provider.
3420 *
3421 * The provider is under no obligation to be able to bring up the network it offers at any
3422 * given time. Instead, this mechanism is meant to limit requests received by providers
3423 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3424 * the quality of the network satisfying a given request to their own offer.
3425 *
3426 * An offer can be updated by calling this again with the same callback object. This is
3427 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3428 * provider with the changes caused by the changes in the offer.
3429 *
3430 * @param provider The provider making this offer.
3431 * @param score The prospective score of the network.
3432 * @param caps The prospective capabilities of the network.
3433 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003434 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003435 */
3436 @RequiresPermission(anyOf = {
3437 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3438 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003439 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003440 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3441 @NonNull final INetworkOfferCallback callback) {
3442 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003443 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003444 Objects.requireNonNull(score, "null score"),
3445 Objects.requireNonNull(caps, "null caps"),
3446 Objects.requireNonNull(callback, "null callback"));
3447 } catch (RemoteException e) {
3448 throw e.rethrowFromSystemServer();
3449 }
3450 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003451
Chalard Jeand1b498b2021-01-05 08:40:09 +09003452 /**
3453 * Withdraw a network offer made with {@link #offerNetwork}.
3454 *
3455 * @param callback The callback passed at registration time. This must be the same object
3456 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003457 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003458 */
3459 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3460 try {
3461 mService.unofferNetwork(Objects.requireNonNull(callback));
3462 } catch (RemoteException e) {
3463 throw e.rethrowFromSystemServer();
3464 }
3465 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003466 /** @hide exposed via the NetworkProvider class. */
3467 @RequiresPermission(anyOf = {
3468 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3469 android.Manifest.permission.NETWORK_FACTORY})
3470 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3471 try {
3472 mService.declareNetworkRequestUnfulfillable(request);
3473 } catch (RemoteException e) {
3474 throw e.rethrowFromSystemServer();
3475 }
3476 }
3477
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003478 /**
3479 * @hide
3480 * Register a NetworkAgent with ConnectivityService.
3481 * @return Network corresponding to NetworkAgent.
3482 */
3483 @RequiresPermission(anyOf = {
3484 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3485 android.Manifest.permission.NETWORK_FACTORY})
3486 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003487 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3488 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003489 try {
3490 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3491 } catch (RemoteException e) {
3492 throw e.rethrowFromSystemServer();
3493 }
3494 }
3495
3496 /**
3497 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3498 * changes. Should be extended by applications wanting notifications.
3499 *
3500 * A {@code NetworkCallback} is registered by calling
3501 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3502 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3503 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3504 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3505 * A {@code NetworkCallback} should be registered at most once at any time.
3506 * A {@code NetworkCallback} that has been unregistered can be registered again.
3507 */
3508 public static class NetworkCallback {
3509 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003510 * No flags associated with this callback.
3511 * @hide
3512 */
3513 public static final int FLAG_NONE = 0;
3514 /**
3515 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3516 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3517 * <p>
3518 * These include:
3519 * <li> Some transport info instances (retrieved via
3520 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3521 * contain location sensitive information.
3522 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003523 * sensitive for wifi suggestor apps (i.e using
3524 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003525 * </p>
3526 * <p>
3527 * Note:
3528 * <li> Retrieving this location sensitive information (subject to app's location
3529 * permissions) will be noted by system. </li>
3530 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3531 * not include location sensitive info.
3532 * </p>
3533 */
Roshan Pius189d0092021-03-11 21:16:44 -08003534 // Note: Some existing fields which are location sensitive may still be included without
3535 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003536 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3537
3538 /** @hide */
3539 @Retention(RetentionPolicy.SOURCE)
3540 @IntDef(flag = true, prefix = "FLAG_", value = {
3541 FLAG_NONE,
3542 FLAG_INCLUDE_LOCATION_INFO
3543 })
3544 public @interface Flag { }
3545
3546 /**
3547 * All the valid flags for error checking.
3548 */
3549 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3550
3551 public NetworkCallback() {
3552 this(FLAG_NONE);
3553 }
3554
3555 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003556 if ((flags & VALID_FLAGS) != flags) {
3557 throw new IllegalArgumentException("Invalid flags");
3558 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003559 mFlags = flags;
3560 }
3561
3562 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003563 * Called when the framework connects to a new network to evaluate whether it satisfies this
3564 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3565 * callback. There is no guarantee that this new network will satisfy any requests, or that
3566 * the network will stay connected for longer than the time necessary to evaluate it.
3567 * <p>
3568 * Most applications <b>should not</b> act on this callback, and should instead use
3569 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3570 * the framework in properly evaluating the network &mdash; for example, an application that
3571 * can automatically log in to a captive portal without user intervention.
3572 *
3573 * @param network The {@link Network} of the network that is being evaluated.
3574 *
3575 * @hide
3576 */
3577 public void onPreCheck(@NonNull Network network) {}
3578
3579 /**
3580 * Called when the framework connects and has declared a new network ready for use.
3581 * This callback may be called more than once if the {@link Network} that is
3582 * satisfying the request changes.
3583 *
3584 * @param network The {@link Network} of the satisfying network.
3585 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3586 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3587 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3588 * @hide
3589 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003590 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003591 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003592 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003593 // Internally only this method is called when a new network is available, and
3594 // it calls the callback in the same way and order that older versions used
3595 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003596 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3597 onBlockedStatusChanged(network, blocked);
3598 }
3599
3600 /**
3601 * Legacy variant of onAvailable that takes a boolean blocked reason.
3602 *
3603 * This method has never been public API, but it's not final, so there may be apps that
3604 * implemented it and rely on it being called. Do our best not to break them.
3605 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3606 * this method is called. There does not seem to be a way to avoid this.
3607 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3608 *
3609 * @hide
3610 */
3611 public void onAvailable(@NonNull Network network,
3612 @NonNull NetworkCapabilities networkCapabilities,
3613 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003614 onAvailable(network);
3615 if (!networkCapabilities.hasCapability(
3616 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3617 onNetworkSuspended(network);
3618 }
3619 onCapabilitiesChanged(network, networkCapabilities);
3620 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003621 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003622 }
3623
3624 /**
3625 * Called when the framework connects and has declared a new network ready for use.
3626 *
3627 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3628 * be available at the same time, and onAvailable will be called for each of these as they
3629 * appear.
3630 *
3631 * <p>For callbacks registered with {@link #requestNetwork} and
3632 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3633 * is the new best network for this request and is now tracked by this callback ; this
3634 * callback will no longer receive method calls about other networks that may have been
3635 * passed to this method previously. The previously-best network may have disconnected, or
3636 * it may still be around and the newly-best network may simply be better.
3637 *
3638 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3639 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3640 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3641 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3642 *
3643 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3644 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3645 * this callback as this is prone to race conditions (there is no guarantee the objects
3646 * returned by these methods will be current). Instead, wait for a call to
3647 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3648 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3649 * to be well-ordered with respect to other callbacks.
3650 *
3651 * @param network The {@link Network} of the satisfying network.
3652 */
3653 public void onAvailable(@NonNull Network network) {}
3654
3655 /**
3656 * Called when the network is about to be lost, typically because there are no outstanding
3657 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3658 * with the new replacement network for graceful handover. This method is not guaranteed
3659 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3660 * network is suddenly disconnected.
3661 *
3662 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3663 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3664 * this callback as this is prone to race conditions ; calling these methods while in a
3665 * callback may return an outdated or even a null object.
3666 *
3667 * @param network The {@link Network} that is about to be lost.
3668 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3669 * connected for graceful handover; note that the network may still
3670 * suffer a hard loss at any time.
3671 */
3672 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3673
3674 /**
3675 * Called when a network disconnects or otherwise no longer satisfies this request or
3676 * callback.
3677 *
3678 * <p>If the callback was registered with requestNetwork() or
3679 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3680 * returned by onAvailable() when that network is lost and no other network satisfies
3681 * the criteria of the request.
3682 *
3683 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3684 * each network which no longer satisfies the criteria of the callback.
3685 *
3686 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3687 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3688 * this callback as this is prone to race conditions ; calling these methods while in a
3689 * callback may return an outdated or even a null object.
3690 *
3691 * @param network The {@link Network} lost.
3692 */
3693 public void onLost(@NonNull Network network) {}
3694
3695 /**
3696 * Called if no network is found within the timeout time specified in
3697 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3698 * requested network request cannot be fulfilled (whether or not a timeout was
3699 * specified). When this callback is invoked the associated
3700 * {@link NetworkRequest} will have already been removed and released, as if
3701 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3702 */
3703 public void onUnavailable() {}
3704
3705 /**
3706 * Called when the network corresponding to this request changes capabilities but still
3707 * satisfies the requested criteria.
3708 *
3709 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3710 * to be called immediately after {@link #onAvailable}.
3711 *
3712 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3713 * ConnectivityManager methods in this callback as this is prone to race conditions :
3714 * calling these methods while in a callback may return an outdated or even a null object.
3715 *
3716 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003717 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003718 * network.
3719 */
3720 public void onCapabilitiesChanged(@NonNull Network network,
3721 @NonNull NetworkCapabilities networkCapabilities) {}
3722
3723 /**
3724 * Called when the network corresponding to this request changes {@link LinkProperties}.
3725 *
3726 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3727 * to be called immediately after {@link #onAvailable}.
3728 *
3729 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3730 * ConnectivityManager methods in this callback as this is prone to race conditions :
3731 * calling these methods while in a callback may return an outdated or even a null object.
3732 *
3733 * @param network The {@link Network} whose link properties have changed.
3734 * @param linkProperties The new {@link LinkProperties} for this network.
3735 */
3736 public void onLinkPropertiesChanged(@NonNull Network network,
3737 @NonNull LinkProperties linkProperties) {}
3738
3739 /**
3740 * Called when the network the framework connected to for this request suspends data
3741 * transmission temporarily.
3742 *
3743 * <p>This generally means that while the TCP connections are still live temporarily
3744 * network data fails to transfer. To give a specific example, this is used on cellular
3745 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3746 * means read operations on sockets on this network will block once the buffers are
3747 * drained, and write operations will block once the buffers are full.
3748 *
3749 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3750 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3751 * this callback as this is prone to race conditions (there is no guarantee the objects
3752 * returned by these methods will be current).
3753 *
3754 * @hide
3755 */
3756 public void onNetworkSuspended(@NonNull Network network) {}
3757
3758 /**
3759 * Called when the network the framework connected to for this request
3760 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3761 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
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 : calling these methods while in a
3766 * callback may return an outdated or even a null object.
3767 *
3768 * @hide
3769 */
3770 public void onNetworkResumed(@NonNull Network network) {}
3771
3772 /**
3773 * Called when access to the specified network is blocked or unblocked.
3774 *
3775 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3776 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3777 * this callback as this is prone to race conditions : calling these methods while in a
3778 * callback may return an outdated or even a null object.
3779 *
3780 * @param network The {@link Network} whose blocked status has changed.
3781 * @param blocked The blocked status of this {@link Network}.
3782 */
3783 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3784
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003785 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09003786 * Called when access to the specified network is blocked or unblocked, or the reason for
3787 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003788 *
3789 * If a NetworkCallback object implements this method,
3790 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3791 *
3792 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3793 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3794 * this callback as this is prone to race conditions : calling these methods while in a
3795 * callback may return an outdated or even a null object.
3796 *
3797 * @param network The {@link Network} whose blocked status has changed.
3798 * @param blocked The blocked status of this {@link Network}.
3799 * @hide
3800 */
3801 @SystemApi(client = MODULE_LIBRARIES)
3802 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3803 onBlockedStatusChanged(network, blocked != 0);
3804 }
3805
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003806 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08003807 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003808 }
3809
3810 /**
3811 * Constant error codes used by ConnectivityService to communicate about failures and errors
3812 * across a Binder boundary.
3813 * @hide
3814 */
3815 public interface Errors {
3816 int TOO_MANY_REQUESTS = 1;
3817 }
3818
3819 /** @hide */
3820 public static class TooManyRequestsException extends RuntimeException {}
3821
3822 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3823 switch (e.errorCode) {
3824 case Errors.TOO_MANY_REQUESTS:
3825 return new TooManyRequestsException();
3826 default:
3827 Log.w(TAG, "Unknown service error code " + e.errorCode);
3828 return new RuntimeException(e);
3829 }
3830 }
3831
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003832 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003833 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003834 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003835 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003836 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003837 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003838 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003839 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003840 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003841 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003842 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003843 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003844 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003845 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003846 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003847 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003848 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003849 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003850 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003851 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003852 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003853 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003854
3855 /** @hide */
3856 public static String getCallbackName(int whichCallback) {
3857 switch (whichCallback) {
3858 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3859 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3860 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3861 case CALLBACK_LOST: return "CALLBACK_LOST";
3862 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3863 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3864 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
3865 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3866 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3867 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
3868 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
3869 default:
3870 return Integer.toString(whichCallback);
3871 }
3872 }
3873
3874 private class CallbackHandler extends Handler {
3875 private static final String TAG = "ConnectivityManager.CallbackHandler";
3876 private static final boolean DBG = false;
3877
3878 CallbackHandler(Looper looper) {
3879 super(looper);
3880 }
3881
3882 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003883 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003884 }
3885
3886 @Override
3887 public void handleMessage(Message message) {
3888 if (message.what == EXPIRE_LEGACY_REQUEST) {
3889 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3890 return;
3891 }
3892
3893 final NetworkRequest request = getObject(message, NetworkRequest.class);
3894 final Network network = getObject(message, Network.class);
3895 final NetworkCallback callback;
3896 synchronized (sCallbacks) {
3897 callback = sCallbacks.get(request);
3898 if (callback == null) {
3899 Log.w(TAG,
3900 "callback not found for " + getCallbackName(message.what) + " message");
3901 return;
3902 }
3903 if (message.what == CALLBACK_UNAVAIL) {
3904 sCallbacks.remove(request);
3905 callback.networkRequest = ALREADY_UNREGISTERED;
3906 }
3907 }
3908 if (DBG) {
3909 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
3910 }
3911
3912 switch (message.what) {
3913 case CALLBACK_PRECHECK: {
3914 callback.onPreCheck(network);
3915 break;
3916 }
3917 case CALLBACK_AVAILABLE: {
3918 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3919 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003920 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003921 break;
3922 }
3923 case CALLBACK_LOSING: {
3924 callback.onLosing(network, message.arg1);
3925 break;
3926 }
3927 case CALLBACK_LOST: {
3928 callback.onLost(network);
3929 break;
3930 }
3931 case CALLBACK_UNAVAIL: {
3932 callback.onUnavailable();
3933 break;
3934 }
3935 case CALLBACK_CAP_CHANGED: {
3936 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3937 callback.onCapabilitiesChanged(network, cap);
3938 break;
3939 }
3940 case CALLBACK_IP_CHANGED: {
3941 LinkProperties lp = getObject(message, LinkProperties.class);
3942 callback.onLinkPropertiesChanged(network, lp);
3943 break;
3944 }
3945 case CALLBACK_SUSPENDED: {
3946 callback.onNetworkSuspended(network);
3947 break;
3948 }
3949 case CALLBACK_RESUMED: {
3950 callback.onNetworkResumed(network);
3951 break;
3952 }
3953 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003954 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003955 }
3956 }
3957 }
3958
3959 private <T> T getObject(Message msg, Class<T> c) {
3960 return (T) msg.getData().getParcelable(c.getSimpleName());
3961 }
3962 }
3963
3964 private CallbackHandler getDefaultHandler() {
3965 synchronized (sCallbacks) {
3966 if (sCallbackHandler == null) {
3967 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
3968 }
3969 return sCallbackHandler;
3970 }
3971 }
3972
3973 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3974 private static CallbackHandler sCallbackHandler;
3975
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003976 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3977 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3978 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003979 printStackTrace();
3980 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003981 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3982 throw new IllegalArgumentException("null NetworkCapabilities");
3983 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003984 final NetworkRequest request;
3985 final String callingPackageName = mContext.getOpPackageName();
3986 try {
3987 synchronized(sCallbacks) {
3988 if (callback.networkRequest != null
3989 && callback.networkRequest != ALREADY_UNREGISTERED) {
3990 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3991 // and requests (http://b/20701525).
3992 Log.e(TAG, "NetworkCallback was already registered");
3993 }
3994 Messenger messenger = new Messenger(handler);
3995 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08003996 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003997 if (reqType == LISTEN) {
3998 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08003999 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004000 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004001 } else {
4002 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004003 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4004 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004005 }
4006 if (request != null) {
4007 sCallbacks.put(request, callback);
4008 }
4009 callback.networkRequest = request;
4010 }
4011 } catch (RemoteException e) {
4012 throw e.rethrowFromSystemServer();
4013 } catch (ServiceSpecificException e) {
4014 throw convertServiceException(e);
4015 }
4016 return request;
4017 }
4018
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004019 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4020 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4021 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4022 legacyType, handler);
4023 }
4024
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004025 /**
4026 * Helper function to request a network with a particular legacy type.
4027 *
4028 * This API is only for use in internal system code that requests networks with legacy type and
4029 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4030 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4031 *
4032 * @param request {@link NetworkRequest} describing this request.
4033 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4034 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4035 * be a positive value (i.e. >0).
4036 * @param legacyType to specify the network type(#TYPE_*).
4037 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4038 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4039 * the callback must not be shared - it uniquely specifies this request.
4040 *
4041 * @hide
4042 */
4043 @SystemApi
4044 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4045 public void requestNetwork(@NonNull NetworkRequest request,
4046 int timeoutMs, int legacyType, @NonNull Handler handler,
4047 @NonNull NetworkCallback networkCallback) {
4048 if (legacyType == TYPE_NONE) {
4049 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4050 }
4051 CallbackHandler cbHandler = new CallbackHandler(handler);
4052 NetworkCapabilities nc = request.networkCapabilities;
4053 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4054 }
4055
4056 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004057 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004058 *
4059 * <p>This method will attempt to find the best network that matches the passed
4060 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4061 * criteria. The platform will evaluate which network is the best at its own discretion.
4062 * Throughput, latency, cost per byte, policy, user preference and other considerations
4063 * may be factored in the decision of what is considered the best network.
4064 *
4065 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4066 * matching this request, while always attempting to match the request to a better network if
4067 * possible. If a better match is found, the platform will switch this request to the now-best
4068 * network and inform the app of the newly best network by invoking
4069 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4070 * will not try to maintain any other network than the best one currently matching the request:
4071 * a network not matching any network request may be disconnected at any time.
4072 *
4073 * <p>For example, an application could use this method to obtain a connected cellular network
4074 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4075 * radio to consume additional power. Or, an application could inform the system that it wants
4076 * a network supporting sending MMSes and have the system let it know about the currently best
4077 * MMS-supporting network through the provided {@link NetworkCallback}.
4078 *
4079 * <p>The status of the request can be followed by listening to the various callbacks described
4080 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4081 * used to direct traffic to the network (although accessing some networks may be subject to
4082 * holding specific permissions). Callers will learn about the specific characteristics of the
4083 * network through
4084 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4085 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4086 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4087 * matching the request at any given time; therefore when a better network matching the request
4088 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4089 * with the new network after which no further updates are given about the previously-best
4090 * network, unless it becomes the best again at some later time. All callbacks are invoked
4091 * in order on the same thread, which by default is a thread created by the framework running
4092 * in the app.
4093 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4094 * callbacks are invoked.
4095 *
4096 * <p>This{@link NetworkRequest} will live until released via
4097 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4098 * which point the system may let go of the network at any time.
4099 *
4100 * <p>A version of this method which takes a timeout is
4101 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4102 * wait for a limited amount of time for the network to become unavailable.
4103 *
4104 * <p>It is presently unsupported to request a network with mutable
4105 * {@link NetworkCapabilities} such as
4106 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4107 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4108 * as these {@code NetworkCapabilities} represent states that a particular
4109 * network may never attain, and whether a network will attain these states
4110 * is unknown prior to bringing up the network so the framework does not
4111 * know how to go about satisfying a request with these capabilities.
4112 *
4113 * <p>This method requires the caller to hold either the
4114 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4115 * or the ability to modify system settings as determined by
4116 * {@link android.provider.Settings.System#canWrite}.</p>
4117 *
4118 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4119 * number of outstanding requests to 100 per app (identified by their UID), shared with
4120 * all variants of this method, of {@link #registerNetworkCallback} as well as
4121 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4122 * Requesting a network with this method will count toward this limit. If this limit is
4123 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4124 * make sure to unregister the callbacks with
4125 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4126 *
4127 * @param request {@link NetworkRequest} describing this request.
4128 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4129 * the callback must not be shared - it uniquely specifies this request.
4130 * The callback is invoked on the default internal Handler.
4131 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4132 * @throws SecurityException if missing the appropriate permissions.
4133 * @throws RuntimeException if the app already has too many callbacks registered.
4134 */
4135 public void requestNetwork(@NonNull NetworkRequest request,
4136 @NonNull NetworkCallback networkCallback) {
4137 requestNetwork(request, networkCallback, getDefaultHandler());
4138 }
4139
4140 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004141 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004142 *
4143 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4144 * but runs all the callbacks on the passed Handler.
4145 *
4146 * <p>This method has the same permission requirements as
4147 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4148 * and throws the same exceptions in the same conditions.
4149 *
4150 * @param request {@link NetworkRequest} describing this request.
4151 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4152 * the callback must not be shared - it uniquely specifies this request.
4153 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4154 */
4155 public void requestNetwork(@NonNull NetworkRequest request,
4156 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4157 CallbackHandler cbHandler = new CallbackHandler(handler);
4158 NetworkCapabilities nc = request.networkCapabilities;
4159 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4160 }
4161
4162 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004163 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004164 * by a timeout.
4165 *
4166 * This function behaves identically to the non-timed-out version
4167 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4168 * is not found within the given time (in milliseconds) the
4169 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4170 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4171 * not have to be released if timed-out (it is automatically released). Unregistering a
4172 * request that timed out is not an error.
4173 *
4174 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4175 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4176 * for that purpose. Calling this method will attempt to bring up the requested network.
4177 *
4178 * <p>This method has the same permission requirements as
4179 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4180 * and throws the same exceptions in the same conditions.
4181 *
4182 * @param request {@link NetworkRequest} describing this request.
4183 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4184 * the callback must not be shared - it uniquely specifies this request.
4185 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4186 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4187 * be a positive value (i.e. >0).
4188 */
4189 public void requestNetwork(@NonNull NetworkRequest request,
4190 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4191 checkTimeout(timeoutMs);
4192 NetworkCapabilities nc = request.networkCapabilities;
4193 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4194 getDefaultHandler());
4195 }
4196
4197 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004198 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004199 * by a timeout.
4200 *
4201 * This method behaves identically to
4202 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4203 * on the passed Handler.
4204 *
4205 * <p>This method has the same permission requirements as
4206 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4207 * and throws the same exceptions in the same conditions.
4208 *
4209 * @param request {@link NetworkRequest} describing this request.
4210 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4211 * the callback must not be shared - it uniquely specifies this request.
4212 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4213 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4214 * before {@link NetworkCallback#onUnavailable} is called.
4215 */
4216 public void requestNetwork(@NonNull NetworkRequest request,
4217 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4218 checkTimeout(timeoutMs);
4219 CallbackHandler cbHandler = new CallbackHandler(handler);
4220 NetworkCapabilities nc = request.networkCapabilities;
4221 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4222 }
4223
4224 /**
4225 * The lookup key for a {@link Network} object included with the intent after
4226 * successfully finding a network for the applications request. Retrieve it with
4227 * {@link android.content.Intent#getParcelableExtra(String)}.
4228 * <p>
4229 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4230 * then you must get a ConnectivityManager instance before doing so.
4231 */
4232 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4233
4234 /**
4235 * The lookup key for a {@link NetworkRequest} object included with the intent after
4236 * successfully finding a network for the applications request. Retrieve it with
4237 * {@link android.content.Intent#getParcelableExtra(String)}.
4238 */
4239 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4240
4241
4242 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004243 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004244 *
4245 * This function behaves identically to the version that takes a NetworkCallback, but instead
4246 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4247 * the request may outlive the calling application and get called back when a suitable
4248 * network is found.
4249 * <p>
4250 * The operation is an Intent broadcast that goes to a broadcast receiver that
4251 * you registered with {@link Context#registerReceiver} or through the
4252 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4253 * <p>
4254 * The operation Intent is delivered with two extras, a {@link Network} typed
4255 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4256 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4257 * the original requests parameters. It is important to create a new,
4258 * {@link NetworkCallback} based request before completing the processing of the
4259 * Intent to reserve the network or it will be released shortly after the Intent
4260 * is processed.
4261 * <p>
4262 * If there is already a request for this Intent registered (with the equality of
4263 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4264 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4265 * <p>
4266 * The request may be released normally by calling
4267 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4268 * <p>It is presently unsupported to request a network with either
4269 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4270 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4271 * as these {@code NetworkCapabilities} represent states that a particular
4272 * network may never attain, and whether a network will attain these states
4273 * is unknown prior to bringing up the network so the framework does not
4274 * know how to go about satisfying a request with these capabilities.
4275 *
4276 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4277 * number of outstanding requests to 100 per app (identified by their UID), shared with
4278 * all variants of this method, of {@link #registerNetworkCallback} as well as
4279 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4280 * Requesting a network with this method will count toward this limit. If this limit is
4281 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4282 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4283 * or {@link #releaseNetworkRequest(PendingIntent)}.
4284 *
4285 * <p>This method requires the caller to hold either the
4286 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4287 * or the ability to modify system settings as determined by
4288 * {@link android.provider.Settings.System#canWrite}.</p>
4289 *
4290 * @param request {@link NetworkRequest} describing this request.
4291 * @param operation Action to perform when the network is available (corresponds
4292 * to the {@link NetworkCallback#onAvailable} call. Typically
4293 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4294 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4295 * @throws SecurityException if missing the appropriate permissions.
4296 * @throws RuntimeException if the app already has too many callbacks registered.
4297 */
4298 public void requestNetwork(@NonNull NetworkRequest request,
4299 @NonNull PendingIntent operation) {
4300 printStackTrace();
4301 checkPendingIntentNotNull(operation);
4302 try {
4303 mService.pendingRequestForNetwork(
4304 request.networkCapabilities, operation, mContext.getOpPackageName(),
4305 getAttributionTag());
4306 } catch (RemoteException e) {
4307 throw e.rethrowFromSystemServer();
4308 } catch (ServiceSpecificException e) {
4309 throw convertServiceException(e);
4310 }
4311 }
4312
4313 /**
4314 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4315 * <p>
4316 * This method has the same behavior as
4317 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4318 * releasing network resources and disconnecting.
4319 *
4320 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4321 * PendingIntent passed to
4322 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4323 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4324 */
4325 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4326 printStackTrace();
4327 checkPendingIntentNotNull(operation);
4328 try {
4329 mService.releasePendingNetworkRequest(operation);
4330 } catch (RemoteException e) {
4331 throw e.rethrowFromSystemServer();
4332 }
4333 }
4334
4335 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004336 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004337 }
4338
4339 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004340 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004341 }
4342
4343 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004344 if (timeoutMs <= 0) {
4345 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4346 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004347 }
4348
4349 /**
4350 * Registers to receive notifications about all networks which satisfy the given
4351 * {@link NetworkRequest}. The callbacks will continue to be called until
4352 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4353 * called.
4354 *
4355 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4356 * number of outstanding requests to 100 per app (identified by their UID), shared with
4357 * all variants of this method, of {@link #requestNetwork} as well as
4358 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4359 * Requesting a network with this method will count toward this limit. If this limit is
4360 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4361 * make sure to unregister the callbacks with
4362 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4363 *
4364 * @param request {@link NetworkRequest} describing this request.
4365 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4366 * networks change state.
4367 * The callback is invoked on the default internal Handler.
4368 * @throws RuntimeException if the app already has too many callbacks registered.
4369 */
4370 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4371 public void registerNetworkCallback(@NonNull NetworkRequest request,
4372 @NonNull NetworkCallback networkCallback) {
4373 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4374 }
4375
4376 /**
4377 * Registers to receive notifications about all networks which satisfy the given
4378 * {@link NetworkRequest}. The callbacks will continue to be called until
4379 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4380 * called.
4381 *
4382 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4383 * number of outstanding requests to 100 per app (identified by their UID), shared with
4384 * all variants of this method, of {@link #requestNetwork} as well as
4385 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4386 * Requesting a network with this method will count toward this limit. If this limit is
4387 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4388 * make sure to unregister the callbacks with
4389 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4390 *
4391 *
4392 * @param request {@link NetworkRequest} describing this request.
4393 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4394 * networks change state.
4395 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4396 * @throws RuntimeException if the app already has too many callbacks registered.
4397 */
4398 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4399 public void registerNetworkCallback(@NonNull NetworkRequest request,
4400 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4401 CallbackHandler cbHandler = new CallbackHandler(handler);
4402 NetworkCapabilities nc = request.networkCapabilities;
4403 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4404 }
4405
4406 /**
4407 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4408 * {@link NetworkRequest}.
4409 *
4410 * This function behaves identically to the version that takes a NetworkCallback, but instead
4411 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4412 * the request may outlive the calling application and get called back when a suitable
4413 * network is found.
4414 * <p>
4415 * The operation is an Intent broadcast that goes to a broadcast receiver that
4416 * you registered with {@link Context#registerReceiver} or through the
4417 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4418 * <p>
4419 * The operation Intent is delivered with two extras, a {@link Network} typed
4420 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4421 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4422 * the original requests parameters.
4423 * <p>
4424 * If there is already a request for this Intent registered (with the equality of
4425 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4426 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4427 * <p>
4428 * The request may be released normally by calling
4429 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4430 *
4431 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4432 * number of outstanding requests to 100 per app (identified by their UID), shared with
4433 * all variants of this method, of {@link #requestNetwork} as well as
4434 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4435 * Requesting a network with this method will count toward this limit. If this limit is
4436 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4437 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4438 * or {@link #releaseNetworkRequest(PendingIntent)}.
4439 *
4440 * @param request {@link NetworkRequest} describing this request.
4441 * @param operation Action to perform when the network is available (corresponds
4442 * to the {@link NetworkCallback#onAvailable} call. Typically
4443 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4444 * @throws RuntimeException if the app already has too many callbacks registered.
4445 */
4446 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4447 public void registerNetworkCallback(@NonNull NetworkRequest request,
4448 @NonNull PendingIntent operation) {
4449 printStackTrace();
4450 checkPendingIntentNotNull(operation);
4451 try {
4452 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004453 request.networkCapabilities, operation, mContext.getOpPackageName(),
4454 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004455 } catch (RemoteException e) {
4456 throw e.rethrowFromSystemServer();
4457 } catch (ServiceSpecificException e) {
4458 throw convertServiceException(e);
4459 }
4460 }
4461
4462 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004463 * Registers to receive notifications about changes in the application's default network. This
4464 * may be a physical network or a virtual network, such as a VPN that applies to the
4465 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004466 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4467 *
4468 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4469 * number of outstanding requests to 100 per app (identified by their UID), shared with
4470 * all variants of this method, of {@link #requestNetwork} as well as
4471 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4472 * Requesting a network with this method will count toward this limit. If this limit is
4473 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4474 * make sure to unregister the callbacks with
4475 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4476 *
4477 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004478 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004479 * The callback is invoked on the default internal Handler.
4480 * @throws RuntimeException if the app already has too many callbacks registered.
4481 */
4482 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4483 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4484 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4485 }
4486
4487 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004488 * Registers to receive notifications about changes in the application's default network. This
4489 * may be a physical network or a virtual network, such as a VPN that applies to the
4490 * application. The callbacks will continue to be called until either the application exits or
4491 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4492 *
4493 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4494 * number of outstanding requests to 100 per app (identified by their UID), shared with
4495 * all variants of this method, of {@link #requestNetwork} as well as
4496 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4497 * Requesting a network with this method will count toward this limit. If this limit is
4498 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4499 * make sure to unregister the callbacks with
4500 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4501 *
4502 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4503 * application's default network changes.
4504 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4505 * @throws RuntimeException if the app already has too many callbacks registered.
4506 */
4507 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4508 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4509 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004510 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004511 }
4512
4513 /**
4514 * Registers to receive notifications about changes in the default network for the specified
4515 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4516 * UID. The callbacks will continue to be called until either the application exits or
4517 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4518 *
4519 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4520 * number of outstanding requests to 100 per app (identified by their UID), shared with
4521 * all variants of this method, of {@link #requestNetwork} as well as
4522 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4523 * Requesting a network with this method will count toward this limit. If this limit is
4524 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4525 * make sure to unregister the callbacks with
4526 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4527 *
4528 * @param uid the UID for which to track default network changes.
4529 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4530 * UID's default network changes.
4531 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4532 * @throws RuntimeException if the app already has too many callbacks registered.
4533 * @hide
4534 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004535 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004536 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4537 @RequiresPermission(anyOf = {
4538 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4539 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004540 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004541 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004542 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004543 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004544 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4545 }
4546
4547 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004548 * Registers to receive notifications about changes in the system default network. The callbacks
4549 * will continue to be called until either the application exits or
4550 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4551 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004552 * This method should not be used to determine networking state seen by applications, because in
4553 * many cases, most or even all application traffic may not use the default network directly,
4554 * and traffic from different applications may go on different networks by default. As an
4555 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4556 * and not onto the system default network. Applications or system components desiring to do
4557 * determine network state as seen by applications should use other methods such as
4558 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4559 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004560 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4561 * number of outstanding requests to 100 per app (identified by their UID), shared with
4562 * all variants of this method, of {@link #requestNetwork} as well as
4563 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4564 * Requesting a network with this method will count toward this limit. If this limit is
4565 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4566 * make sure to unregister the callbacks with
4567 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4568 *
4569 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4570 * system default network changes.
4571 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4572 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004573 *
4574 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004575 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004576 @SystemApi(client = MODULE_LIBRARIES)
4577 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4578 @RequiresPermission(anyOf = {
4579 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4580 android.Manifest.permission.NETWORK_SETTINGS})
4581 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004582 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004583 CallbackHandler cbHandler = new CallbackHandler(handler);
4584 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004585 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004586 }
4587
4588 /**
junyulaibd123062021-03-15 11:48:48 +08004589 * Registers to receive notifications about the best matching network which satisfy the given
4590 * {@link NetworkRequest}. The callbacks will continue to be called until
4591 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4592 * called.
4593 *
4594 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4595 * number of outstanding requests to 100 per app (identified by their UID), shared with
4596 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4597 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4598 * Requesting a network with this method will count toward this limit. If this limit is
4599 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4600 * make sure to unregister the callbacks with
4601 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4602 *
4603 *
4604 * @param request {@link NetworkRequest} describing this request.
4605 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4606 * networks change state.
4607 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4608 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004609 */
junyulai5a5c99b2021-03-05 15:51:17 +08004610 @SuppressLint("ExecutorRegistration")
4611 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4612 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4613 final NetworkCapabilities nc = request.networkCapabilities;
4614 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004615 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004616 }
4617
4618 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004619 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4620 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4621 * network connection for updated bandwidth information. The caller will be notified via
4622 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4623 * method assumes that the caller has previously called
4624 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4625 * changes.
4626 *
4627 * @param network {@link Network} specifying which network you're interested.
4628 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4629 */
4630 public boolean requestBandwidthUpdate(@NonNull Network network) {
4631 try {
4632 return mService.requestBandwidthUpdate(network);
4633 } catch (RemoteException e) {
4634 throw e.rethrowFromSystemServer();
4635 }
4636 }
4637
4638 /**
4639 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4640 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4641 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4642 * If the given {@code NetworkCallback} had previously been used with
4643 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4644 * will be disconnected.
4645 *
4646 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4647 * triggering it as soon as this call returns.
4648 *
4649 * @param networkCallback The {@link NetworkCallback} used when making the request.
4650 */
4651 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4652 printStackTrace();
4653 checkCallbackNotNull(networkCallback);
4654 final List<NetworkRequest> reqs = new ArrayList<>();
4655 // Find all requests associated to this callback and stop callback triggers immediately.
4656 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4657 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004658 if (networkCallback.networkRequest == null) {
4659 throw new IllegalArgumentException("NetworkCallback was not registered");
4660 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004661 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4662 Log.d(TAG, "NetworkCallback was already unregistered");
4663 return;
4664 }
4665 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4666 if (e.getValue() == networkCallback) {
4667 reqs.add(e.getKey());
4668 }
4669 }
4670 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4671 for (NetworkRequest r : reqs) {
4672 try {
4673 mService.releaseNetworkRequest(r);
4674 } catch (RemoteException e) {
4675 throw e.rethrowFromSystemServer();
4676 }
4677 // Only remove mapping if rpc was successful.
4678 sCallbacks.remove(r);
4679 }
4680 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4681 }
4682 }
4683
4684 /**
4685 * Unregisters a callback previously registered via
4686 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4687 *
4688 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4689 * PendingIntent passed to
4690 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4691 * Cannot be null.
4692 */
4693 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4694 releaseNetworkRequest(operation);
4695 }
4696
4697 /**
4698 * Informs the system whether it should switch to {@code network} regardless of whether it is
4699 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4700 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4701 * the system default network regardless of any other network that's currently connected. If
4702 * {@code always} is true, then the choice is remembered, so that the next time the user
4703 * connects to this network, the system will switch to it.
4704 *
4705 * @param network The network to accept.
4706 * @param accept Whether to accept the network even if unvalidated.
4707 * @param always Whether to remember this choice in the future.
4708 *
4709 * @hide
4710 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004711 @SystemApi(client = MODULE_LIBRARIES)
4712 @RequiresPermission(anyOf = {
4713 android.Manifest.permission.NETWORK_SETTINGS,
4714 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4715 android.Manifest.permission.NETWORK_STACK,
4716 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4717 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004718 try {
4719 mService.setAcceptUnvalidated(network, accept, always);
4720 } catch (RemoteException e) {
4721 throw e.rethrowFromSystemServer();
4722 }
4723 }
4724
4725 /**
4726 * Informs the system whether it should consider the network as validated even if it only has
4727 * partial connectivity. If {@code accept} is true, then the network will be considered as
4728 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4729 * is remembered, so that the next time the user connects to this network, the system will
4730 * switch to it.
4731 *
4732 * @param network The network to accept.
4733 * @param accept Whether to consider the network as validated even if it has partial
4734 * connectivity.
4735 * @param always Whether to remember this choice in the future.
4736 *
4737 * @hide
4738 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004739 @SystemApi(client = MODULE_LIBRARIES)
4740 @RequiresPermission(anyOf = {
4741 android.Manifest.permission.NETWORK_SETTINGS,
4742 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4743 android.Manifest.permission.NETWORK_STACK,
4744 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4745 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4746 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004747 try {
4748 mService.setAcceptPartialConnectivity(network, accept, always);
4749 } catch (RemoteException e) {
4750 throw e.rethrowFromSystemServer();
4751 }
4752 }
4753
4754 /**
4755 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4756 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4757 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4758 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4759 *
4760 * @param network The network to accept.
4761 *
4762 * @hide
4763 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004764 @SystemApi(client = MODULE_LIBRARIES)
4765 @RequiresPermission(anyOf = {
4766 android.Manifest.permission.NETWORK_SETTINGS,
4767 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4768 android.Manifest.permission.NETWORK_STACK,
4769 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4770 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004771 try {
4772 mService.setAvoidUnvalidated(network);
4773 } catch (RemoteException e) {
4774 throw e.rethrowFromSystemServer();
4775 }
4776 }
4777
4778 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004779 * Temporarily allow bad wifi to override {@code config_networkAvoidBadWifi} configuration.
4780 *
4781 * @param timeMs The expired current time. The value should be set within a limited time from
4782 * now.
4783 *
4784 * @hide
4785 */
4786 public void setTestAllowBadWifiUntil(long timeMs) {
4787 try {
4788 mService.setTestAllowBadWifiUntil(timeMs);
4789 } catch (RemoteException e) {
4790 throw e.rethrowFromSystemServer();
4791 }
4792 }
4793
4794 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004795 * Requests that the system open the captive portal app on the specified network.
4796 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004797 * <p>This is to be used on networks where a captive portal was detected, as per
4798 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4799 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004800 * @param network The network to log into.
4801 *
4802 * @hide
4803 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004804 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4805 @RequiresPermission(anyOf = {
4806 android.Manifest.permission.NETWORK_SETTINGS,
4807 android.Manifest.permission.NETWORK_STACK,
4808 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4809 })
4810 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004811 try {
4812 mService.startCaptivePortalApp(network);
4813 } catch (RemoteException e) {
4814 throw e.rethrowFromSystemServer();
4815 }
4816 }
4817
4818 /**
4819 * Requests that the system open the captive portal app with the specified extras.
4820 *
4821 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4822 * corresponding permission.
4823 * @param network Network on which the captive portal was detected.
4824 * @param appExtras Extras to include in the app start intent.
4825 * @hide
4826 */
4827 @SystemApi
4828 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4829 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4830 try {
4831 mService.startCaptivePortalAppInternal(network, appExtras);
4832 } catch (RemoteException e) {
4833 throw e.rethrowFromSystemServer();
4834 }
4835 }
4836
4837 /**
4838 * Determine whether the device is configured to avoid bad wifi.
4839 * @hide
4840 */
4841 @SystemApi
4842 @RequiresPermission(anyOf = {
4843 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4844 android.Manifest.permission.NETWORK_STACK})
4845 public boolean shouldAvoidBadWifi() {
4846 try {
4847 return mService.shouldAvoidBadWifi();
4848 } catch (RemoteException e) {
4849 throw e.rethrowFromSystemServer();
4850 }
4851 }
4852
4853 /**
4854 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4855 * time-sensitive user-facing operations when the system default network is temporarily
4856 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4857 * this method), and the operation should be infrequent to ensure that data usage is limited.
4858 *
4859 * An example of such an operation might be a time-sensitive foreground activity, such as a
4860 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4861 */
4862 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4863
4864 /**
4865 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4866 * a backup channel for traffic that is primarily going over another network.
4867 *
4868 * An example might be maintaining backup connections to peers or servers for the purpose of
4869 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4870 * on backup paths should be negligible compared to the traffic on the main path.
4871 */
4872 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4873
4874 /**
4875 * It is acceptable to use metered data to improve network latency and performance.
4876 */
4877 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4878
4879 /**
4880 * Return value to use for unmetered networks. On such networks we currently set all the flags
4881 * to true.
4882 * @hide
4883 */
4884 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4885 MULTIPATH_PREFERENCE_HANDOVER |
4886 MULTIPATH_PREFERENCE_RELIABILITY |
4887 MULTIPATH_PREFERENCE_PERFORMANCE;
4888
Aaron Huangcff22942021-05-27 16:31:26 +08004889 /** @hide */
4890 @Retention(RetentionPolicy.SOURCE)
4891 @IntDef(flag = true, value = {
4892 MULTIPATH_PREFERENCE_HANDOVER,
4893 MULTIPATH_PREFERENCE_RELIABILITY,
4894 MULTIPATH_PREFERENCE_PERFORMANCE,
4895 })
4896 public @interface MultipathPreference {
4897 }
4898
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004899 /**
4900 * Provides a hint to the calling application on whether it is desirable to use the
4901 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4902 * for multipath data transfer on this network when it is not the system default network.
4903 * Applications desiring to use multipath network protocols should call this method before
4904 * each such operation.
4905 *
4906 * @param network The network on which the application desires to use multipath data.
4907 * If {@code null}, this method will return the a preference that will generally
4908 * apply to metered networks.
4909 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4910 */
4911 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4912 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
4913 try {
4914 return mService.getMultipathPreference(network);
4915 } catch (RemoteException e) {
4916 throw e.rethrowFromSystemServer();
4917 }
4918 }
4919
4920 /**
4921 * Resets all connectivity manager settings back to factory defaults.
4922 * @hide
4923 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004924 @SystemApi(client = MODULE_LIBRARIES)
4925 @RequiresPermission(anyOf = {
4926 android.Manifest.permission.NETWORK_SETTINGS,
4927 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004928 public void factoryReset() {
4929 try {
4930 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09004931 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004932 } catch (RemoteException e) {
4933 throw e.rethrowFromSystemServer();
4934 }
4935 }
4936
4937 /**
4938 * Binds the current process to {@code network}. All Sockets created in the future
4939 * (and not explicitly bound via a bound SocketFactory from
4940 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4941 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4942 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4943 * work and all host name resolutions will fail. This is by design so an application doesn't
4944 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4945 * To clear binding pass {@code null} for {@code network}. Using individually bound
4946 * Sockets created by Network.getSocketFactory().createSocket() and
4947 * performing network-specific host name resolutions via
4948 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4949 * {@code bindProcessToNetwork}.
4950 *
4951 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4952 * the current binding.
4953 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4954 */
4955 public boolean bindProcessToNetwork(@Nullable Network network) {
4956 // Forcing callers to call through non-static function ensures ConnectivityManager
4957 // instantiated.
4958 return setProcessDefaultNetwork(network);
4959 }
4960
4961 /**
4962 * Binds the current process to {@code network}. All Sockets created in the future
4963 * (and not explicitly bound via a bound SocketFactory from
4964 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4965 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4966 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4967 * work and all host name resolutions will fail. This is by design so an application doesn't
4968 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4969 * To clear binding pass {@code null} for {@code network}. Using individually bound
4970 * Sockets created by Network.getSocketFactory().createSocket() and
4971 * performing network-specific host name resolutions via
4972 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4973 * {@code setProcessDefaultNetwork}.
4974 *
4975 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4976 * the current binding.
4977 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4978 * @deprecated This function can throw {@link IllegalStateException}. Use
4979 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4980 * is a direct replacement.
4981 */
4982 @Deprecated
4983 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
4984 int netId = (network == null) ? NETID_UNSET : network.netId;
4985 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4986
4987 if (netId != NETID_UNSET) {
4988 netId = network.getNetIdForResolv();
4989 }
4990
4991 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4992 return false;
4993 }
4994
4995 if (!isSameNetId) {
4996 // Set HTTP proxy system properties to match network.
4997 // TODO: Deprecate this static method and replace it with a non-static version.
4998 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09004999 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005000 } catch (SecurityException e) {
5001 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5002 Log.e(TAG, "Can't set proxy properties", e);
5003 }
5004 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005005 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005006 // Must flush socket pool as idle sockets will be bound to previous network and may
5007 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005008 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005009 }
5010
5011 return true;
5012 }
5013
5014 /**
5015 * Returns the {@link Network} currently bound to this process via
5016 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5017 *
5018 * @return {@code Network} to which this process is bound, or {@code null}.
5019 */
5020 @Nullable
5021 public Network getBoundNetworkForProcess() {
5022 // Forcing callers to call thru non-static function ensures ConnectivityManager
5023 // instantiated.
5024 return getProcessDefaultNetwork();
5025 }
5026
5027 /**
5028 * Returns the {@link Network} currently bound to this process via
5029 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5030 *
5031 * @return {@code Network} to which this process is bound, or {@code null}.
5032 * @deprecated Using this function can lead to other functions throwing
5033 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5034 * {@code getBoundNetworkForProcess} is a direct replacement.
5035 */
5036 @Deprecated
5037 @Nullable
5038 public static Network getProcessDefaultNetwork() {
5039 int netId = NetworkUtils.getBoundNetworkForProcess();
5040 if (netId == NETID_UNSET) return null;
5041 return new Network(netId);
5042 }
5043
5044 private void unsupportedStartingFrom(int version) {
5045 if (Process.myUid() == Process.SYSTEM_UID) {
5046 // The getApplicationInfo() call we make below is not supported in system context. Let
5047 // the call through here, and rely on the fact that ConnectivityService will refuse to
5048 // allow the system to use these APIs anyway.
5049 return;
5050 }
5051
5052 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5053 throw new UnsupportedOperationException(
5054 "This method is not supported in target SDK version " + version + " and above");
5055 }
5056 }
5057
5058 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5059 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5060 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5061 // remove these exemptions. Note that this check is not secure, and apps can still access these
5062 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5063 // so is unsupported and may break in the future. http://b/22728205
5064 private void checkLegacyRoutingApiAccess() {
5065 unsupportedStartingFrom(VERSION_CODES.M);
5066 }
5067
5068 /**
5069 * Binds host resolutions performed by this process to {@code network}.
5070 * {@link #bindProcessToNetwork} takes precedence over this setting.
5071 *
5072 * @param network The {@link Network} to bind host resolutions from the current process to, or
5073 * {@code null} to clear the current binding.
5074 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5075 * @hide
5076 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5077 */
5078 @Deprecated
5079 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5080 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5081 return NetworkUtils.bindProcessToNetworkForHostResolution(
5082 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5083 }
5084
5085 /**
5086 * Device is not restricting metered network activity while application is running on
5087 * background.
5088 */
5089 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5090
5091 /**
5092 * Device is restricting metered network activity while application is running on background,
5093 * but application is allowed to bypass it.
5094 * <p>
5095 * In this state, application should take action to mitigate metered network access.
5096 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5097 */
5098 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5099
5100 /**
5101 * Device is restricting metered network activity while application is running on background.
5102 * <p>
5103 * In this state, application should not try to use the network while running on background,
5104 * because it would be denied.
5105 */
5106 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5107
5108 /**
5109 * A change in the background metered network activity restriction has occurred.
5110 * <p>
5111 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5112 * applies to them.
5113 * <p>
5114 * This is only sent to registered receivers, not manifest receivers.
5115 */
5116 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5117 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5118 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5119
Aaron Huangcff22942021-05-27 16:31:26 +08005120 /** @hide */
5121 @Retention(RetentionPolicy.SOURCE)
5122 @IntDef(flag = false, value = {
5123 RESTRICT_BACKGROUND_STATUS_DISABLED,
5124 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5125 RESTRICT_BACKGROUND_STATUS_ENABLED,
5126 })
5127 public @interface RestrictBackgroundStatus {
5128 }
5129
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005130 /**
5131 * Determines if the calling application is subject to metered network restrictions while
5132 * running on background.
5133 *
5134 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5135 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5136 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5137 */
5138 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5139 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005140 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005141 } catch (RemoteException e) {
5142 throw e.rethrowFromSystemServer();
5143 }
5144 }
5145
5146 /**
5147 * The network watchlist is a list of domains and IP addresses that are associated with
5148 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5149 * currently used by the system for validation purposes.
5150 *
5151 * @return Hash of network watchlist config file. Null if config does not exist.
5152 */
5153 @Nullable
5154 public byte[] getNetworkWatchlistConfigHash() {
5155 try {
5156 return mService.getNetworkWatchlistConfigHash();
5157 } catch (RemoteException e) {
5158 Log.e(TAG, "Unable to get watchlist config hash");
5159 throw e.rethrowFromSystemServer();
5160 }
5161 }
5162
5163 /**
5164 * Returns the {@code uid} of the owner of a network connection.
5165 *
5166 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5167 * IPPROTO_UDP} currently supported.
5168 * @param local The local {@link InetSocketAddress} of a connection.
5169 * @param remote The remote {@link InetSocketAddress} of a connection.
5170 * @return {@code uid} if the connection is found and the app has permission to observe it
5171 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5172 * android.os.Process#INVALID_UID} if the connection is not found.
5173 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5174 * user.
5175 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5176 */
5177 public int getConnectionOwnerUid(
5178 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5179 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5180 try {
5181 return mService.getConnectionOwnerUid(connectionInfo);
5182 } catch (RemoteException e) {
5183 throw e.rethrowFromSystemServer();
5184 }
5185 }
5186
5187 private void printStackTrace() {
5188 if (DEBUG) {
5189 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5190 final StringBuffer sb = new StringBuffer();
5191 for (int i = 3; i < callStack.length; i++) {
5192 final String stackTrace = callStack[i].toString();
5193 if (stackTrace == null || stackTrace.contains("android.os")) {
5194 break;
5195 }
5196 sb.append(" [").append(stackTrace).append("]");
5197 }
5198 Log.d(TAG, "StackLog:" + sb.toString());
5199 }
5200 }
5201
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005202 /** @hide */
5203 public TestNetworkManager startOrGetTestNetworkManager() {
5204 final IBinder tnBinder;
5205 try {
5206 tnBinder = mService.startOrGetTestNetworkService();
5207 } catch (RemoteException e) {
5208 throw e.rethrowFromSystemServer();
5209 }
5210
5211 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5212 }
5213
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005214 /** @hide */
5215 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5216 return new ConnectivityDiagnosticsManager(mContext, mService);
5217 }
5218
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005219 /**
5220 * Simulates a Data Stall for the specified Network.
5221 *
5222 * <p>This method should only be used for tests.
5223 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005224 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5225 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005226 *
5227 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005228 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5229 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5230 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005231 * @param network The Network for which a Data Stall is being simluated.
5232 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5233 * @throws SecurityException if the caller is not the owner of the given network.
5234 * @hide
5235 */
5236 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5237 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5238 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005239 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005240 @NonNull Network network, @NonNull PersistableBundle extras) {
5241 try {
5242 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5243 } catch (RemoteException e) {
5244 e.rethrowFromSystemServer();
5245 }
5246 }
5247
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005248 @NonNull
5249 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5250
5251 /**
5252 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5253 * receive available QoS events related to the {@link Network} and local ip + port
5254 * specified within socketInfo.
5255 * <p/>
5256 * The same {@link QosCallback} must be unregistered before being registered a second time,
5257 * otherwise {@link QosCallbackRegistrationException} is thrown.
5258 * <p/>
5259 * This API does not, in itself, require any permission if called with a network that is not
5260 * restricted. However, the underlying implementation currently only supports the IMS network,
5261 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5262 * useful, because they'd never be called back on networks that they would have access to.
5263 *
5264 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5265 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5266 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5267 * @throws RuntimeException if the app already has too many callbacks registered.
5268 *
5269 * Exceptions after the time of registration is passed through
5270 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5271 *
5272 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005273 * @param executor The executor on which the callback will be invoked. The provided
5274 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005275 * callbacks cannot be guaranteed.onQosCallbackRegistered
5276 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005277 *
5278 * @hide
5279 */
5280 @SystemApi
5281 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005282 @CallbackExecutor @NonNull final Executor executor,
5283 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005284 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005285 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005286 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005287
5288 try {
5289 synchronized (mQosCallbackConnections) {
5290 if (getQosCallbackConnection(callback) == null) {
5291 final QosCallbackConnection connection =
5292 new QosCallbackConnection(this, callback, executor);
5293 mQosCallbackConnections.add(connection);
5294 mService.registerQosSocketCallback(socketInfo, connection);
5295 } else {
5296 Log.e(TAG, "registerQosCallback: Callback already registered");
5297 throw new QosCallbackRegistrationException();
5298 }
5299 }
5300 } catch (final RemoteException e) {
5301 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5302
5303 // The same unregister method method is called for consistency even though nothing
5304 // will be sent to the ConnectivityService since the callback was never successfully
5305 // registered.
5306 unregisterQosCallback(callback);
5307 e.rethrowFromSystemServer();
5308 } catch (final ServiceSpecificException e) {
5309 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5310 unregisterQosCallback(callback);
5311 throw convertServiceException(e);
5312 }
5313 }
5314
5315 /**
5316 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5317 * events once unregistered and can be registered a second time.
5318 * <p/>
5319 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5320 *
5321 * @param callback the callback being unregistered
5322 *
5323 * @hide
5324 */
5325 @SystemApi
5326 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5327 Objects.requireNonNull(callback, "The callback must be non-null");
5328 try {
5329 synchronized (mQosCallbackConnections) {
5330 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5331 if (connection != null) {
5332 connection.stopReceivingMessages();
5333 mService.unregisterQosCallback(connection);
5334 mQosCallbackConnections.remove(connection);
5335 } else {
5336 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5337 }
5338 }
5339 } catch (final RemoteException e) {
5340 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5341 e.rethrowFromSystemServer();
5342 }
5343 }
5344
5345 /**
5346 * Gets the connection related to the callback.
5347 *
5348 * @param callback the callback to look up
5349 * @return the related connection
5350 */
5351 @Nullable
5352 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5353 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5354 // Checking by reference here is intentional
5355 if (connection.getCallback() == callback) {
5356 return connection;
5357 }
5358 }
5359 return null;
5360 }
5361
5362 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005363 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005364 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5365 * be used to request that the system provide a network without causing the network to be
5366 * in the foreground.
5367 *
5368 * <p>This method will attempt to find the best network that matches the passed
5369 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5370 * criteria. The platform will evaluate which network is the best at its own discretion.
5371 * Throughput, latency, cost per byte, policy, user preference and other considerations
5372 * may be factored in the decision of what is considered the best network.
5373 *
5374 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5375 * matching this request, while always attempting to match the request to a better network if
5376 * possible. If a better match is found, the platform will switch this request to the now-best
5377 * network and inform the app of the newly best network by invoking
5378 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5379 * will not try to maintain any other network than the best one currently matching the request:
5380 * a network not matching any network request may be disconnected at any time.
5381 *
5382 * <p>For example, an application could use this method to obtain a connected cellular network
5383 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5384 * radio to consume additional power. Or, an application could inform the system that it wants
5385 * a network supporting sending MMSes and have the system let it know about the currently best
5386 * MMS-supporting network through the provided {@link NetworkCallback}.
5387 *
5388 * <p>The status of the request can be followed by listening to the various callbacks described
5389 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5390 * used to direct traffic to the network (although accessing some networks may be subject to
5391 * holding specific permissions). Callers will learn about the specific characteristics of the
5392 * network through
5393 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5394 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5395 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5396 * matching the request at any given time; therefore when a better network matching the request
5397 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5398 * with the new network after which no further updates are given about the previously-best
5399 * network, unless it becomes the best again at some later time. All callbacks are invoked
5400 * in order on the same thread, which by default is a thread created by the framework running
5401 * in the app.
5402 *
5403 * <p>This{@link NetworkRequest} will live until released via
5404 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5405 * which point the system may let go of the network at any time.
5406 *
5407 * <p>It is presently unsupported to request a network with mutable
5408 * {@link NetworkCapabilities} such as
5409 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5410 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5411 * as these {@code NetworkCapabilities} represent states that a particular
5412 * network may never attain, and whether a network will attain these states
5413 * is unknown prior to bringing up the network so the framework does not
5414 * know how to go about satisfying a request with these capabilities.
5415 *
5416 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5417 * number of outstanding requests to 100 per app (identified by their UID), shared with
5418 * all variants of this method, of {@link #registerNetworkCallback} as well as
5419 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5420 * Requesting a network with this method will count toward this limit. If this limit is
5421 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5422 * make sure to unregister the callbacks with
5423 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5424 *
5425 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005426 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5427 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005428 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5429 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005430 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5431 * @throws SecurityException if missing the appropriate permissions.
5432 * @throws RuntimeException if the app already has too many callbacks registered.
5433 *
5434 * @hide
5435 */
5436 @SystemApi(client = MODULE_LIBRARIES)
5437 @SuppressLint("ExecutorRegistration")
5438 @RequiresPermission(anyOf = {
5439 android.Manifest.permission.NETWORK_SETTINGS,
5440 android.Manifest.permission.NETWORK_STACK,
5441 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5442 })
5443 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005444 @NonNull NetworkCallback networkCallback,
5445 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005446 final NetworkCapabilities nc = request.networkCapabilities;
5447 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005448 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005449 }
James Mattis12aeab82021-01-10 14:24:24 -08005450
5451 /**
James Mattis12aeab82021-01-10 14:24:24 -08005452 * Used by automotive devices to set the network preferences used to direct traffic at an
5453 * application level as per the given OemNetworkPreferences. An example use-case would be an
5454 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5455 * vehicle via a particular network.
5456 *
5457 * Calling this will overwrite the existing preference.
5458 *
5459 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5460 * @param executor the executor on which listener will be invoked.
5461 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5462 * communicate completion of setOemNetworkPreference(). This will only be
5463 * called once upon successful completion of setOemNetworkPreference().
5464 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5465 * @throws SecurityException if missing the appropriate permissions.
5466 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005467 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005468 */
James Mattis6e2d7022021-01-26 16:23:52 -08005469 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005470 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005471 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005472 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005473 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005474 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5475 if (null != listener) {
5476 Objects.requireNonNull(executor, "Executor must be non-null");
5477 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005478 final IOnCompleteListener listenerInternal = listener == null ? null :
5479 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005480 @Override
5481 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005482 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005483 }
5484 };
5485
5486 try {
5487 mService.setOemNetworkPreference(preference, listenerInternal);
5488 } catch (RemoteException e) {
5489 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5490 throw e.rethrowFromSystemServer();
5491 }
5492 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005493
Chalard Jeanad565e22021-02-25 17:23:40 +09005494 /**
5495 * Request that a user profile is put by default on a network matching a given preference.
5496 *
5497 * See the documentation for the individual preferences for a description of the supported
5498 * behaviors.
5499 *
5500 * @param profile the profile concerned.
5501 * @param preference the preference for this profile.
5502 * @param executor an executor to execute the listener on. Optional if listener is null.
5503 * @param listener an optional listener to listen for completion of the operation.
5504 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5505 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005506 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5507 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005508 * @hide
5509 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005510 // This function is for establishing per-profile default networking and can only be called by
5511 // the device policy manager, running as the system server. It would make no sense to call it
5512 // on a context for a user because it does not establish a setting on behalf of a user, rather
5513 // it establishes a setting for a user on behalf of the DPM.
5514 @SuppressLint({"UserHandle"})
5515 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005516 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005517 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005518 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005519 @ProfileNetworkPreferencePolicy final int preference,
5520 @Nullable @CallbackExecutor final Executor executor,
5521 @Nullable final Runnable listener) {
5522
5523 ProfileNetworkPreference.Builder preferenceBuilder =
5524 new ProfileNetworkPreference.Builder();
5525 preferenceBuilder.setPreference(preference);
5526 setProfileNetworkPreferences(profile,
5527 List.of(preferenceBuilder.build()), executor, listener);
5528 }
5529
5530 /**
5531 * Set a list of default network selection policies for a user profile.
5532 *
5533 * Calling this API with a user handle defines the entire policy for that user handle.
5534 * It will overwrite any setting previously set for the same user profile,
5535 * and not affect previously set settings for other handles.
5536 *
5537 * Call this API with an empty list to remove settings for this user profile.
5538 *
5539 * See {@link ProfileNetworkPreference} for more details on each preference
5540 * parameter.
5541 *
5542 * @param profile the user profile for which the preference is being set.
5543 * @param profileNetworkPreferences the list of profile network preferences for the
5544 * provided profile.
5545 * @param executor an executor to execute the listener on. Optional if listener is null.
5546 * @param listener an optional listener to listen for completion of the operation.
5547 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5548 * @throws SecurityException if missing the appropriate permissions.
5549 * @hide
5550 */
5551 @SystemApi(client = MODULE_LIBRARIES)
5552 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5553 public void setProfileNetworkPreferences(
5554 @NonNull final UserHandle profile,
5555 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005556 @Nullable @CallbackExecutor final Executor executor,
5557 @Nullable final Runnable listener) {
5558 if (null != listener) {
5559 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5560 }
5561 final IOnCompleteListener proxy;
5562 if (null == listener) {
5563 proxy = null;
5564 } else {
5565 proxy = new IOnCompleteListener.Stub() {
5566 @Override
5567 public void onComplete() {
5568 executor.execute(listener::run);
5569 }
5570 };
5571 }
5572 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005573 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005574 } catch (RemoteException e) {
5575 throw e.rethrowFromSystemServer();
5576 }
5577 }
5578
lucaslin5cdbcfb2021-03-12 00:46:33 +08005579 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005580 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005581 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005582 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005583
5584 /**
5585 * Get the network ID range reserved for IPSec tunnel interfaces.
5586 *
5587 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5588 * @hide
5589 */
5590 @SystemApi(client = MODULE_LIBRARIES)
5591 @NonNull
5592 public static Range<Integer> getIpSecNetIdRange() {
5593 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5594 }
markchien738ad912021-12-09 18:15:45 +08005595
5596 /**
markchiene1561fa2021-12-09 22:00:56 +08005597 * Sets whether the specified UID is allowed to use data on metered networks even when
5598 * background data is restricted.
markchien738ad912021-12-09 18:15:45 +08005599 *
5600 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005601 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005602 * @hide
5603 */
5604 @SystemApi(client = MODULE_LIBRARIES)
5605 @RequiresPermission(anyOf = {
5606 android.Manifest.permission.NETWORK_SETTINGS,
5607 android.Manifest.permission.NETWORK_STACK,
5608 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5609 })
5610 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
5611 try {
5612 mService.updateMeteredNetworkAllowList(uid, add);
5613 } catch (RemoteException e) {
5614 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005615 }
5616 }
5617
5618 /**
markchiene1561fa2021-12-09 22:00:56 +08005619 * Sets whether the specified UID is prevented from using background data on metered networks.
5620 * Takes precedence over {@link #updateMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08005621 *
5622 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005623 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08005624 * @hide
5625 */
5626 @SystemApi(client = MODULE_LIBRARIES)
5627 @RequiresPermission(anyOf = {
5628 android.Manifest.permission.NETWORK_SETTINGS,
5629 android.Manifest.permission.NETWORK_STACK,
5630 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5631 })
5632 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
5633 try {
5634 mService.updateMeteredNetworkDenyList(uid, add);
5635 } catch (RemoteException e) {
5636 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08005637 }
5638 }
5639
5640 /**
5641 * Sets a firewall rule for the specified UID on the specified chain.
5642 *
5643 * @param chain target chain.
5644 * @param uid uid to allow/deny.
markchien68cfadc2022-01-14 13:39:54 +08005645 * @param allow whether networking is allowed or denied.
5646 * @throws IllegalStateException if updating firewall rule failed.
markchiene1561fa2021-12-09 22:00:56 +08005647 * @hide
5648 */
5649 @SystemApi(client = MODULE_LIBRARIES)
5650 @RequiresPermission(anyOf = {
5651 android.Manifest.permission.NETWORK_SETTINGS,
5652 android.Manifest.permission.NETWORK_STACK,
5653 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5654 })
5655 public void updateFirewallRule(@FirewallChain final int chain, final int uid,
5656 final boolean allow) {
5657 try {
5658 mService.updateFirewallRule(chain, uid, allow);
5659 } catch (RemoteException e) {
5660 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005661 }
5662 }
markchien98a6f952022-01-13 23:43:53 +08005663
5664 /**
5665 * Enables or disables the specified firewall chain.
5666 *
5667 * @param chain target chain.
5668 * @param enable whether the chain should be enabled.
markchien68cfadc2022-01-14 13:39:54 +08005669 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08005670 * @hide
5671 */
5672 @SystemApi(client = MODULE_LIBRARIES)
5673 @RequiresPermission(anyOf = {
5674 android.Manifest.permission.NETWORK_SETTINGS,
5675 android.Manifest.permission.NETWORK_STACK,
5676 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5677 })
5678 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
5679 try {
5680 mService.setFirewallChainEnabled(chain, enable);
5681 } catch (RemoteException e) {
5682 throw e.rethrowFromSystemServer();
5683 }
5684 }
markchien00a0bed2022-01-13 23:46:13 +08005685
5686 /**
5687 * Replaces the contents of the specified UID-based firewall chain.
5688 *
5689 * @param chain target chain to replace.
5690 * @param uids The list of UIDs to be placed into chain.
markchien68cfadc2022-01-14 13:39:54 +08005691 * @throws IllegalStateException if replacing the firewall chain failed.
markchien00a0bed2022-01-13 23:46:13 +08005692 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
5693 * @hide
5694 */
5695 @SystemApi(client = MODULE_LIBRARIES)
5696 @RequiresPermission(anyOf = {
5697 android.Manifest.permission.NETWORK_SETTINGS,
5698 android.Manifest.permission.NETWORK_STACK,
5699 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5700 })
5701 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
5702 Objects.requireNonNull(uids);
5703 try {
5704 mService.replaceFirewallChain(chain, uids);
5705 } catch (RemoteException e) {
5706 throw e.rethrowFromSystemServer();
5707 }
5708 }
markchien9c806112022-01-11 23:28:23 +08005709
5710 /**
5711 * Request to change the current active network stats map.
5712 * STOPSHIP: Remove this API before T sdk finalized, this API is temporary added for the
5713 * NetworkStatsFactory which is platform code but will be moved into connectivity (tethering)
5714 * mainline module.
5715 *
markchien68cfadc2022-01-14 13:39:54 +08005716 * @throws IllegalStateException if swapping active stats map failed.
markchien9c806112022-01-11 23:28:23 +08005717 * @hide
5718 */
5719 @SystemApi(client = MODULE_LIBRARIES)
5720 @RequiresPermission(anyOf = {
5721 android.Manifest.permission.NETWORK_SETTINGS,
5722 android.Manifest.permission.NETWORK_STACK,
5723 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5724 })
5725 public void swapActiveStatsMap() {
5726 try {
5727 mService.swapActiveStatsMap();
5728 } catch (RemoteException e) {
5729 throw e.rethrowFromSystemServer();
5730 }
5731 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005732}