blob: dbc7fcf3395d66b2c747d283b5d772d8dd2c0585 [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 /**
934 * A kludge to facilitate static access where a Context pointer isn't available, like in the
935 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
936 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
937 * methods that take a Context argument.
938 */
939 private static ConnectivityManager sInstance;
940
941 private final Context mContext;
942
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +0900943 @GuardedBy("mTetheringEventCallbacks")
944 private TetheringManager mTetheringManager;
945
946 private TetheringManager getTetheringManager() {
947 synchronized (mTetheringEventCallbacks) {
948 if (mTetheringManager == null) {
949 mTetheringManager = mContext.getSystemService(TetheringManager.class);
950 }
951 return mTetheringManager;
952 }
953 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900954
955 /**
956 * Tests if a given integer represents a valid network type.
957 * @param networkType the type to be tested
958 * @return a boolean. {@code true} if the type is valid, else {@code false}
959 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
960 * validate a network type.
961 */
962 @Deprecated
963 public static boolean isNetworkTypeValid(int networkType) {
964 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
965 }
966
967 /**
968 * Returns a non-localized string representing a given network type.
969 * ONLY used for debugging output.
970 * @param type the type needing naming
971 * @return a String for the given type, or a string version of the type ("87")
972 * if no name is known.
973 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
974 * {@hide}
975 */
976 @Deprecated
977 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
978 public static String getNetworkTypeName(int type) {
979 switch (type) {
980 case TYPE_NONE:
981 return "NONE";
982 case TYPE_MOBILE:
983 return "MOBILE";
984 case TYPE_WIFI:
985 return "WIFI";
986 case TYPE_MOBILE_MMS:
987 return "MOBILE_MMS";
988 case TYPE_MOBILE_SUPL:
989 return "MOBILE_SUPL";
990 case TYPE_MOBILE_DUN:
991 return "MOBILE_DUN";
992 case TYPE_MOBILE_HIPRI:
993 return "MOBILE_HIPRI";
994 case TYPE_WIMAX:
995 return "WIMAX";
996 case TYPE_BLUETOOTH:
997 return "BLUETOOTH";
998 case TYPE_DUMMY:
999 return "DUMMY";
1000 case TYPE_ETHERNET:
1001 return "ETHERNET";
1002 case TYPE_MOBILE_FOTA:
1003 return "MOBILE_FOTA";
1004 case TYPE_MOBILE_IMS:
1005 return "MOBILE_IMS";
1006 case TYPE_MOBILE_CBS:
1007 return "MOBILE_CBS";
1008 case TYPE_WIFI_P2P:
1009 return "WIFI_P2P";
1010 case TYPE_MOBILE_IA:
1011 return "MOBILE_IA";
1012 case TYPE_MOBILE_EMERGENCY:
1013 return "MOBILE_EMERGENCY";
1014 case TYPE_PROXY:
1015 return "PROXY";
1016 case TYPE_VPN:
1017 return "VPN";
1018 default:
1019 return Integer.toString(type);
1020 }
1021 }
1022
1023 /**
1024 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001025 */
lucaslin10774b72021-03-17 14:16:01 +08001026 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001027 public void systemReady() {
1028 try {
1029 mService.systemReady();
1030 } catch (RemoteException e) {
1031 throw e.rethrowFromSystemServer();
1032 }
1033 }
1034
1035 /**
1036 * Checks if a given type uses the cellular data connection.
1037 * This should be replaced in the future by a network property.
1038 * @param networkType the type to check
1039 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1040 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1041 * {@hide}
1042 */
1043 @Deprecated
1044 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1045 public static boolean isNetworkTypeMobile(int networkType) {
1046 switch (networkType) {
1047 case TYPE_MOBILE:
1048 case TYPE_MOBILE_MMS:
1049 case TYPE_MOBILE_SUPL:
1050 case TYPE_MOBILE_DUN:
1051 case TYPE_MOBILE_HIPRI:
1052 case TYPE_MOBILE_FOTA:
1053 case TYPE_MOBILE_IMS:
1054 case TYPE_MOBILE_CBS:
1055 case TYPE_MOBILE_IA:
1056 case TYPE_MOBILE_EMERGENCY:
1057 return true;
1058 default:
1059 return false;
1060 }
1061 }
1062
1063 /**
1064 * Checks if the given network type is backed by a Wi-Fi radio.
1065 *
1066 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1067 * @hide
1068 */
1069 @Deprecated
1070 public static boolean isNetworkTypeWifi(int networkType) {
1071 switch (networkType) {
1072 case TYPE_WIFI:
1073 case TYPE_WIFI_P2P:
1074 return true;
1075 default:
1076 return false;
1077 }
1078 }
1079
1080 /**
Chalard Jeanad565e22021-02-25 17:23:40 +09001081 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1082 * Specify that the traffic for this user should by follow the default rules.
1083 * @hide
1084 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001085 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001086 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1087
1088 /**
1089 * Preference for {@link #setNetworkPreferenceForUser(UserHandle, int, Executor, Runnable)}.
1090 * Specify that the traffic for this user should by default go on a network with
1091 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1092 * if no such network is available.
1093 * @hide
1094 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001095 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001096 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1097
1098 /** @hide */
1099 @Retention(RetentionPolicy.SOURCE)
1100 @IntDef(value = {
1101 PROFILE_NETWORK_PREFERENCE_DEFAULT,
1102 PROFILE_NETWORK_PREFERENCE_ENTERPRISE
1103 })
1104 public @interface ProfileNetworkPreference {
1105 }
1106
1107 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001108 * Specifies the preferred network type. When the device has more
1109 * than one type available the preferred network type will be used.
1110 *
1111 * @param preference the network type to prefer over all others. It is
1112 * unspecified what happens to the old preferred network in the
1113 * overall ordering.
1114 * @deprecated Functionality has been removed as it no longer makes sense,
1115 * with many more than two networks - we'd need an array to express
1116 * preference. Instead we use dynamic network properties of
1117 * the networks to describe their precedence.
1118 */
1119 @Deprecated
1120 public void setNetworkPreference(int preference) {
1121 }
1122
1123 /**
1124 * Retrieves the current preferred network type.
1125 *
1126 * @return an integer representing the preferred network type
1127 *
1128 * @deprecated Functionality has been removed as it no longer makes sense,
1129 * with many more than two networks - we'd need an array to express
1130 * preference. Instead we use dynamic network properties of
1131 * the networks to describe their precedence.
1132 */
1133 @Deprecated
1134 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1135 public int getNetworkPreference() {
1136 return TYPE_NONE;
1137 }
1138
1139 /**
1140 * Returns details about the currently active default data network. When
1141 * connected, this network is the default route for outgoing connections.
1142 * You should always check {@link NetworkInfo#isConnected()} before initiating
1143 * network traffic. This may return {@code null} when there is no default
1144 * network.
1145 * Note that if the default network is a VPN, this method will return the
1146 * NetworkInfo for one of its underlying networks instead, or null if the
1147 * VPN agent did not specify any. Apps interested in learning about VPNs
1148 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1149 *
1150 * @return a {@link NetworkInfo} object for the current default network
1151 * or {@code null} if no default network is currently active
1152 * @deprecated See {@link NetworkInfo}.
1153 */
1154 @Deprecated
1155 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1156 @Nullable
1157 public NetworkInfo getActiveNetworkInfo() {
1158 try {
1159 return mService.getActiveNetworkInfo();
1160 } catch (RemoteException e) {
1161 throw e.rethrowFromSystemServer();
1162 }
1163 }
1164
1165 /**
1166 * Returns a {@link Network} object corresponding to the currently active
1167 * default data network. In the event that the current active default data
1168 * network disconnects, the returned {@code Network} object will no longer
1169 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001170 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001171 *
1172 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001173 * {@code null} if no default network is currently active or if
1174 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001175 */
1176 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1177 @Nullable
1178 public Network getActiveNetwork() {
1179 try {
1180 return mService.getActiveNetwork();
1181 } catch (RemoteException e) {
1182 throw e.rethrowFromSystemServer();
1183 }
1184 }
1185
1186 /**
1187 * Returns a {@link Network} object corresponding to the currently active
1188 * default data network for a specific UID. In the event that the default data
1189 * network disconnects, the returned {@code Network} object will no longer
1190 * be usable. This will return {@code null} when there is no default
1191 * network for the UID.
1192 *
1193 * @return a {@link Network} object for the current default network for the
1194 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001195 *
1196 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001197 */
1198 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1199 @Nullable
1200 public Network getActiveNetworkForUid(int uid) {
1201 return getActiveNetworkForUid(uid, false);
1202 }
1203
1204 /** {@hide} */
1205 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1206 try {
1207 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1208 } catch (RemoteException e) {
1209 throw e.rethrowFromSystemServer();
1210 }
1211 }
1212
1213 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001214 * Adds or removes a requirement for given UID ranges to use the VPN.
1215 *
1216 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1217 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1218 * otherwise have permission to bypass the VPN (e.g., because they have the
1219 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1220 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1221 * set to {@code false}, a previously-added restriction is removed.
1222 * <p>
1223 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1224 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1225 * remove a previously-added range, the exact range must be removed as is.
1226 * <p>
1227 * The changes are applied asynchronously and may not have been applied by the time the method
1228 * returns. Apps will be notified about any changes that apply to them via
1229 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1230 * effect.
1231 * <p>
1232 * This method should be called only by the VPN code.
1233 *
1234 * @param ranges the UID ranges to restrict
1235 * @param requireVpn whether the specified UID ranges must use a VPN
1236 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001237 * @hide
1238 */
1239 @RequiresPermission(anyOf = {
1240 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001241 android.Manifest.permission.NETWORK_STACK,
1242 android.Manifest.permission.NETWORK_SETTINGS})
1243 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001244 public void setRequireVpnForUids(boolean requireVpn,
1245 @NonNull Collection<Range<Integer>> ranges) {
1246 Objects.requireNonNull(ranges);
1247 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1248 // This method is not necessarily expected to be used outside the system server, so
1249 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1250 // stack process, or by tests.
1251 UidRange[] rangesArray = new UidRange[ranges.size()];
1252 int index = 0;
1253 for (Range<Integer> range : ranges) {
1254 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1255 }
1256 try {
1257 mService.setRequireVpnForUids(requireVpn, rangesArray);
1258 } catch (RemoteException e) {
1259 throw e.rethrowFromSystemServer();
1260 }
1261 }
1262
1263 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001264 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1265 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1266 * but is still supported for backwards compatibility.
1267 * <p>
1268 * This type of VPN is assumed always to use the system default network, and must always declare
1269 * exactly one underlying network, which is the network that was the default when the VPN
1270 * connected.
1271 * <p>
1272 * Calling this method with {@code true} enables legacy behaviour, specifically:
1273 * <ul>
1274 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1275 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1276 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1277 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1278 * underlying the VPN.</li>
1279 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1280 * similarly replaced by the VPN network state.</li>
1281 * <li>Information on current network interfaces passed to NetworkStatsService will not
1282 * include any VPN interfaces.</li>
1283 * </ul>
1284 *
1285 * @param enabled whether legacy lockdown VPN is enabled or disabled
1286 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001287 * @hide
1288 */
1289 @RequiresPermission(anyOf = {
1290 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001291 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001292 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001293 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001294 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1295 try {
1296 mService.setLegacyLockdownVpnEnabled(enabled);
1297 } catch (RemoteException e) {
1298 throw e.rethrowFromSystemServer();
1299 }
1300 }
1301
1302 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001303 * Returns details about the currently active default data network
1304 * for a given uid. This is for internal use only to avoid spying
1305 * other apps.
1306 *
1307 * @return a {@link NetworkInfo} object for the current default network
1308 * for the given uid or {@code null} if no default network is
1309 * available for the specified uid.
1310 *
1311 * {@hide}
1312 */
1313 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1314 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1315 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1316 return getActiveNetworkInfoForUid(uid, false);
1317 }
1318
1319 /** {@hide} */
1320 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1321 try {
1322 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1323 } catch (RemoteException e) {
1324 throw e.rethrowFromSystemServer();
1325 }
1326 }
1327
1328 /**
1329 * Returns connection status information about a particular
1330 * network type.
1331 *
1332 * @param networkType integer specifying which networkType in
1333 * which you're interested.
1334 * @return a {@link NetworkInfo} object for the requested
1335 * network type or {@code null} if the type is not
1336 * supported by the device. If {@code networkType} is
1337 * TYPE_VPN and a VPN is active for the calling app,
1338 * then this method will try to return one of the
1339 * underlying networks for the VPN or null if the
1340 * VPN agent didn't specify any.
1341 *
1342 * @deprecated This method does not support multiple connected networks
1343 * of the same type. Use {@link #getAllNetworks} and
1344 * {@link #getNetworkInfo(android.net.Network)} instead.
1345 */
1346 @Deprecated
1347 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1348 @Nullable
1349 public NetworkInfo getNetworkInfo(int networkType) {
1350 try {
1351 return mService.getNetworkInfo(networkType);
1352 } catch (RemoteException e) {
1353 throw e.rethrowFromSystemServer();
1354 }
1355 }
1356
1357 /**
1358 * Returns connection status information about a particular
1359 * Network.
1360 *
1361 * @param network {@link Network} specifying which network
1362 * in which you're interested.
1363 * @return a {@link NetworkInfo} object for the requested
1364 * network or {@code null} if the {@code Network}
1365 * is not valid.
1366 * @deprecated See {@link NetworkInfo}.
1367 */
1368 @Deprecated
1369 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1370 @Nullable
1371 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1372 return getNetworkInfoForUid(network, Process.myUid(), false);
1373 }
1374
1375 /** {@hide} */
1376 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1377 try {
1378 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1379 } catch (RemoteException e) {
1380 throw e.rethrowFromSystemServer();
1381 }
1382 }
1383
1384 /**
1385 * Returns connection status information about all network
1386 * types supported by the device.
1387 *
1388 * @return an array of {@link NetworkInfo} objects. Check each
1389 * {@link NetworkInfo#getType} for which type each applies.
1390 *
1391 * @deprecated This method does not support multiple connected networks
1392 * of the same type. Use {@link #getAllNetworks} and
1393 * {@link #getNetworkInfo(android.net.Network)} instead.
1394 */
1395 @Deprecated
1396 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1397 @NonNull
1398 public NetworkInfo[] getAllNetworkInfo() {
1399 try {
1400 return mService.getAllNetworkInfo();
1401 } catch (RemoteException e) {
1402 throw e.rethrowFromSystemServer();
1403 }
1404 }
1405
1406 /**
junyulaib1211372021-03-03 12:09:05 +08001407 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1408 * connected.
1409 * @hide
1410 */
1411 @SystemApi(client = MODULE_LIBRARIES)
1412 @RequiresPermission(anyOf = {
1413 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1414 android.Manifest.permission.NETWORK_STACK,
1415 android.Manifest.permission.NETWORK_SETTINGS})
1416 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001417 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001418 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001419 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001420 } catch (RemoteException e) {
1421 throw e.rethrowFromSystemServer();
1422 }
1423 }
1424
1425 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001426 * Returns the {@link Network} object currently serving a given type, or
1427 * null if the given type is not connected.
1428 *
1429 * @hide
1430 * @deprecated This method does not support multiple connected networks
1431 * of the same type. Use {@link #getAllNetworks} and
1432 * {@link #getNetworkInfo(android.net.Network)} instead.
1433 */
1434 @Deprecated
1435 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1436 @UnsupportedAppUsage
1437 public Network getNetworkForType(int networkType) {
1438 try {
1439 return mService.getNetworkForType(networkType);
1440 } catch (RemoteException e) {
1441 throw e.rethrowFromSystemServer();
1442 }
1443 }
1444
1445 /**
1446 * Returns an array of all {@link Network} currently tracked by the
1447 * framework.
1448 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001449 * @deprecated This method does not provide any notification of network state changes, forcing
1450 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1451 * Apps should use methods such as
1452 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1453 * Apps that desire to obtain information about networks that do not apply to them
1454 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1455 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001456 * @return an array of {@link Network} objects.
1457 */
1458 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1459 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001460 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001461 public Network[] getAllNetworks() {
1462 try {
1463 return mService.getAllNetworks();
1464 } catch (RemoteException e) {
1465 throw e.rethrowFromSystemServer();
1466 }
1467 }
1468
1469 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001470 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001471 * the Networks that applications run by the given user will use by default.
1472 * @hide
1473 */
1474 @UnsupportedAppUsage
1475 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1476 try {
1477 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001478 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001479 } catch (RemoteException e) {
1480 throw e.rethrowFromSystemServer();
1481 }
1482 }
1483
1484 /**
1485 * Returns the IP information for the current default network.
1486 *
1487 * @return a {@link LinkProperties} object describing the IP info
1488 * for the current default network, or {@code null} if there
1489 * is no current default network.
1490 *
1491 * {@hide}
1492 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1493 * value of {@link #getActiveNetwork()} instead. In particular,
1494 * this method will return non-null LinkProperties even if the
1495 * app is blocked by policy from using this network.
1496 */
1497 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1498 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1499 public LinkProperties getActiveLinkProperties() {
1500 try {
1501 return mService.getActiveLinkProperties();
1502 } catch (RemoteException e) {
1503 throw e.rethrowFromSystemServer();
1504 }
1505 }
1506
1507 /**
1508 * Returns the IP information for a given network type.
1509 *
1510 * @param networkType the network type of interest.
1511 * @return a {@link LinkProperties} object describing the IP info
1512 * for the given networkType, or {@code null} if there is
1513 * no current default network.
1514 *
1515 * {@hide}
1516 * @deprecated This method does not support multiple connected networks
1517 * of the same type. Use {@link #getAllNetworks},
1518 * {@link #getNetworkInfo(android.net.Network)}, and
1519 * {@link #getLinkProperties(android.net.Network)} instead.
1520 */
1521 @Deprecated
1522 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1523 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1524 public LinkProperties getLinkProperties(int networkType) {
1525 try {
1526 return mService.getLinkPropertiesForType(networkType);
1527 } catch (RemoteException e) {
1528 throw e.rethrowFromSystemServer();
1529 }
1530 }
1531
1532 /**
1533 * Get the {@link LinkProperties} for the given {@link Network}. This
1534 * will return {@code null} if the network is unknown.
1535 *
1536 * @param network The {@link Network} object identifying the network in question.
1537 * @return The {@link LinkProperties} for the network, or {@code null}.
1538 */
1539 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1540 @Nullable
1541 public LinkProperties getLinkProperties(@Nullable Network network) {
1542 try {
1543 return mService.getLinkProperties(network);
1544 } catch (RemoteException e) {
1545 throw e.rethrowFromSystemServer();
1546 }
1547 }
1548
1549 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001550 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Chalard Jean070bdd42021-04-30 20:22:10 +09001551 * will return {@code null} if the network is unknown or if the |network| argument is null.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001552 *
Roshan Piuse08bc182020-12-22 15:10:42 -08001553 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1554 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1555 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1556 * this location sensitive information (subject to app's location permissions) will be
1557 * noted by system. To include any location sensitive data in {@link TransportInfo},
1558 * use a {@link NetworkCallback} with
1559 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1560 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001561 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001562 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001563 */
1564 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1565 @Nullable
1566 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1567 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001568 return mService.getNetworkCapabilities(
1569 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001570 } catch (RemoteException e) {
1571 throw e.rethrowFromSystemServer();
1572 }
1573 }
1574
1575 /**
1576 * Gets a URL that can be used for resolving whether a captive portal is present.
1577 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1578 * portal is present.
1579 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1580 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1581 *
1582 * The system network validation may be using different strategies to detect captive portals,
1583 * so this method does not necessarily return a URL used by the system. It only returns a URL
1584 * that may be relevant for other components trying to detect captive portals.
1585 *
1586 * @hide
1587 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1588 * system.
1589 */
1590 @Deprecated
1591 @SystemApi
1592 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1593 public String getCaptivePortalServerUrl() {
1594 try {
1595 return mService.getCaptivePortalServerUrl();
1596 } catch (RemoteException e) {
1597 throw e.rethrowFromSystemServer();
1598 }
1599 }
1600
1601 /**
1602 * Tells the underlying networking system that the caller wants to
1603 * begin using the named feature. The interpretation of {@code feature}
1604 * is completely up to each networking implementation.
1605 *
1606 * <p>This method requires the caller to hold either the
1607 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1608 * or the ability to modify system settings as determined by
1609 * {@link android.provider.Settings.System#canWrite}.</p>
1610 *
1611 * @param networkType specifies which network the request pertains to
1612 * @param feature the name of the feature to be used
1613 * @return an integer value representing the outcome of the request.
1614 * The interpretation of this value is specific to each networking
1615 * implementation+feature combination, except that the value {@code -1}
1616 * always indicates failure.
1617 *
1618 * @deprecated Deprecated in favor of the cleaner
1619 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1620 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1621 * throw {@code UnsupportedOperationException} if called.
1622 * @removed
1623 */
1624 @Deprecated
1625 public int startUsingNetworkFeature(int networkType, String feature) {
1626 checkLegacyRoutingApiAccess();
1627 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1628 if (netCap == null) {
1629 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1630 feature);
1631 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1632 }
1633
1634 NetworkRequest request = null;
1635 synchronized (sLegacyRequests) {
1636 LegacyRequest l = sLegacyRequests.get(netCap);
1637 if (l != null) {
1638 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1639 renewRequestLocked(l);
1640 if (l.currentNetwork != null) {
1641 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1642 } else {
1643 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1644 }
1645 }
1646
1647 request = requestNetworkForFeatureLocked(netCap);
1648 }
1649 if (request != null) {
1650 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1651 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1652 } else {
1653 Log.d(TAG, " request Failed");
1654 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1655 }
1656 }
1657
1658 /**
1659 * Tells the underlying networking system that the caller is finished
1660 * using the named feature. The interpretation of {@code feature}
1661 * is completely up to each networking implementation.
1662 *
1663 * <p>This method requires the caller to hold either the
1664 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1665 * or the ability to modify system settings as determined by
1666 * {@link android.provider.Settings.System#canWrite}.</p>
1667 *
1668 * @param networkType specifies which network the request pertains to
1669 * @param feature the name of the feature that is no longer needed
1670 * @return an integer value representing the outcome of the request.
1671 * The interpretation of this value is specific to each networking
1672 * implementation+feature combination, except that the value {@code -1}
1673 * always indicates failure.
1674 *
1675 * @deprecated Deprecated in favor of the cleaner
1676 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1677 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1678 * throw {@code UnsupportedOperationException} if called.
1679 * @removed
1680 */
1681 @Deprecated
1682 public int stopUsingNetworkFeature(int networkType, String feature) {
1683 checkLegacyRoutingApiAccess();
1684 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1685 if (netCap == null) {
1686 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1687 feature);
1688 return -1;
1689 }
1690
1691 if (removeRequestForFeature(netCap)) {
1692 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1693 }
1694 return 1;
1695 }
1696
1697 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1698 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1699 if (networkType == TYPE_MOBILE) {
1700 switch (feature) {
1701 case "enableCBS":
1702 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1703 case "enableDUN":
1704 case "enableDUNAlways":
1705 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1706 case "enableFOTA":
1707 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1708 case "enableHIPRI":
1709 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1710 case "enableIMS":
1711 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1712 case "enableMMS":
1713 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1714 case "enableSUPL":
1715 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1716 default:
1717 return null;
1718 }
1719 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1720 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1721 }
1722 return null;
1723 }
1724
1725 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1726 if (netCap == null) return TYPE_NONE;
1727 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1728 return TYPE_MOBILE_CBS;
1729 }
1730 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1731 return TYPE_MOBILE_IMS;
1732 }
1733 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1734 return TYPE_MOBILE_FOTA;
1735 }
1736 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1737 return TYPE_MOBILE_DUN;
1738 }
1739 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1740 return TYPE_MOBILE_SUPL;
1741 }
1742 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1743 return TYPE_MOBILE_MMS;
1744 }
1745 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1746 return TYPE_MOBILE_HIPRI;
1747 }
1748 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1749 return TYPE_WIFI_P2P;
1750 }
1751 return TYPE_NONE;
1752 }
1753
1754 private static class LegacyRequest {
1755 NetworkCapabilities networkCapabilities;
1756 NetworkRequest networkRequest;
1757 int expireSequenceNumber;
1758 Network currentNetwork;
1759 int delay = -1;
1760
1761 private void clearDnsBinding() {
1762 if (currentNetwork != null) {
1763 currentNetwork = null;
1764 setProcessDefaultNetworkForHostResolution(null);
1765 }
1766 }
1767
1768 NetworkCallback networkCallback = new NetworkCallback() {
1769 @Override
1770 public void onAvailable(Network network) {
1771 currentNetwork = network;
1772 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1773 setProcessDefaultNetworkForHostResolution(network);
1774 }
1775 @Override
1776 public void onLost(Network network) {
1777 if (network.equals(currentNetwork)) clearDnsBinding();
1778 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1779 }
1780 };
1781 }
1782
1783 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1784 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1785 new HashMap<>();
1786
1787 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1788 synchronized (sLegacyRequests) {
1789 LegacyRequest l = sLegacyRequests.get(netCap);
1790 if (l != null) return l.networkRequest;
1791 }
1792 return null;
1793 }
1794
1795 private void renewRequestLocked(LegacyRequest l) {
1796 l.expireSequenceNumber++;
1797 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1798 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1799 }
1800
1801 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1802 int ourSeqNum = -1;
1803 synchronized (sLegacyRequests) {
1804 LegacyRequest l = sLegacyRequests.get(netCap);
1805 if (l == null) return;
1806 ourSeqNum = l.expireSequenceNumber;
1807 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
1808 }
1809 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1810 }
1811
1812 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1813 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1814 int delay = -1;
1815 int type = legacyTypeForNetworkCapabilities(netCap);
1816 try {
1817 delay = mService.getRestoreDefaultNetworkDelay(type);
1818 } catch (RemoteException e) {
1819 throw e.rethrowFromSystemServer();
1820 }
1821 LegacyRequest l = new LegacyRequest();
1822 l.networkCapabilities = netCap;
1823 l.delay = delay;
1824 l.expireSequenceNumber = 0;
1825 l.networkRequest = sendRequestForNetwork(
1826 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
1827 if (l.networkRequest == null) return null;
1828 sLegacyRequests.put(netCap, l);
1829 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1830 return l.networkRequest;
1831 }
1832
1833 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1834 if (delay >= 0) {
1835 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
1836 CallbackHandler handler = getDefaultHandler();
1837 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1838 handler.sendMessageDelayed(msg, delay);
1839 }
1840 }
1841
1842 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1843 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1844 final LegacyRequest l;
1845 synchronized (sLegacyRequests) {
1846 l = sLegacyRequests.remove(netCap);
1847 }
1848 if (l == null) return false;
1849 unregisterNetworkCallback(l.networkCallback);
1850 l.clearDnsBinding();
1851 return true;
1852 }
1853
1854 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1855 static {
1856 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1857 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1858 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1859 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1860 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1861 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1862 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1863 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1864 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1865 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1866 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1867 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1868 }
1869
1870 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1871 static {
1872 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1873 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1874 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1875 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1876 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1877 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1878 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1879 }
1880
1881 /**
1882 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1883 * instance suitable for registering a request or callback. Throws an
1884 * IllegalArgumentException if no mapping from the legacy type to
1885 * NetworkCapabilities is known.
1886 *
1887 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1888 * to find the network instead.
1889 * @hide
1890 */
1891 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1892 final NetworkCapabilities nc = new NetworkCapabilities();
1893
1894 // Map from type to transports.
1895 final int NOT_FOUND = -1;
1896 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00001897 if (transport == NOT_FOUND) {
1898 throw new IllegalArgumentException("unknown legacy type: " + type);
1899 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001900 nc.addTransportType(transport);
1901
1902 // Map from type to capabilities.
1903 nc.addCapability(sLegacyTypeToCapability.get(
1904 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1905 nc.maybeMarkCapabilitiesRestricted();
1906 return nc;
1907 }
1908
1909 /** @hide */
1910 public static class PacketKeepaliveCallback {
1911 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1912 public PacketKeepaliveCallback() {
1913 }
1914 /** The requested keepalive was successfully started. */
1915 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1916 public void onStarted() {}
1917 /** The keepalive was successfully stopped. */
1918 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1919 public void onStopped() {}
1920 /** An error occurred. */
1921 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1922 public void onError(int error) {}
1923 }
1924
1925 /**
1926 * Allows applications to request that the system periodically send specific packets on their
1927 * behalf, using hardware offload to save battery power.
1928 *
1929 * To request that the system send keepalives, call one of the methods that return a
1930 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1931 * passing in a non-null callback. If the callback is successfully started, the callback's
1932 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1933 * specifying one of the {@code ERROR_*} constants in this class.
1934 *
1935 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1936 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1937 * {@link PacketKeepaliveCallback#onError} if an error occurred.
1938 *
1939 * @deprecated Use {@link SocketKeepalive} instead.
1940 *
1941 * @hide
1942 */
1943 public class PacketKeepalive {
1944
1945 private static final String TAG = "PacketKeepalive";
1946
1947 /** @hide */
1948 public static final int SUCCESS = 0;
1949
1950 /** @hide */
1951 public static final int NO_KEEPALIVE = -1;
1952
1953 /** @hide */
1954 public static final int BINDER_DIED = -10;
1955
1956 /** The specified {@code Network} is not connected. */
1957 public static final int ERROR_INVALID_NETWORK = -20;
1958 /** The specified IP addresses are invalid. For example, the specified source IP address is
1959 * not configured on the specified {@code Network}. */
1960 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1961 /** The requested port is invalid. */
1962 public static final int ERROR_INVALID_PORT = -22;
1963 /** The packet length is invalid (e.g., too long). */
1964 public static final int ERROR_INVALID_LENGTH = -23;
1965 /** The packet transmission interval is invalid (e.g., too short). */
1966 public static final int ERROR_INVALID_INTERVAL = -24;
1967
1968 /** The hardware does not support this request. */
1969 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
1970 /** The hardware returned an error. */
1971 public static final int ERROR_HARDWARE_ERROR = -31;
1972
1973 /** The NAT-T destination port for IPsec */
1974 public static final int NATT_PORT = 4500;
1975
1976 /** The minimum interval in seconds between keepalive packet transmissions */
1977 public static final int MIN_INTERVAL = 10;
1978
1979 private final Network mNetwork;
1980 private final ISocketKeepaliveCallback mCallback;
1981 private final ExecutorService mExecutor;
1982
1983 private volatile Integer mSlot;
1984
1985 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1986 public void stop() {
1987 try {
1988 mExecutor.execute(() -> {
1989 try {
1990 if (mSlot != null) {
1991 mService.stopKeepalive(mNetwork, mSlot);
1992 }
1993 } catch (RemoteException e) {
1994 Log.e(TAG, "Error stopping packet keepalive: ", e);
1995 throw e.rethrowFromSystemServer();
1996 }
1997 });
1998 } catch (RejectedExecutionException e) {
1999 // The internal executor has already stopped due to previous event.
2000 }
2001 }
2002
2003 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002004 Objects.requireNonNull(network, "network cannot be null");
2005 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002006 mNetwork = network;
2007 mExecutor = Executors.newSingleThreadExecutor();
2008 mCallback = new ISocketKeepaliveCallback.Stub() {
2009 @Override
2010 public void onStarted(int slot) {
2011 final long token = Binder.clearCallingIdentity();
2012 try {
2013 mExecutor.execute(() -> {
2014 mSlot = slot;
2015 callback.onStarted();
2016 });
2017 } finally {
2018 Binder.restoreCallingIdentity(token);
2019 }
2020 }
2021
2022 @Override
2023 public void onStopped() {
2024 final long token = Binder.clearCallingIdentity();
2025 try {
2026 mExecutor.execute(() -> {
2027 mSlot = null;
2028 callback.onStopped();
2029 });
2030 } finally {
2031 Binder.restoreCallingIdentity(token);
2032 }
2033 mExecutor.shutdown();
2034 }
2035
2036 @Override
2037 public void onError(int error) {
2038 final long token = Binder.clearCallingIdentity();
2039 try {
2040 mExecutor.execute(() -> {
2041 mSlot = null;
2042 callback.onError(error);
2043 });
2044 } finally {
2045 Binder.restoreCallingIdentity(token);
2046 }
2047 mExecutor.shutdown();
2048 }
2049
2050 @Override
2051 public void onDataReceived() {
2052 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2053 // this callback when data is received.
2054 }
2055 };
2056 }
2057 }
2058
2059 /**
2060 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2061 *
2062 * @deprecated Use {@link #createSocketKeepalive} instead.
2063 *
2064 * @hide
2065 */
2066 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2067 public PacketKeepalive startNattKeepalive(
2068 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2069 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2070 final PacketKeepalive k = new PacketKeepalive(network, callback);
2071 try {
2072 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2073 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2074 } catch (RemoteException e) {
2075 Log.e(TAG, "Error starting packet keepalive: ", e);
2076 throw e.rethrowFromSystemServer();
2077 }
2078 return k;
2079 }
2080
2081 // Construct an invalid fd.
2082 private ParcelFileDescriptor createInvalidFd() {
2083 final int invalidFd = -1;
2084 return ParcelFileDescriptor.adoptFd(invalidFd);
2085 }
2086
2087 /**
2088 * Request that keepalives be started on a IPsec NAT-T socket.
2089 *
2090 * @param network The {@link Network} the socket is on.
2091 * @param socket The socket that needs to be kept alive.
2092 * @param source The source address of the {@link UdpEncapsulationSocket}.
2093 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2094 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2095 * must run callback sequentially, otherwise the order of callbacks cannot be
2096 * guaranteed.
2097 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2098 * changes. Must be extended by applications that use this API.
2099 *
2100 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2101 * given socket.
2102 **/
2103 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2104 @NonNull UdpEncapsulationSocket socket,
2105 @NonNull InetAddress source,
2106 @NonNull InetAddress destination,
2107 @NonNull @CallbackExecutor Executor executor,
2108 @NonNull Callback callback) {
2109 ParcelFileDescriptor dup;
2110 try {
2111 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2112 // which cannot be obtained by the app process.
2113 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2114 } catch (IOException ignored) {
2115 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2116 // ERROR_INVALID_SOCKET.
2117 dup = createInvalidFd();
2118 }
2119 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2120 destination, executor, callback);
2121 }
2122
2123 /**
2124 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2125 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2126 *
2127 * @param network The {@link Network} the socket is on.
2128 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2129 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2130 * from that port.
2131 * @param source The source address of the {@link UdpEncapsulationSocket}.
2132 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2133 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2134 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2135 * must run callback sequentially, otherwise the order of callbacks cannot be
2136 * guaranteed.
2137 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2138 * changes. Must be extended by applications that use this API.
2139 *
2140 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2141 * given socket.
2142 * @hide
2143 */
2144 @SystemApi
2145 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2146 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2147 @NonNull ParcelFileDescriptor pfd,
2148 @NonNull InetAddress source,
2149 @NonNull InetAddress destination,
2150 @NonNull @CallbackExecutor Executor executor,
2151 @NonNull Callback callback) {
2152 ParcelFileDescriptor dup;
2153 try {
2154 // TODO: Consider remove unnecessary dup.
2155 dup = pfd.dup();
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,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002162 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002163 }
2164
2165 /**
2166 * Request that keepalives be started on a TCP socket.
2167 * The socket must be established.
2168 *
2169 * @param network The {@link Network} the socket is on.
2170 * @param socket The socket that needs to be kept alive.
2171 * @param executor The executor on which callback will be invoked. This implementation assumes
2172 * the provided {@link Executor} runs the callbacks in sequence with no
2173 * concurrency. Failing this, no guarantee of correctness can be made. It is
2174 * the responsibility of the caller to ensure the executor provides this
2175 * guarantee. A simple way of creating such an executor is with the standard
2176 * tool {@code Executors.newSingleThreadExecutor}.
2177 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2178 * changes. Must be extended by applications that use this API.
2179 *
2180 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2181 * given socket.
2182 * @hide
2183 */
2184 @SystemApi
2185 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2186 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2187 @NonNull Socket socket,
2188 @NonNull Executor executor,
2189 @NonNull Callback callback) {
2190 ParcelFileDescriptor dup;
2191 try {
2192 dup = ParcelFileDescriptor.fromSocket(socket);
2193 } catch (UncheckedIOException ignored) {
2194 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2195 // ERROR_INVALID_SOCKET.
2196 dup = createInvalidFd();
2197 }
2198 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2199 }
2200
2201 /**
2202 * Ensure that a network route exists to deliver traffic to the specified
2203 * host via the specified network interface. An attempt to add a route that
2204 * already exists is ignored, but treated as successful.
2205 *
2206 * <p>This method requires the caller to hold either the
2207 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2208 * or the ability to modify system settings as determined by
2209 * {@link android.provider.Settings.System#canWrite}.</p>
2210 *
2211 * @param networkType the type of the network over which traffic to the specified
2212 * host is to be routed
2213 * @param hostAddress the IP address of the host to which the route is desired
2214 * @return {@code true} on success, {@code false} on failure
2215 *
2216 * @deprecated Deprecated in favor of the
2217 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2218 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2219 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2220 * throw {@code UnsupportedOperationException} if called.
2221 * @removed
2222 */
2223 @Deprecated
2224 public boolean requestRouteToHost(int networkType, int hostAddress) {
2225 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2226 }
2227
2228 /**
2229 * Ensure that a network route exists to deliver traffic to the specified
2230 * host via the specified network interface. An attempt to add a route that
2231 * already exists is ignored, but treated as successful.
2232 *
2233 * <p>This method requires the caller to hold either the
2234 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2235 * or the ability to modify system settings as determined by
2236 * {@link android.provider.Settings.System#canWrite}.</p>
2237 *
2238 * @param networkType the type of the network over which traffic to the specified
2239 * host is to be routed
2240 * @param hostAddress the IP address of the host to which the route is desired
2241 * @return {@code true} on success, {@code false} on failure
2242 * @hide
2243 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2244 * {@link #bindProcessToNetwork} API.
2245 */
2246 @Deprecated
2247 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002248 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002249 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2250 checkLegacyRoutingApiAccess();
2251 try {
2252 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2253 mContext.getOpPackageName(), getAttributionTag());
2254 } catch (RemoteException e) {
2255 throw e.rethrowFromSystemServer();
2256 }
2257 }
2258
2259 /**
2260 * @return the context's attribution tag
2261 */
2262 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2263 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002264 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002265 }
2266
2267 /**
2268 * Returns the value of the setting for background data usage. If false,
2269 * applications should not use the network if the application is not in the
2270 * foreground. Developers should respect this setting, and check the value
2271 * of this before performing any background data operations.
2272 * <p>
2273 * All applications that have background services that use the network
2274 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2275 * <p>
2276 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2277 * background data depends on several combined factors, and this method will
2278 * always return {@code true}. Instead, when background data is unavailable,
2279 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2280 *
2281 * @return Whether background data usage is allowed.
2282 */
2283 @Deprecated
2284 public boolean getBackgroundDataSetting() {
2285 // assume that background data is allowed; final authority is
2286 // NetworkInfo which may be blocked.
2287 return true;
2288 }
2289
2290 /**
2291 * Sets the value of the setting for background data usage.
2292 *
2293 * @param allowBackgroundData Whether an application should use data while
2294 * it is in the background.
2295 *
2296 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2297 * @see #getBackgroundDataSetting()
2298 * @hide
2299 */
2300 @Deprecated
2301 @UnsupportedAppUsage
2302 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2303 // ignored
2304 }
2305
2306 /**
2307 * @hide
2308 * @deprecated Talk to TelephonyManager directly
2309 */
2310 @Deprecated
2311 @UnsupportedAppUsage
2312 public boolean getMobileDataEnabled() {
2313 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2314 if (tm != null) {
2315 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2316 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2317 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2318 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2319 + " retVal=" + retVal);
2320 return retVal;
2321 }
2322 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2323 return false;
2324 }
2325
2326 /**
2327 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2328 * to find out when the system default network has gone in to a high power state.
2329 */
2330 public interface OnNetworkActiveListener {
2331 /**
2332 * Called on the main thread of the process to report that the current data network
2333 * has become active, and it is now a good time to perform any pending network
2334 * operations. Note that this listener only tells you when the network becomes
2335 * active; if at any other time you want to know whether it is active (and thus okay
2336 * to initiate network traffic), you can retrieve its instantaneous state with
2337 * {@link ConnectivityManager#isDefaultNetworkActive}.
2338 */
2339 void onNetworkActive();
2340 }
2341
Chiachang Wang2de41682021-09-23 10:46:03 +08002342 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002343 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2344 mNetworkActivityListeners = new ArrayMap<>();
2345
2346 /**
2347 * Start listening to reports when the system's default data network is active, meaning it is
2348 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2349 * to determine the current state of the system's default network after registering the
2350 * listener.
2351 * <p>
2352 * If the process default network has been set with
2353 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2354 * reflect the process's default, but the system default.
2355 *
2356 * @param l The listener to be told when the network is active.
2357 */
2358 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002359 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002360 @Override
2361 public void onNetworkActive() throws RemoteException {
2362 l.onNetworkActive();
2363 }
2364 };
2365
Chiachang Wang2de41682021-09-23 10:46:03 +08002366 synchronized (mNetworkActivityListeners) {
2367 try {
2368 mService.registerNetworkActivityListener(rl);
2369 mNetworkActivityListeners.put(l, rl);
2370 } catch (RemoteException e) {
2371 throw e.rethrowFromSystemServer();
2372 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002373 }
2374 }
2375
2376 /**
2377 * Remove network active listener previously registered with
2378 * {@link #addDefaultNetworkActiveListener}.
2379 *
2380 * @param l Previously registered listener.
2381 */
2382 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002383 synchronized (mNetworkActivityListeners) {
2384 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2385 if (rl == null) {
2386 throw new IllegalArgumentException("Listener was not registered.");
2387 }
2388 try {
2389 mService.unregisterNetworkActivityListener(rl);
2390 mNetworkActivityListeners.remove(l);
2391 } catch (RemoteException e) {
2392 throw e.rethrowFromSystemServer();
2393 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002394 }
2395 }
2396
2397 /**
2398 * Return whether the data network is currently active. An active network means that
2399 * it is currently in a high power state for performing data transmission. On some
2400 * types of networks, it may be expensive to move and stay in such a state, so it is
2401 * more power efficient to batch network traffic together when the radio is already in
2402 * this state. This method tells you whether right now is currently a good time to
2403 * initiate network traffic, as the network is already active.
2404 */
2405 public boolean isDefaultNetworkActive() {
2406 try {
lucaslin709eb842021-01-21 02:04:15 +08002407 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002408 } catch (RemoteException e) {
2409 throw e.rethrowFromSystemServer();
2410 }
2411 }
2412
2413 /**
2414 * {@hide}
2415 */
2416 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002417 mContext = Objects.requireNonNull(context, "missing context");
2418 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002419 sInstance = this;
2420 }
2421
2422 /** {@hide} */
2423 @UnsupportedAppUsage
2424 public static ConnectivityManager from(Context context) {
2425 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2426 }
2427
2428 /** @hide */
2429 public NetworkRequest getDefaultRequest() {
2430 try {
2431 // This is not racy as the default request is final in ConnectivityService.
2432 return mService.getDefaultRequest();
2433 } catch (RemoteException e) {
2434 throw e.rethrowFromSystemServer();
2435 }
2436 }
2437
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002438 /**
2439 * Check if the package is a allowed to write settings. This also accounts that such an access
2440 * happened.
2441 *
2442 * @return {@code true} iff the package is allowed to write settings.
2443 */
2444 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2445 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2446 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2447 boolean throwException) {
2448 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002449 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002450 }
2451
2452 /**
2453 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2454 * situations where a Context pointer is unavailable.
2455 * @hide
2456 */
2457 @Deprecated
2458 static ConnectivityManager getInstanceOrNull() {
2459 return sInstance;
2460 }
2461
2462 /**
2463 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2464 * situations where a Context pointer is unavailable.
2465 * @hide
2466 */
2467 @Deprecated
2468 @UnsupportedAppUsage
2469 private static ConnectivityManager getInstance() {
2470 if (getInstanceOrNull() == null) {
2471 throw new IllegalStateException("No ConnectivityManager yet constructed");
2472 }
2473 return getInstanceOrNull();
2474 }
2475
2476 /**
2477 * Get the set of tetherable, available interfaces. This list is limited by
2478 * device configuration and current interface existence.
2479 *
2480 * @return an array of 0 or more Strings of tetherable interface names.
2481 *
2482 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2483 * {@hide}
2484 */
2485 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2486 @UnsupportedAppUsage
2487 @Deprecated
2488 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002489 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002490 }
2491
2492 /**
2493 * Get the set of tethered interfaces.
2494 *
2495 * @return an array of 0 or more String of currently tethered interface names.
2496 *
2497 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2498 * {@hide}
2499 */
2500 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2501 @UnsupportedAppUsage
2502 @Deprecated
2503 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002504 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002505 }
2506
2507 /**
2508 * Get the set of interface names which attempted to tether but
2509 * failed. Re-attempting to tether may cause them to reset to the Tethered
2510 * state. Alternatively, causing the interface to be destroyed and recreated
2511 * may cause them to reset to the available state.
2512 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2513 * information on the cause of the errors.
2514 *
2515 * @return an array of 0 or more String indicating the interface names
2516 * which failed to tether.
2517 *
2518 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2519 * {@hide}
2520 */
2521 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2522 @UnsupportedAppUsage
2523 @Deprecated
2524 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002525 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002526 }
2527
2528 /**
2529 * Get the set of tethered dhcp ranges.
2530 *
2531 * @deprecated This method is not supported.
2532 * TODO: remove this function when all of clients are removed.
2533 * {@hide}
2534 */
2535 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2536 @Deprecated
2537 public String[] getTetheredDhcpRanges() {
2538 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2539 }
2540
2541 /**
2542 * Attempt to tether the named interface. This will setup a dhcp server
2543 * on the interface, forward and NAT IP packets and forward DNS requests
2544 * to the best active upstream network interface. Note that if no upstream
2545 * IP network interface is available, dhcp will still run and traffic will be
2546 * allowed between the tethered devices and this device, though upstream net
2547 * access will of course fail until an upstream network interface becomes
2548 * active.
2549 *
2550 * <p>This method requires the caller to hold either the
2551 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2552 * or the ability to modify system settings as determined by
2553 * {@link android.provider.Settings.System#canWrite}.</p>
2554 *
2555 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2556 * and WifiStateMachine which need direct access. All other clients should use
2557 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2558 * logic.</p>
2559 *
2560 * @param iface the interface name to tether.
2561 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2562 * @deprecated Use {@link TetheringManager#startTethering} instead
2563 *
2564 * {@hide}
2565 */
2566 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2567 @Deprecated
2568 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002569 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002570 }
2571
2572 /**
2573 * Stop tethering the named interface.
2574 *
2575 * <p>This method requires the caller to hold either the
2576 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2577 * or the ability to modify system settings as determined by
2578 * {@link android.provider.Settings.System#canWrite}.</p>
2579 *
2580 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2581 * and WifiStateMachine which need direct access. All other clients should use
2582 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2583 * logic.</p>
2584 *
2585 * @param iface the interface name to untether.
2586 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2587 *
2588 * {@hide}
2589 */
2590 @UnsupportedAppUsage
2591 @Deprecated
2592 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002593 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002594 }
2595
2596 /**
2597 * Check if the device allows for tethering. It may be disabled via
2598 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2599 * due to device configuration.
2600 *
2601 * <p>If this app does not have permission to use this API, it will always
2602 * return false rather than throw an exception.</p>
2603 *
2604 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2605 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2606 *
2607 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2608 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2609 *
2610 * @return a boolean - {@code true} indicating Tethering is supported.
2611 *
2612 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2613 * {@hide}
2614 */
2615 @SystemApi
2616 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2617 android.Manifest.permission.WRITE_SETTINGS})
2618 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002619 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002620 }
2621
2622 /**
2623 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2624 *
2625 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2626 * @hide
2627 */
2628 @SystemApi
2629 @Deprecated
2630 public static abstract class OnStartTetheringCallback {
2631 /**
2632 * Called when tethering has been successfully started.
2633 */
2634 public void onTetheringStarted() {}
2635
2636 /**
2637 * Called when starting tethering failed.
2638 */
2639 public void onTetheringFailed() {}
2640 }
2641
2642 /**
2643 * Convenient overload for
2644 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2645 * handler to run on the current thread's {@link Looper}.
2646 *
2647 * @deprecated Use {@link TetheringManager#startTethering} instead.
2648 * @hide
2649 */
2650 @SystemApi
2651 @Deprecated
2652 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2653 public void startTethering(int type, boolean showProvisioningUi,
2654 final OnStartTetheringCallback callback) {
2655 startTethering(type, showProvisioningUi, callback, null);
2656 }
2657
2658 /**
2659 * Runs tether provisioning for the given type if needed and then starts tethering if
2660 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2661 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2662 * schedules tether provisioning re-checks if appropriate.
2663 *
2664 * @param type The type of tethering to start. Must be one of
2665 * {@link ConnectivityManager.TETHERING_WIFI},
2666 * {@link ConnectivityManager.TETHERING_USB}, or
2667 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2668 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2669 * is one. This should be true the first time this function is called and also any time
2670 * the user can see this UI. It gives users information from their carrier about the
2671 * check failing and how they can sign up for tethering if possible.
2672 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2673 * of the result of trying to tether.
2674 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2675 *
2676 * @deprecated Use {@link TetheringManager#startTethering} instead.
2677 * @hide
2678 */
2679 @SystemApi
2680 @Deprecated
2681 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2682 public void startTethering(int type, boolean showProvisioningUi,
2683 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002684 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002685
2686 final Executor executor = new Executor() {
2687 @Override
2688 public void execute(Runnable command) {
2689 if (handler == null) {
2690 command.run();
2691 } else {
2692 handler.post(command);
2693 }
2694 }
2695 };
2696
2697 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2698 @Override
2699 public void onTetheringStarted() {
2700 callback.onTetheringStarted();
2701 }
2702
2703 @Override
2704 public void onTetheringFailed(final int error) {
2705 callback.onTetheringFailed();
2706 }
2707 };
2708
2709 final TetheringRequest request = new TetheringRequest.Builder(type)
2710 .setShouldShowEntitlementUi(showProvisioningUi).build();
2711
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002712 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002713 }
2714
2715 /**
2716 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2717 * applicable.
2718 *
2719 * @param type The type of tethering to stop. Must be one of
2720 * {@link ConnectivityManager.TETHERING_WIFI},
2721 * {@link ConnectivityManager.TETHERING_USB}, or
2722 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2723 *
2724 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2725 * @hide
2726 */
2727 @SystemApi
2728 @Deprecated
2729 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2730 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002731 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002732 }
2733
2734 /**
2735 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2736 * upstream status.
2737 *
2738 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2739 * @hide
2740 */
2741 @SystemApi
2742 @Deprecated
2743 public abstract static class OnTetheringEventCallback {
2744
2745 /**
2746 * Called when tethering upstream changed. This can be called multiple times and can be
2747 * called any time.
2748 *
2749 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2750 * have any upstream.
2751 */
2752 public void onUpstreamChanged(@Nullable Network network) {}
2753 }
2754
2755 @GuardedBy("mTetheringEventCallbacks")
2756 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2757 mTetheringEventCallbacks = new ArrayMap<>();
2758
2759 /**
2760 * Start listening to tethering change events. Any new added callback will receive the last
2761 * tethering status right away. If callback is registered when tethering has no upstream or
2762 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2763 * with a null argument. The same callback object cannot be registered twice.
2764 *
2765 * @param executor the executor on which callback will be invoked.
2766 * @param callback the callback to be called when tethering has change events.
2767 *
2768 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2769 * @hide
2770 */
2771 @SystemApi
2772 @Deprecated
2773 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2774 public void registerTetheringEventCallback(
2775 @NonNull @CallbackExecutor Executor executor,
2776 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002777 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002778
2779 final TetheringEventCallback tetherCallback =
2780 new TetheringEventCallback() {
2781 @Override
2782 public void onUpstreamChanged(@Nullable Network network) {
2783 callback.onUpstreamChanged(network);
2784 }
2785 };
2786
2787 synchronized (mTetheringEventCallbacks) {
2788 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002789 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002790 }
2791 }
2792
2793 /**
2794 * Remove tethering event callback previously registered with
2795 * {@link #registerTetheringEventCallback}.
2796 *
2797 * @param callback previously registered callback.
2798 *
2799 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
2800 * @hide
2801 */
2802 @SystemApi
2803 @Deprecated
2804 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2805 public void unregisterTetheringEventCallback(
2806 @NonNull final OnTetheringEventCallback callback) {
2807 Objects.requireNonNull(callback, "The callback must be non-null");
2808 synchronized (mTetheringEventCallbacks) {
2809 final TetheringEventCallback tetherCallback =
2810 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002811 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002812 }
2813 }
2814
2815
2816 /**
2817 * Get the list of regular expressions that define any tetherable
2818 * USB network interfaces. If USB tethering is not supported by the
2819 * device, this list should be empty.
2820 *
2821 * @return an array of 0 or more regular expression Strings defining
2822 * what interfaces are considered tetherable usb interfaces.
2823 *
2824 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2825 * {@hide}
2826 */
2827 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2828 @UnsupportedAppUsage
2829 @Deprecated
2830 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002831 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002832 }
2833
2834 /**
2835 * Get the list of regular expressions that define any tetherable
2836 * Wifi network interfaces. If Wifi tethering is not supported by the
2837 * device, this list should be empty.
2838 *
2839 * @return an array of 0 or more regular expression Strings defining
2840 * what interfaces are considered tetherable wifi interfaces.
2841 *
2842 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2843 * {@hide}
2844 */
2845 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2846 @UnsupportedAppUsage
2847 @Deprecated
2848 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002849 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002850 }
2851
2852 /**
2853 * Get the list of regular expressions that define any tetherable
2854 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2855 * device, this list should be empty.
2856 *
2857 * @return an array of 0 or more regular expression Strings defining
2858 * what interfaces are considered tetherable bluetooth interfaces.
2859 *
2860 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2861 *TetheringManager.TetheringInterfaceRegexps)} instead.
2862 * {@hide}
2863 */
2864 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2865 @UnsupportedAppUsage
2866 @Deprecated
2867 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002868 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002869 }
2870
2871 /**
2872 * Attempt to both alter the mode of USB and Tethering of USB. A
2873 * utility method to deal with some of the complexity of USB - will
2874 * attempt to switch to Rndis and subsequently tether the resulting
2875 * interface on {@code true} or turn off tethering and switch off
2876 * Rndis on {@code false}.
2877 *
2878 * <p>This method requires the caller to hold either the
2879 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2880 * or the ability to modify system settings as determined by
2881 * {@link android.provider.Settings.System#canWrite}.</p>
2882 *
2883 * @param enable a boolean - {@code true} to enable tethering
2884 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2885 * @deprecated Use {@link TetheringManager#startTethering} instead
2886 *
2887 * {@hide}
2888 */
2889 @UnsupportedAppUsage
2890 @Deprecated
2891 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002892 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002893 }
2894
2895 /**
2896 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2897 * {@hide}
2898 */
2899 @SystemApi
2900 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002901 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002902 /**
2903 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2904 * {@hide}
2905 */
2906 @Deprecated
2907 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2908 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2909 /**
2910 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2911 * {@hide}
2912 */
2913 @Deprecated
2914 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2915 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2916 /**
2917 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2918 * {@hide}
2919 */
2920 @Deprecated
2921 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2922 /**
2923 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2924 * {@hide}
2925 */
2926 @Deprecated
2927 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2928 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2929 /**
2930 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
2931 * {@hide}
2932 */
2933 @Deprecated
2934 public static final int TETHER_ERROR_MASTER_ERROR =
2935 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
2936 /**
2937 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2938 * {@hide}
2939 */
2940 @Deprecated
2941 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2942 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2943 /**
2944 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2945 * {@hide}
2946 */
2947 @Deprecated
2948 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2949 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2950 /**
2951 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
2952 * {@hide}
2953 */
2954 @Deprecated
2955 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
2956 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
2957 /**
2958 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
2959 * {@hide}
2960 */
2961 @Deprecated
2962 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
2963 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
2964 /**
2965 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2966 * {@hide}
2967 */
2968 @Deprecated
2969 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2970 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2971 /**
2972 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
2973 * {@hide}
2974 */
2975 @SystemApi
2976 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002977 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002978 /**
2979 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2980 * {@hide}
2981 */
2982 @Deprecated
2983 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2984 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2985 /**
2986 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2987 * {@hide}
2988 */
2989 @SystemApi
2990 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002991 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002992
2993 /**
2994 * Get a more detailed error code after a Tethering or Untethering
2995 * request asynchronously failed.
2996 *
2997 * @param iface The name of the interface of interest
2998 * @return error The error code of the last error tethering or untethering the named
2999 * interface
3000 *
3001 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3002 * {@hide}
3003 */
3004 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3005 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3006 @Deprecated
3007 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003008 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003009 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3010 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3011 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3012 // instead.
3013 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3014 }
3015 return error;
3016 }
3017
3018 /** @hide */
3019 @Retention(RetentionPolicy.SOURCE)
3020 @IntDef(value = {
3021 TETHER_ERROR_NO_ERROR,
3022 TETHER_ERROR_PROVISION_FAILED,
3023 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3024 })
3025 public @interface EntitlementResultCode {
3026 }
3027
3028 /**
3029 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3030 * entitlement succeeded.
3031 *
3032 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3033 * @hide
3034 */
3035 @SystemApi
3036 @Deprecated
3037 public interface OnTetheringEntitlementResultListener {
3038 /**
3039 * Called to notify entitlement result.
3040 *
3041 * @param resultCode an int value of entitlement result. It may be one of
3042 * {@link #TETHER_ERROR_NO_ERROR},
3043 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3044 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3045 */
3046 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3047 }
3048
3049 /**
3050 * Get the last value of the entitlement check on this downstream. If the cached value is
3051 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3052 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3053 * guaranteed that the UI-based entitlement check will complete in any specific time period
3054 * and may in fact never complete. Any successful entitlement check the platform performs for
3055 * any reason will update the cached value.
3056 *
3057 * @param type the downstream type of tethering. Must be one of
3058 * {@link #TETHERING_WIFI},
3059 * {@link #TETHERING_USB}, or
3060 * {@link #TETHERING_BLUETOOTH}.
3061 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3062 * @param executor the executor on which callback will be invoked.
3063 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3064 * notify the caller of the result of entitlement check. The listener may be called zero
3065 * or one time.
3066 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3067 * {@hide}
3068 */
3069 @SystemApi
3070 @Deprecated
3071 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3072 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3073 @NonNull @CallbackExecutor Executor executor,
3074 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003075 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003076 ResultReceiver wrappedListener = new ResultReceiver(null) {
3077 @Override
3078 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003079 final long token = Binder.clearCallingIdentity();
3080 try {
3081 executor.execute(() -> {
3082 listener.onTetheringEntitlementResult(resultCode);
3083 });
3084 } finally {
3085 Binder.restoreCallingIdentity(token);
3086 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003087 }
3088 };
3089
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003090 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003091 showEntitlementUi);
3092 }
3093
3094 /**
3095 * Report network connectivity status. This is currently used only
3096 * to alter status bar UI.
3097 * <p>This method requires the caller to hold the permission
3098 * {@link android.Manifest.permission#STATUS_BAR}.
3099 *
3100 * @param networkType The type of network you want to report on
3101 * @param percentage The quality of the connection 0 is bad, 100 is good
3102 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3103 * {@hide}
3104 */
3105 public void reportInetCondition(int networkType, int percentage) {
3106 printStackTrace();
3107 try {
3108 mService.reportInetCondition(networkType, percentage);
3109 } catch (RemoteException e) {
3110 throw e.rethrowFromSystemServer();
3111 }
3112 }
3113
3114 /**
3115 * Report a problem network to the framework. This provides a hint to the system
3116 * that there might be connectivity problems on this network and may cause
3117 * the framework to re-evaluate network connectivity and/or switch to another
3118 * network.
3119 *
3120 * @param network The {@link Network} the application was attempting to use
3121 * or {@code null} to indicate the current default network.
3122 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3123 * working and non-working connectivity.
3124 */
3125 @Deprecated
3126 public void reportBadNetwork(@Nullable Network network) {
3127 printStackTrace();
3128 try {
3129 // One of these will be ignored because it matches system's current state.
3130 // The other will trigger the necessary reevaluation.
3131 mService.reportNetworkConnectivity(network, true);
3132 mService.reportNetworkConnectivity(network, false);
3133 } catch (RemoteException e) {
3134 throw e.rethrowFromSystemServer();
3135 }
3136 }
3137
3138 /**
3139 * Report to the framework whether a network has working connectivity.
3140 * This provides a hint to the system that a particular network is providing
3141 * working connectivity or not. In response the framework may re-evaluate
3142 * the network's connectivity and might take further action thereafter.
3143 *
3144 * @param network The {@link Network} the application was attempting to use
3145 * or {@code null} to indicate the current default network.
3146 * @param hasConnectivity {@code true} if the application was able to successfully access the
3147 * Internet using {@code network} or {@code false} if not.
3148 */
3149 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3150 printStackTrace();
3151 try {
3152 mService.reportNetworkConnectivity(network, hasConnectivity);
3153 } catch (RemoteException e) {
3154 throw e.rethrowFromSystemServer();
3155 }
3156 }
3157
3158 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003159 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003160 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003161 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3162 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3163 * accessing any network, regardless of what the settings for that network are.
3164 *
3165 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3166 * proxy is likely to break networking on multiple networks. This method is only meant
3167 * for device policy clients looking to do general internal filtering or similar use cases.
3168 *
3169 * {@see #getGlobalProxy}
3170 * {@see LinkProperties#getHttpProxy}
3171 *
3172 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3173 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003174 * @hide
3175 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003176 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003177 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003178 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003179 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003180 try {
3181 mService.setGlobalProxy(p);
3182 } catch (RemoteException e) {
3183 throw e.rethrowFromSystemServer();
3184 }
3185 }
3186
3187 /**
3188 * Retrieve any network-independent global HTTP proxy.
3189 *
3190 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3191 * if no global HTTP proxy is set.
3192 * @hide
3193 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003194 @SystemApi(client = MODULE_LIBRARIES)
3195 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003196 public ProxyInfo getGlobalProxy() {
3197 try {
3198 return mService.getGlobalProxy();
3199 } catch (RemoteException e) {
3200 throw e.rethrowFromSystemServer();
3201 }
3202 }
3203
3204 /**
3205 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3206 * network-specific HTTP proxy. If {@code network} is null, the
3207 * network-specific proxy returned is the proxy of the default active
3208 * network.
3209 *
3210 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3211 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3212 * or when {@code network} is {@code null},
3213 * the {@code ProxyInfo} for the default active network. Returns
3214 * {@code null} when no proxy applies or the caller doesn't have
3215 * permission to use {@code network}.
3216 * @hide
3217 */
3218 public ProxyInfo getProxyForNetwork(Network network) {
3219 try {
3220 return mService.getProxyForNetwork(network);
3221 } catch (RemoteException e) {
3222 throw e.rethrowFromSystemServer();
3223 }
3224 }
3225
3226 /**
3227 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3228 * otherwise if this process is bound to a {@link Network} using
3229 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3230 * the default network's proxy is returned.
3231 *
3232 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3233 * HTTP proxy is active.
3234 */
3235 @Nullable
3236 public ProxyInfo getDefaultProxy() {
3237 return getProxyForNetwork(getBoundNetworkForProcess());
3238 }
3239
3240 /**
3241 * Returns true if the hardware supports the given network type
3242 * else it returns false. This doesn't indicate we have coverage
3243 * or are authorized onto a network, just whether or not the
3244 * hardware supports it. For example a GSM phone without a SIM
3245 * should still return {@code true} for mobile data, but a wifi only
3246 * tablet would return {@code false}.
3247 *
3248 * @param networkType The network type we'd like to check
3249 * @return {@code true} if supported, else {@code false}
3250 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3251 * @hide
3252 */
3253 @Deprecated
3254 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3255 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3256 public boolean isNetworkSupported(int networkType) {
3257 try {
3258 return mService.isNetworkSupported(networkType);
3259 } catch (RemoteException e) {
3260 throw e.rethrowFromSystemServer();
3261 }
3262 }
3263
3264 /**
3265 * Returns if the currently active data network is metered. A network is
3266 * classified as metered when the user is sensitive to heavy data usage on
3267 * that connection due to monetary costs, data limitations or
3268 * battery/performance issues. You should check this before doing large
3269 * data transfers, and warn the user or delay the operation until another
3270 * network is available.
3271 *
3272 * @return {@code true} if large transfers should be avoided, otherwise
3273 * {@code false}.
3274 */
3275 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3276 public boolean isActiveNetworkMetered() {
3277 try {
3278 return mService.isActiveNetworkMetered();
3279 } catch (RemoteException e) {
3280 throw e.rethrowFromSystemServer();
3281 }
3282 }
3283
3284 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003285 * Set sign in error notification to visible or invisible
3286 *
3287 * @hide
3288 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3289 */
3290 @Deprecated
3291 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3292 String action) {
3293 try {
3294 mService.setProvisioningNotificationVisible(visible, networkType, action);
3295 } catch (RemoteException e) {
3296 throw e.rethrowFromSystemServer();
3297 }
3298 }
3299
3300 /**
3301 * Set the value for enabling/disabling airplane mode
3302 *
3303 * @param enable whether to enable airplane mode or not
3304 *
3305 * @hide
3306 */
3307 @RequiresPermission(anyOf = {
3308 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3309 android.Manifest.permission.NETWORK_SETTINGS,
3310 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3311 android.Manifest.permission.NETWORK_STACK})
3312 @SystemApi
3313 public void setAirplaneMode(boolean enable) {
3314 try {
3315 mService.setAirplaneMode(enable);
3316 } catch (RemoteException e) {
3317 throw e.rethrowFromSystemServer();
3318 }
3319 }
3320
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003321 /**
3322 * Registers the specified {@link NetworkProvider}.
3323 * Each listener must only be registered once. The listener can be unregistered with
3324 * {@link #unregisterNetworkProvider}.
3325 *
3326 * @param provider the provider to register
3327 * @return the ID of the provider. This ID must be used by the provider when registering
3328 * {@link android.net.NetworkAgent}s.
3329 * @hide
3330 */
3331 @SystemApi
3332 @RequiresPermission(anyOf = {
3333 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3334 android.Manifest.permission.NETWORK_FACTORY})
3335 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3336 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3337 throw new IllegalStateException("NetworkProviders can only be registered once");
3338 }
3339
3340 try {
3341 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3342 provider.getName());
3343 provider.setProviderId(providerId);
3344 } catch (RemoteException e) {
3345 throw e.rethrowFromSystemServer();
3346 }
3347 return provider.getProviderId();
3348 }
3349
3350 /**
3351 * Unregisters the specified NetworkProvider.
3352 *
3353 * @param provider the provider to unregister
3354 * @hide
3355 */
3356 @SystemApi
3357 @RequiresPermission(anyOf = {
3358 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3359 android.Manifest.permission.NETWORK_FACTORY})
3360 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3361 try {
3362 mService.unregisterNetworkProvider(provider.getMessenger());
3363 } catch (RemoteException e) {
3364 throw e.rethrowFromSystemServer();
3365 }
3366 provider.setProviderId(NetworkProvider.ID_NONE);
3367 }
3368
Chalard Jeand1b498b2021-01-05 08:40:09 +09003369 /**
3370 * Register or update a network offer with ConnectivityService.
3371 *
3372 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003373 * them to networking requests made by apps or the system. A callback identifies an offer
3374 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3375 * score and the capabilities of the network it might be able to bring up ; these act as
3376 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003377 * provider.
3378 *
3379 * The provider is under no obligation to be able to bring up the network it offers at any
3380 * given time. Instead, this mechanism is meant to limit requests received by providers
3381 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3382 * the quality of the network satisfying a given request to their own offer.
3383 *
3384 * An offer can be updated by calling this again with the same callback object. This is
3385 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3386 * provider with the changes caused by the changes in the offer.
3387 *
3388 * @param provider The provider making this offer.
3389 * @param score The prospective score of the network.
3390 * @param caps The prospective capabilities of the network.
3391 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003392 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003393 */
3394 @RequiresPermission(anyOf = {
3395 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3396 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003397 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003398 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3399 @NonNull final INetworkOfferCallback callback) {
3400 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003401 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003402 Objects.requireNonNull(score, "null score"),
3403 Objects.requireNonNull(caps, "null caps"),
3404 Objects.requireNonNull(callback, "null callback"));
3405 } catch (RemoteException e) {
3406 throw e.rethrowFromSystemServer();
3407 }
3408 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003409
Chalard Jeand1b498b2021-01-05 08:40:09 +09003410 /**
3411 * Withdraw a network offer made with {@link #offerNetwork}.
3412 *
3413 * @param callback The callback passed at registration time. This must be the same object
3414 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003415 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003416 */
3417 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3418 try {
3419 mService.unofferNetwork(Objects.requireNonNull(callback));
3420 } catch (RemoteException e) {
3421 throw e.rethrowFromSystemServer();
3422 }
3423 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003424 /** @hide exposed via the NetworkProvider class. */
3425 @RequiresPermission(anyOf = {
3426 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3427 android.Manifest.permission.NETWORK_FACTORY})
3428 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3429 try {
3430 mService.declareNetworkRequestUnfulfillable(request);
3431 } catch (RemoteException e) {
3432 throw e.rethrowFromSystemServer();
3433 }
3434 }
3435
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003436 /**
3437 * @hide
3438 * Register a NetworkAgent with ConnectivityService.
3439 * @return Network corresponding to NetworkAgent.
3440 */
3441 @RequiresPermission(anyOf = {
3442 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3443 android.Manifest.permission.NETWORK_FACTORY})
3444 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003445 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3446 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003447 try {
3448 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3449 } catch (RemoteException e) {
3450 throw e.rethrowFromSystemServer();
3451 }
3452 }
3453
3454 /**
3455 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3456 * changes. Should be extended by applications wanting notifications.
3457 *
3458 * A {@code NetworkCallback} is registered by calling
3459 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3460 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3461 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3462 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3463 * A {@code NetworkCallback} should be registered at most once at any time.
3464 * A {@code NetworkCallback} that has been unregistered can be registered again.
3465 */
3466 public static class NetworkCallback {
3467 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003468 * No flags associated with this callback.
3469 * @hide
3470 */
3471 public static final int FLAG_NONE = 0;
3472 /**
3473 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3474 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3475 * <p>
3476 * These include:
3477 * <li> Some transport info instances (retrieved via
3478 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3479 * contain location sensitive information.
3480 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003481 * sensitive for wifi suggestor apps (i.e using
3482 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003483 * </p>
3484 * <p>
3485 * Note:
3486 * <li> Retrieving this location sensitive information (subject to app's location
3487 * permissions) will be noted by system. </li>
3488 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3489 * not include location sensitive info.
3490 * </p>
3491 */
Roshan Pius189d0092021-03-11 21:16:44 -08003492 // Note: Some existing fields which are location sensitive may still be included without
3493 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003494 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3495
3496 /** @hide */
3497 @Retention(RetentionPolicy.SOURCE)
3498 @IntDef(flag = true, prefix = "FLAG_", value = {
3499 FLAG_NONE,
3500 FLAG_INCLUDE_LOCATION_INFO
3501 })
3502 public @interface Flag { }
3503
3504 /**
3505 * All the valid flags for error checking.
3506 */
3507 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3508
3509 public NetworkCallback() {
3510 this(FLAG_NONE);
3511 }
3512
3513 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003514 if ((flags & VALID_FLAGS) != flags) {
3515 throw new IllegalArgumentException("Invalid flags");
3516 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003517 mFlags = flags;
3518 }
3519
3520 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003521 * Called when the framework connects to a new network to evaluate whether it satisfies this
3522 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3523 * callback. There is no guarantee that this new network will satisfy any requests, or that
3524 * the network will stay connected for longer than the time necessary to evaluate it.
3525 * <p>
3526 * Most applications <b>should not</b> act on this callback, and should instead use
3527 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3528 * the framework in properly evaluating the network &mdash; for example, an application that
3529 * can automatically log in to a captive portal without user intervention.
3530 *
3531 * @param network The {@link Network} of the network that is being evaluated.
3532 *
3533 * @hide
3534 */
3535 public void onPreCheck(@NonNull Network network) {}
3536
3537 /**
3538 * Called when the framework connects and has declared a new network ready for use.
3539 * This callback may be called more than once if the {@link Network} that is
3540 * satisfying the request changes.
3541 *
3542 * @param network The {@link Network} of the satisfying network.
3543 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3544 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3545 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3546 * @hide
3547 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003548 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003549 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003550 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003551 // Internally only this method is called when a new network is available, and
3552 // it calls the callback in the same way and order that older versions used
3553 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003554 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3555 onBlockedStatusChanged(network, blocked);
3556 }
3557
3558 /**
3559 * Legacy variant of onAvailable that takes a boolean blocked reason.
3560 *
3561 * This method has never been public API, but it's not final, so there may be apps that
3562 * implemented it and rely on it being called. Do our best not to break them.
3563 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3564 * this method is called. There does not seem to be a way to avoid this.
3565 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3566 *
3567 * @hide
3568 */
3569 public void onAvailable(@NonNull Network network,
3570 @NonNull NetworkCapabilities networkCapabilities,
3571 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003572 onAvailable(network);
3573 if (!networkCapabilities.hasCapability(
3574 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3575 onNetworkSuspended(network);
3576 }
3577 onCapabilitiesChanged(network, networkCapabilities);
3578 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003579 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003580 }
3581
3582 /**
3583 * Called when the framework connects and has declared a new network ready for use.
3584 *
3585 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3586 * be available at the same time, and onAvailable will be called for each of these as they
3587 * appear.
3588 *
3589 * <p>For callbacks registered with {@link #requestNetwork} and
3590 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3591 * is the new best network for this request and is now tracked by this callback ; this
3592 * callback will no longer receive method calls about other networks that may have been
3593 * passed to this method previously. The previously-best network may have disconnected, or
3594 * it may still be around and the newly-best network may simply be better.
3595 *
3596 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3597 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3598 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3599 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3600 *
3601 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3602 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3603 * this callback as this is prone to race conditions (there is no guarantee the objects
3604 * returned by these methods will be current). Instead, wait for a call to
3605 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3606 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3607 * to be well-ordered with respect to other callbacks.
3608 *
3609 * @param network The {@link Network} of the satisfying network.
3610 */
3611 public void onAvailable(@NonNull Network network) {}
3612
3613 /**
3614 * Called when the network is about to be lost, typically because there are no outstanding
3615 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3616 * with the new replacement network for graceful handover. This method is not guaranteed
3617 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3618 * network is suddenly disconnected.
3619 *
3620 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3621 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3622 * this callback as this is prone to race conditions ; calling these methods while in a
3623 * callback may return an outdated or even a null object.
3624 *
3625 * @param network The {@link Network} that is about to be lost.
3626 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3627 * connected for graceful handover; note that the network may still
3628 * suffer a hard loss at any time.
3629 */
3630 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3631
3632 /**
3633 * Called when a network disconnects or otherwise no longer satisfies this request or
3634 * callback.
3635 *
3636 * <p>If the callback was registered with requestNetwork() or
3637 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3638 * returned by onAvailable() when that network is lost and no other network satisfies
3639 * the criteria of the request.
3640 *
3641 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3642 * each network which no longer satisfies the criteria of the callback.
3643 *
3644 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3645 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3646 * this callback as this is prone to race conditions ; calling these methods while in a
3647 * callback may return an outdated or even a null object.
3648 *
3649 * @param network The {@link Network} lost.
3650 */
3651 public void onLost(@NonNull Network network) {}
3652
3653 /**
3654 * Called if no network is found within the timeout time specified in
3655 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3656 * requested network request cannot be fulfilled (whether or not a timeout was
3657 * specified). When this callback is invoked the associated
3658 * {@link NetworkRequest} will have already been removed and released, as if
3659 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3660 */
3661 public void onUnavailable() {}
3662
3663 /**
3664 * Called when the network corresponding to this request changes capabilities but still
3665 * satisfies the requested criteria.
3666 *
3667 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3668 * to be called immediately after {@link #onAvailable}.
3669 *
3670 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3671 * ConnectivityManager methods in this callback as this is prone to race conditions :
3672 * calling these methods while in a callback may return an outdated or even a null object.
3673 *
3674 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003675 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003676 * network.
3677 */
3678 public void onCapabilitiesChanged(@NonNull Network network,
3679 @NonNull NetworkCapabilities networkCapabilities) {}
3680
3681 /**
3682 * Called when the network corresponding to this request changes {@link LinkProperties}.
3683 *
3684 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3685 * to be called immediately after {@link #onAvailable}.
3686 *
3687 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3688 * ConnectivityManager methods in this callback as this is prone to race conditions :
3689 * calling these methods while in a callback may return an outdated or even a null object.
3690 *
3691 * @param network The {@link Network} whose link properties have changed.
3692 * @param linkProperties The new {@link LinkProperties} for this network.
3693 */
3694 public void onLinkPropertiesChanged(@NonNull Network network,
3695 @NonNull LinkProperties linkProperties) {}
3696
3697 /**
3698 * Called when the network the framework connected to for this request suspends data
3699 * transmission temporarily.
3700 *
3701 * <p>This generally means that while the TCP connections are still live temporarily
3702 * network data fails to transfer. To give a specific example, this is used on cellular
3703 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3704 * means read operations on sockets on this network will block once the buffers are
3705 * drained, and write operations will block once the buffers are full.
3706 *
3707 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3708 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3709 * this callback as this is prone to race conditions (there is no guarantee the objects
3710 * returned by these methods will be current).
3711 *
3712 * @hide
3713 */
3714 public void onNetworkSuspended(@NonNull Network network) {}
3715
3716 /**
3717 * Called when the network the framework connected to for this request
3718 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3719 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3720
3721 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3722 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3723 * this callback as this is prone to race conditions : calling these methods while in a
3724 * callback may return an outdated or even a null object.
3725 *
3726 * @hide
3727 */
3728 public void onNetworkResumed(@NonNull Network network) {}
3729
3730 /**
3731 * Called when access to the specified network is blocked or unblocked.
3732 *
3733 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3734 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3735 * this callback as this is prone to race conditions : calling these methods while in a
3736 * callback may return an outdated or even a null object.
3737 *
3738 * @param network The {@link Network} whose blocked status has changed.
3739 * @param blocked The blocked status of this {@link Network}.
3740 */
3741 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3742
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003743 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09003744 * Called when access to the specified network is blocked or unblocked, or the reason for
3745 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003746 *
3747 * If a NetworkCallback object implements this method,
3748 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3749 *
3750 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3751 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3752 * this callback as this is prone to race conditions : calling these methods while in a
3753 * callback may return an outdated or even a null object.
3754 *
3755 * @param network The {@link Network} whose blocked status has changed.
3756 * @param blocked The blocked status of this {@link Network}.
3757 * @hide
3758 */
3759 @SystemApi(client = MODULE_LIBRARIES)
3760 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3761 onBlockedStatusChanged(network, blocked != 0);
3762 }
3763
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003764 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08003765 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003766 }
3767
3768 /**
3769 * Constant error codes used by ConnectivityService to communicate about failures and errors
3770 * across a Binder boundary.
3771 * @hide
3772 */
3773 public interface Errors {
3774 int TOO_MANY_REQUESTS = 1;
3775 }
3776
3777 /** @hide */
3778 public static class TooManyRequestsException extends RuntimeException {}
3779
3780 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3781 switch (e.errorCode) {
3782 case Errors.TOO_MANY_REQUESTS:
3783 return new TooManyRequestsException();
3784 default:
3785 Log.w(TAG, "Unknown service error code " + e.errorCode);
3786 return new RuntimeException(e);
3787 }
3788 }
3789
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003790 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003791 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003792 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003793 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003794 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003795 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003796 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003797 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003798 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003799 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003800 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003801 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003802 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003803 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003804 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003805 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003806 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003807 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003808 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003809 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003810 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003811 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003812
3813 /** @hide */
3814 public static String getCallbackName(int whichCallback) {
3815 switch (whichCallback) {
3816 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3817 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3818 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3819 case CALLBACK_LOST: return "CALLBACK_LOST";
3820 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3821 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3822 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
3823 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3824 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3825 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
3826 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
3827 default:
3828 return Integer.toString(whichCallback);
3829 }
3830 }
3831
3832 private class CallbackHandler extends Handler {
3833 private static final String TAG = "ConnectivityManager.CallbackHandler";
3834 private static final boolean DBG = false;
3835
3836 CallbackHandler(Looper looper) {
3837 super(looper);
3838 }
3839
3840 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003841 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003842 }
3843
3844 @Override
3845 public void handleMessage(Message message) {
3846 if (message.what == EXPIRE_LEGACY_REQUEST) {
3847 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3848 return;
3849 }
3850
3851 final NetworkRequest request = getObject(message, NetworkRequest.class);
3852 final Network network = getObject(message, Network.class);
3853 final NetworkCallback callback;
3854 synchronized (sCallbacks) {
3855 callback = sCallbacks.get(request);
3856 if (callback == null) {
3857 Log.w(TAG,
3858 "callback not found for " + getCallbackName(message.what) + " message");
3859 return;
3860 }
3861 if (message.what == CALLBACK_UNAVAIL) {
3862 sCallbacks.remove(request);
3863 callback.networkRequest = ALREADY_UNREGISTERED;
3864 }
3865 }
3866 if (DBG) {
3867 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
3868 }
3869
3870 switch (message.what) {
3871 case CALLBACK_PRECHECK: {
3872 callback.onPreCheck(network);
3873 break;
3874 }
3875 case CALLBACK_AVAILABLE: {
3876 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3877 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003878 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003879 break;
3880 }
3881 case CALLBACK_LOSING: {
3882 callback.onLosing(network, message.arg1);
3883 break;
3884 }
3885 case CALLBACK_LOST: {
3886 callback.onLost(network);
3887 break;
3888 }
3889 case CALLBACK_UNAVAIL: {
3890 callback.onUnavailable();
3891 break;
3892 }
3893 case CALLBACK_CAP_CHANGED: {
3894 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3895 callback.onCapabilitiesChanged(network, cap);
3896 break;
3897 }
3898 case CALLBACK_IP_CHANGED: {
3899 LinkProperties lp = getObject(message, LinkProperties.class);
3900 callback.onLinkPropertiesChanged(network, lp);
3901 break;
3902 }
3903 case CALLBACK_SUSPENDED: {
3904 callback.onNetworkSuspended(network);
3905 break;
3906 }
3907 case CALLBACK_RESUMED: {
3908 callback.onNetworkResumed(network);
3909 break;
3910 }
3911 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003912 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003913 }
3914 }
3915 }
3916
3917 private <T> T getObject(Message msg, Class<T> c) {
3918 return (T) msg.getData().getParcelable(c.getSimpleName());
3919 }
3920 }
3921
3922 private CallbackHandler getDefaultHandler() {
3923 synchronized (sCallbacks) {
3924 if (sCallbackHandler == null) {
3925 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
3926 }
3927 return sCallbackHandler;
3928 }
3929 }
3930
3931 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3932 private static CallbackHandler sCallbackHandler;
3933
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003934 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3935 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3936 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003937 printStackTrace();
3938 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003939 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3940 throw new IllegalArgumentException("null NetworkCapabilities");
3941 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003942 final NetworkRequest request;
3943 final String callingPackageName = mContext.getOpPackageName();
3944 try {
3945 synchronized(sCallbacks) {
3946 if (callback.networkRequest != null
3947 && callback.networkRequest != ALREADY_UNREGISTERED) {
3948 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3949 // and requests (http://b/20701525).
3950 Log.e(TAG, "NetworkCallback was already registered");
3951 }
3952 Messenger messenger = new Messenger(handler);
3953 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08003954 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003955 if (reqType == LISTEN) {
3956 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08003957 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08003958 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003959 } else {
3960 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003961 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3962 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003963 }
3964 if (request != null) {
3965 sCallbacks.put(request, callback);
3966 }
3967 callback.networkRequest = request;
3968 }
3969 } catch (RemoteException e) {
3970 throw e.rethrowFromSystemServer();
3971 } catch (ServiceSpecificException e) {
3972 throw convertServiceException(e);
3973 }
3974 return request;
3975 }
3976
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003977 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3978 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3979 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3980 legacyType, handler);
3981 }
3982
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003983 /**
3984 * Helper function to request a network with a particular legacy type.
3985 *
3986 * This API is only for use in internal system code that requests networks with legacy type and
3987 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
3988 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
3989 *
3990 * @param request {@link NetworkRequest} describing this request.
3991 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3992 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3993 * be a positive value (i.e. >0).
3994 * @param legacyType to specify the network type(#TYPE_*).
3995 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3996 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3997 * the callback must not be shared - it uniquely specifies this request.
3998 *
3999 * @hide
4000 */
4001 @SystemApi
4002 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4003 public void requestNetwork(@NonNull NetworkRequest request,
4004 int timeoutMs, int legacyType, @NonNull Handler handler,
4005 @NonNull NetworkCallback networkCallback) {
4006 if (legacyType == TYPE_NONE) {
4007 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4008 }
4009 CallbackHandler cbHandler = new CallbackHandler(handler);
4010 NetworkCapabilities nc = request.networkCapabilities;
4011 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4012 }
4013
4014 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004015 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004016 *
4017 * <p>This method will attempt to find the best network that matches the passed
4018 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4019 * criteria. The platform will evaluate which network is the best at its own discretion.
4020 * Throughput, latency, cost per byte, policy, user preference and other considerations
4021 * may be factored in the decision of what is considered the best network.
4022 *
4023 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4024 * matching this request, while always attempting to match the request to a better network if
4025 * possible. If a better match is found, the platform will switch this request to the now-best
4026 * network and inform the app of the newly best network by invoking
4027 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4028 * will not try to maintain any other network than the best one currently matching the request:
4029 * a network not matching any network request may be disconnected at any time.
4030 *
4031 * <p>For example, an application could use this method to obtain a connected cellular network
4032 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4033 * radio to consume additional power. Or, an application could inform the system that it wants
4034 * a network supporting sending MMSes and have the system let it know about the currently best
4035 * MMS-supporting network through the provided {@link NetworkCallback}.
4036 *
4037 * <p>The status of the request can be followed by listening to the various callbacks described
4038 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4039 * used to direct traffic to the network (although accessing some networks may be subject to
4040 * holding specific permissions). Callers will learn about the specific characteristics of the
4041 * network through
4042 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4043 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4044 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4045 * matching the request at any given time; therefore when a better network matching the request
4046 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4047 * with the new network after which no further updates are given about the previously-best
4048 * network, unless it becomes the best again at some later time. All callbacks are invoked
4049 * in order on the same thread, which by default is a thread created by the framework running
4050 * in the app.
4051 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4052 * callbacks are invoked.
4053 *
4054 * <p>This{@link NetworkRequest} will live until released via
4055 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4056 * which point the system may let go of the network at any time.
4057 *
4058 * <p>A version of this method which takes a timeout is
4059 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4060 * wait for a limited amount of time for the network to become unavailable.
4061 *
4062 * <p>It is presently unsupported to request a network with mutable
4063 * {@link NetworkCapabilities} such as
4064 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4065 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4066 * as these {@code NetworkCapabilities} represent states that a particular
4067 * network may never attain, and whether a network will attain these states
4068 * is unknown prior to bringing up the network so the framework does not
4069 * know how to go about satisfying a request with these capabilities.
4070 *
4071 * <p>This method requires the caller to hold either the
4072 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4073 * or the ability to modify system settings as determined by
4074 * {@link android.provider.Settings.System#canWrite}.</p>
4075 *
4076 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4077 * number of outstanding requests to 100 per app (identified by their UID), shared with
4078 * all variants of this method, of {@link #registerNetworkCallback} as well as
4079 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4080 * Requesting a network with this method will count toward this limit. If this limit is
4081 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4082 * make sure to unregister the callbacks with
4083 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4084 *
4085 * @param request {@link NetworkRequest} describing this request.
4086 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4087 * the callback must not be shared - it uniquely specifies this request.
4088 * The callback is invoked on the default internal Handler.
4089 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4090 * @throws SecurityException if missing the appropriate permissions.
4091 * @throws RuntimeException if the app already has too many callbacks registered.
4092 */
4093 public void requestNetwork(@NonNull NetworkRequest request,
4094 @NonNull NetworkCallback networkCallback) {
4095 requestNetwork(request, networkCallback, getDefaultHandler());
4096 }
4097
4098 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004099 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004100 *
4101 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4102 * but runs all the callbacks on the passed Handler.
4103 *
4104 * <p>This method has the same permission requirements as
4105 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4106 * and throws the same exceptions in the same conditions.
4107 *
4108 * @param request {@link NetworkRequest} describing this request.
4109 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4110 * the callback must not be shared - it uniquely specifies this request.
4111 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4112 */
4113 public void requestNetwork(@NonNull NetworkRequest request,
4114 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4115 CallbackHandler cbHandler = new CallbackHandler(handler);
4116 NetworkCapabilities nc = request.networkCapabilities;
4117 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4118 }
4119
4120 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004121 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004122 * by a timeout.
4123 *
4124 * This function behaves identically to the non-timed-out version
4125 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4126 * is not found within the given time (in milliseconds) the
4127 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4128 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4129 * not have to be released if timed-out (it is automatically released). Unregistering a
4130 * request that timed out is not an error.
4131 *
4132 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4133 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4134 * for that purpose. Calling this method will attempt to bring up the requested network.
4135 *
4136 * <p>This method has the same permission requirements as
4137 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4138 * and throws the same exceptions in the same conditions.
4139 *
4140 * @param request {@link NetworkRequest} describing this request.
4141 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4142 * the callback must not be shared - it uniquely specifies this request.
4143 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4144 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4145 * be a positive value (i.e. >0).
4146 */
4147 public void requestNetwork(@NonNull NetworkRequest request,
4148 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4149 checkTimeout(timeoutMs);
4150 NetworkCapabilities nc = request.networkCapabilities;
4151 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4152 getDefaultHandler());
4153 }
4154
4155 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004156 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004157 * by a timeout.
4158 *
4159 * This method behaves identically to
4160 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4161 * on the passed Handler.
4162 *
4163 * <p>This method has the same permission requirements as
4164 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4165 * and throws the same exceptions in the same conditions.
4166 *
4167 * @param request {@link NetworkRequest} describing this request.
4168 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4169 * the callback must not be shared - it uniquely specifies this request.
4170 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4171 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4172 * before {@link NetworkCallback#onUnavailable} is called.
4173 */
4174 public void requestNetwork(@NonNull NetworkRequest request,
4175 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4176 checkTimeout(timeoutMs);
4177 CallbackHandler cbHandler = new CallbackHandler(handler);
4178 NetworkCapabilities nc = request.networkCapabilities;
4179 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4180 }
4181
4182 /**
4183 * The lookup key for a {@link Network} object included with the intent after
4184 * successfully finding a network for the applications request. Retrieve it with
4185 * {@link android.content.Intent#getParcelableExtra(String)}.
4186 * <p>
4187 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4188 * then you must get a ConnectivityManager instance before doing so.
4189 */
4190 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4191
4192 /**
4193 * The lookup key for a {@link NetworkRequest} object included with the intent after
4194 * successfully finding a network for the applications request. Retrieve it with
4195 * {@link android.content.Intent#getParcelableExtra(String)}.
4196 */
4197 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4198
4199
4200 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004201 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004202 *
4203 * This function behaves identically to the version that takes a NetworkCallback, but instead
4204 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4205 * the request may outlive the calling application and get called back when a suitable
4206 * network is found.
4207 * <p>
4208 * The operation is an Intent broadcast that goes to a broadcast receiver that
4209 * you registered with {@link Context#registerReceiver} or through the
4210 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4211 * <p>
4212 * The operation Intent is delivered with two extras, a {@link Network} typed
4213 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4214 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4215 * the original requests parameters. It is important to create a new,
4216 * {@link NetworkCallback} based request before completing the processing of the
4217 * Intent to reserve the network or it will be released shortly after the Intent
4218 * is processed.
4219 * <p>
4220 * If there is already a request for this Intent registered (with the equality of
4221 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4222 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4223 * <p>
4224 * The request may be released normally by calling
4225 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4226 * <p>It is presently unsupported to request a network with either
4227 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4228 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4229 * as these {@code NetworkCapabilities} represent states that a particular
4230 * network may never attain, and whether a network will attain these states
4231 * is unknown prior to bringing up the network so the framework does not
4232 * know how to go about satisfying a request with these capabilities.
4233 *
4234 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4235 * number of outstanding requests to 100 per app (identified by their UID), shared with
4236 * all variants of this method, of {@link #registerNetworkCallback} as well as
4237 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4238 * Requesting a network with this method will count toward this limit. If this limit is
4239 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4240 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4241 * or {@link #releaseNetworkRequest(PendingIntent)}.
4242 *
4243 * <p>This method requires the caller to hold either the
4244 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4245 * or the ability to modify system settings as determined by
4246 * {@link android.provider.Settings.System#canWrite}.</p>
4247 *
4248 * @param request {@link NetworkRequest} describing this request.
4249 * @param operation Action to perform when the network is available (corresponds
4250 * to the {@link NetworkCallback#onAvailable} call. Typically
4251 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4252 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4253 * @throws SecurityException if missing the appropriate permissions.
4254 * @throws RuntimeException if the app already has too many callbacks registered.
4255 */
4256 public void requestNetwork(@NonNull NetworkRequest request,
4257 @NonNull PendingIntent operation) {
4258 printStackTrace();
4259 checkPendingIntentNotNull(operation);
4260 try {
4261 mService.pendingRequestForNetwork(
4262 request.networkCapabilities, operation, mContext.getOpPackageName(),
4263 getAttributionTag());
4264 } catch (RemoteException e) {
4265 throw e.rethrowFromSystemServer();
4266 } catch (ServiceSpecificException e) {
4267 throw convertServiceException(e);
4268 }
4269 }
4270
4271 /**
4272 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4273 * <p>
4274 * This method has the same behavior as
4275 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4276 * releasing network resources and disconnecting.
4277 *
4278 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4279 * PendingIntent passed to
4280 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4281 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4282 */
4283 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4284 printStackTrace();
4285 checkPendingIntentNotNull(operation);
4286 try {
4287 mService.releasePendingNetworkRequest(operation);
4288 } catch (RemoteException e) {
4289 throw e.rethrowFromSystemServer();
4290 }
4291 }
4292
4293 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004294 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004295 }
4296
4297 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004298 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004299 }
4300
4301 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004302 if (timeoutMs <= 0) {
4303 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4304 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004305 }
4306
4307 /**
4308 * Registers to receive notifications about all networks which satisfy the given
4309 * {@link NetworkRequest}. The callbacks will continue to be called until
4310 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4311 * called.
4312 *
4313 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4314 * number of outstanding requests to 100 per app (identified by their UID), shared with
4315 * all variants of this method, of {@link #requestNetwork} as well as
4316 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4317 * Requesting a network with this method will count toward this limit. If this limit is
4318 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4319 * make sure to unregister the callbacks with
4320 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4321 *
4322 * @param request {@link NetworkRequest} describing this request.
4323 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4324 * networks change state.
4325 * The callback is invoked on the default internal Handler.
4326 * @throws RuntimeException if the app already has too many callbacks registered.
4327 */
4328 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4329 public void registerNetworkCallback(@NonNull NetworkRequest request,
4330 @NonNull NetworkCallback networkCallback) {
4331 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4332 }
4333
4334 /**
4335 * Registers to receive notifications about all networks which satisfy the given
4336 * {@link NetworkRequest}. The callbacks will continue to be called until
4337 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4338 * called.
4339 *
4340 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4341 * number of outstanding requests to 100 per app (identified by their UID), shared with
4342 * all variants of this method, of {@link #requestNetwork} as well as
4343 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4344 * Requesting a network with this method will count toward this limit. If this limit is
4345 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4346 * make sure to unregister the callbacks with
4347 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4348 *
4349 *
4350 * @param request {@link NetworkRequest} describing this request.
4351 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4352 * networks change state.
4353 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4354 * @throws RuntimeException if the app already has too many callbacks registered.
4355 */
4356 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4357 public void registerNetworkCallback(@NonNull NetworkRequest request,
4358 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4359 CallbackHandler cbHandler = new CallbackHandler(handler);
4360 NetworkCapabilities nc = request.networkCapabilities;
4361 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4362 }
4363
4364 /**
4365 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4366 * {@link NetworkRequest}.
4367 *
4368 * This function behaves identically to the version that takes a NetworkCallback, but instead
4369 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4370 * the request may outlive the calling application and get called back when a suitable
4371 * network is found.
4372 * <p>
4373 * The operation is an Intent broadcast that goes to a broadcast receiver that
4374 * you registered with {@link Context#registerReceiver} or through the
4375 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4376 * <p>
4377 * The operation Intent is delivered with two extras, a {@link Network} typed
4378 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4379 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4380 * the original requests parameters.
4381 * <p>
4382 * If there is already a request for this Intent registered (with the equality of
4383 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4384 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4385 * <p>
4386 * The request may be released normally by calling
4387 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4388 *
4389 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4390 * number of outstanding requests to 100 per app (identified by their UID), shared with
4391 * all variants of this method, of {@link #requestNetwork} as well as
4392 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4393 * Requesting a network with this method will count toward this limit. If this limit is
4394 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4395 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4396 * or {@link #releaseNetworkRequest(PendingIntent)}.
4397 *
4398 * @param request {@link NetworkRequest} describing this request.
4399 * @param operation Action to perform when the network is available (corresponds
4400 * to the {@link NetworkCallback#onAvailable} call. Typically
4401 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4402 * @throws RuntimeException if the app already has too many callbacks registered.
4403 */
4404 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4405 public void registerNetworkCallback(@NonNull NetworkRequest request,
4406 @NonNull PendingIntent operation) {
4407 printStackTrace();
4408 checkPendingIntentNotNull(operation);
4409 try {
4410 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004411 request.networkCapabilities, operation, mContext.getOpPackageName(),
4412 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004413 } catch (RemoteException e) {
4414 throw e.rethrowFromSystemServer();
4415 } catch (ServiceSpecificException e) {
4416 throw convertServiceException(e);
4417 }
4418 }
4419
4420 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004421 * Registers to receive notifications about changes in the application's default network. This
4422 * may be a physical network or a virtual network, such as a VPN that applies to the
4423 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004424 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4425 *
4426 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4427 * number of outstanding requests to 100 per app (identified by their UID), shared with
4428 * all variants of this method, of {@link #requestNetwork} as well as
4429 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4430 * Requesting a network with this method will count toward this limit. If this limit is
4431 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4432 * make sure to unregister the callbacks with
4433 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4434 *
4435 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004436 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004437 * The callback is invoked on the default internal Handler.
4438 * @throws RuntimeException if the app already has too many callbacks registered.
4439 */
4440 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4441 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4442 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4443 }
4444
4445 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004446 * Registers to receive notifications about changes in the application's default network. This
4447 * may be a physical network or a virtual network, such as a VPN that applies to the
4448 * application. The callbacks will continue to be called until either the application exits or
4449 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4450 *
4451 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4452 * number of outstanding requests to 100 per app (identified by their UID), shared with
4453 * all variants of this method, of {@link #requestNetwork} as well as
4454 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4455 * Requesting a network with this method will count toward this limit. If this limit is
4456 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4457 * make sure to unregister the callbacks with
4458 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4459 *
4460 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4461 * application's default network changes.
4462 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4463 * @throws RuntimeException if the app already has too many callbacks registered.
4464 */
4465 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4466 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4467 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004468 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004469 }
4470
4471 /**
4472 * Registers to receive notifications about changes in the default network for the specified
4473 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4474 * UID. The callbacks will continue to be called until either the application exits or
4475 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4476 *
4477 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4478 * number of outstanding requests to 100 per app (identified by their UID), shared with
4479 * all variants of this method, of {@link #requestNetwork} as well as
4480 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4481 * Requesting a network with this method will count toward this limit. If this limit is
4482 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4483 * make sure to unregister the callbacks with
4484 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4485 *
4486 * @param uid the UID for which to track default network changes.
4487 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4488 * UID's default network changes.
4489 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4490 * @throws RuntimeException if the app already has too many callbacks registered.
4491 * @hide
4492 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004493 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004494 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4495 @RequiresPermission(anyOf = {
4496 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4497 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004498 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004499 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004500 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004501 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004502 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4503 }
4504
4505 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004506 * Registers to receive notifications about changes in the system default network. The callbacks
4507 * will continue to be called until either the application exits or
4508 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4509 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004510 * This method should not be used to determine networking state seen by applications, because in
4511 * many cases, most or even all application traffic may not use the default network directly,
4512 * and traffic from different applications may go on different networks by default. As an
4513 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4514 * and not onto the system default network. Applications or system components desiring to do
4515 * determine network state as seen by applications should use other methods such as
4516 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4517 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004518 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4519 * number of outstanding requests to 100 per app (identified by their UID), shared with
4520 * all variants of this method, of {@link #requestNetwork} as well as
4521 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4522 * Requesting a network with this method will count toward this limit. If this limit is
4523 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4524 * make sure to unregister the callbacks with
4525 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4526 *
4527 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4528 * system default network changes.
4529 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4530 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004531 *
4532 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004533 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004534 @SystemApi(client = MODULE_LIBRARIES)
4535 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4536 @RequiresPermission(anyOf = {
4537 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4538 android.Manifest.permission.NETWORK_SETTINGS})
4539 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004540 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004541 CallbackHandler cbHandler = new CallbackHandler(handler);
4542 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004543 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004544 }
4545
4546 /**
junyulaibd123062021-03-15 11:48:48 +08004547 * Registers to receive notifications about the best matching network which satisfy the given
4548 * {@link NetworkRequest}. The callbacks will continue to be called until
4549 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4550 * called.
4551 *
4552 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4553 * number of outstanding requests to 100 per app (identified by their UID), shared with
4554 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4555 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4556 * Requesting a network with this method will count toward this limit. If this limit is
4557 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4558 * make sure to unregister the callbacks with
4559 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4560 *
4561 *
4562 * @param request {@link NetworkRequest} describing this request.
4563 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4564 * networks change state.
4565 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4566 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004567 */
junyulai5a5c99b2021-03-05 15:51:17 +08004568 @SuppressLint("ExecutorRegistration")
4569 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4570 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4571 final NetworkCapabilities nc = request.networkCapabilities;
4572 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004573 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004574 }
4575
4576 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004577 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4578 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4579 * network connection for updated bandwidth information. The caller will be notified via
4580 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4581 * method assumes that the caller has previously called
4582 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4583 * changes.
4584 *
4585 * @param network {@link Network} specifying which network you're interested.
4586 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4587 */
4588 public boolean requestBandwidthUpdate(@NonNull Network network) {
4589 try {
4590 return mService.requestBandwidthUpdate(network);
4591 } catch (RemoteException e) {
4592 throw e.rethrowFromSystemServer();
4593 }
4594 }
4595
4596 /**
4597 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4598 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4599 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4600 * If the given {@code NetworkCallback} had previously been used with
4601 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4602 * will be disconnected.
4603 *
4604 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4605 * triggering it as soon as this call returns.
4606 *
4607 * @param networkCallback The {@link NetworkCallback} used when making the request.
4608 */
4609 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4610 printStackTrace();
4611 checkCallbackNotNull(networkCallback);
4612 final List<NetworkRequest> reqs = new ArrayList<>();
4613 // Find all requests associated to this callback and stop callback triggers immediately.
4614 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4615 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004616 if (networkCallback.networkRequest == null) {
4617 throw new IllegalArgumentException("NetworkCallback was not registered");
4618 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004619 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4620 Log.d(TAG, "NetworkCallback was already unregistered");
4621 return;
4622 }
4623 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4624 if (e.getValue() == networkCallback) {
4625 reqs.add(e.getKey());
4626 }
4627 }
4628 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4629 for (NetworkRequest r : reqs) {
4630 try {
4631 mService.releaseNetworkRequest(r);
4632 } catch (RemoteException e) {
4633 throw e.rethrowFromSystemServer();
4634 }
4635 // Only remove mapping if rpc was successful.
4636 sCallbacks.remove(r);
4637 }
4638 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4639 }
4640 }
4641
4642 /**
4643 * Unregisters a callback previously registered via
4644 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4645 *
4646 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4647 * PendingIntent passed to
4648 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4649 * Cannot be null.
4650 */
4651 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4652 releaseNetworkRequest(operation);
4653 }
4654
4655 /**
4656 * Informs the system whether it should switch to {@code network} regardless of whether it is
4657 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4658 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4659 * the system default network regardless of any other network that's currently connected. If
4660 * {@code always} is true, then the choice is remembered, so that the next time the user
4661 * connects to this network, the system will switch to it.
4662 *
4663 * @param network The network to accept.
4664 * @param accept Whether to accept the network even if unvalidated.
4665 * @param always Whether to remember this choice in the future.
4666 *
4667 * @hide
4668 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004669 @SystemApi(client = MODULE_LIBRARIES)
4670 @RequiresPermission(anyOf = {
4671 android.Manifest.permission.NETWORK_SETTINGS,
4672 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4673 android.Manifest.permission.NETWORK_STACK,
4674 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4675 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004676 try {
4677 mService.setAcceptUnvalidated(network, accept, always);
4678 } catch (RemoteException e) {
4679 throw e.rethrowFromSystemServer();
4680 }
4681 }
4682
4683 /**
4684 * Informs the system whether it should consider the network as validated even if it only has
4685 * partial connectivity. If {@code accept} is true, then the network will be considered as
4686 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4687 * is remembered, so that the next time the user connects to this network, the system will
4688 * switch to it.
4689 *
4690 * @param network The network to accept.
4691 * @param accept Whether to consider the network as validated even if it has partial
4692 * connectivity.
4693 * @param always Whether to remember this choice in the future.
4694 *
4695 * @hide
4696 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004697 @SystemApi(client = MODULE_LIBRARIES)
4698 @RequiresPermission(anyOf = {
4699 android.Manifest.permission.NETWORK_SETTINGS,
4700 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4701 android.Manifest.permission.NETWORK_STACK,
4702 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4703 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4704 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004705 try {
4706 mService.setAcceptPartialConnectivity(network, accept, always);
4707 } catch (RemoteException e) {
4708 throw e.rethrowFromSystemServer();
4709 }
4710 }
4711
4712 /**
4713 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4714 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4715 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4716 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4717 *
4718 * @param network The network to accept.
4719 *
4720 * @hide
4721 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004722 @SystemApi(client = MODULE_LIBRARIES)
4723 @RequiresPermission(anyOf = {
4724 android.Manifest.permission.NETWORK_SETTINGS,
4725 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4726 android.Manifest.permission.NETWORK_STACK,
4727 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4728 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004729 try {
4730 mService.setAvoidUnvalidated(network);
4731 } catch (RemoteException e) {
4732 throw e.rethrowFromSystemServer();
4733 }
4734 }
4735
4736 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004737 * Temporarily allow bad wifi to override {@code config_networkAvoidBadWifi} configuration.
4738 *
4739 * @param timeMs The expired current time. The value should be set within a limited time from
4740 * now.
4741 *
4742 * @hide
4743 */
4744 public void setTestAllowBadWifiUntil(long timeMs) {
4745 try {
4746 mService.setTestAllowBadWifiUntil(timeMs);
4747 } catch (RemoteException e) {
4748 throw e.rethrowFromSystemServer();
4749 }
4750 }
4751
4752 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004753 * Requests that the system open the captive portal app on the specified network.
4754 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004755 * <p>This is to be used on networks where a captive portal was detected, as per
4756 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4757 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004758 * @param network The network to log into.
4759 *
4760 * @hide
4761 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004762 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4763 @RequiresPermission(anyOf = {
4764 android.Manifest.permission.NETWORK_SETTINGS,
4765 android.Manifest.permission.NETWORK_STACK,
4766 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4767 })
4768 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004769 try {
4770 mService.startCaptivePortalApp(network);
4771 } catch (RemoteException e) {
4772 throw e.rethrowFromSystemServer();
4773 }
4774 }
4775
4776 /**
4777 * Requests that the system open the captive portal app with the specified extras.
4778 *
4779 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4780 * corresponding permission.
4781 * @param network Network on which the captive portal was detected.
4782 * @param appExtras Extras to include in the app start intent.
4783 * @hide
4784 */
4785 @SystemApi
4786 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4787 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4788 try {
4789 mService.startCaptivePortalAppInternal(network, appExtras);
4790 } catch (RemoteException e) {
4791 throw e.rethrowFromSystemServer();
4792 }
4793 }
4794
4795 /**
4796 * Determine whether the device is configured to avoid bad wifi.
4797 * @hide
4798 */
4799 @SystemApi
4800 @RequiresPermission(anyOf = {
4801 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4802 android.Manifest.permission.NETWORK_STACK})
4803 public boolean shouldAvoidBadWifi() {
4804 try {
4805 return mService.shouldAvoidBadWifi();
4806 } catch (RemoteException e) {
4807 throw e.rethrowFromSystemServer();
4808 }
4809 }
4810
4811 /**
4812 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4813 * time-sensitive user-facing operations when the system default network is temporarily
4814 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4815 * this method), and the operation should be infrequent to ensure that data usage is limited.
4816 *
4817 * An example of such an operation might be a time-sensitive foreground activity, such as a
4818 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4819 */
4820 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4821
4822 /**
4823 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4824 * a backup channel for traffic that is primarily going over another network.
4825 *
4826 * An example might be maintaining backup connections to peers or servers for the purpose of
4827 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4828 * on backup paths should be negligible compared to the traffic on the main path.
4829 */
4830 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4831
4832 /**
4833 * It is acceptable to use metered data to improve network latency and performance.
4834 */
4835 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4836
4837 /**
4838 * Return value to use for unmetered networks. On such networks we currently set all the flags
4839 * to true.
4840 * @hide
4841 */
4842 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4843 MULTIPATH_PREFERENCE_HANDOVER |
4844 MULTIPATH_PREFERENCE_RELIABILITY |
4845 MULTIPATH_PREFERENCE_PERFORMANCE;
4846
Aaron Huangcff22942021-05-27 16:31:26 +08004847 /** @hide */
4848 @Retention(RetentionPolicy.SOURCE)
4849 @IntDef(flag = true, value = {
4850 MULTIPATH_PREFERENCE_HANDOVER,
4851 MULTIPATH_PREFERENCE_RELIABILITY,
4852 MULTIPATH_PREFERENCE_PERFORMANCE,
4853 })
4854 public @interface MultipathPreference {
4855 }
4856
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004857 /**
4858 * Provides a hint to the calling application on whether it is desirable to use the
4859 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4860 * for multipath data transfer on this network when it is not the system default network.
4861 * Applications desiring to use multipath network protocols should call this method before
4862 * each such operation.
4863 *
4864 * @param network The network on which the application desires to use multipath data.
4865 * If {@code null}, this method will return the a preference that will generally
4866 * apply to metered networks.
4867 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4868 */
4869 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4870 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
4871 try {
4872 return mService.getMultipathPreference(network);
4873 } catch (RemoteException e) {
4874 throw e.rethrowFromSystemServer();
4875 }
4876 }
4877
4878 /**
4879 * Resets all connectivity manager settings back to factory defaults.
4880 * @hide
4881 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004882 @SystemApi(client = MODULE_LIBRARIES)
4883 @RequiresPermission(anyOf = {
4884 android.Manifest.permission.NETWORK_SETTINGS,
4885 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004886 public void factoryReset() {
4887 try {
4888 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09004889 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004890 } catch (RemoteException e) {
4891 throw e.rethrowFromSystemServer();
4892 }
4893 }
4894
4895 /**
4896 * Binds the current process to {@code network}. All Sockets created in the future
4897 * (and not explicitly bound via a bound SocketFactory from
4898 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4899 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4900 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4901 * work and all host name resolutions will fail. This is by design so an application doesn't
4902 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4903 * To clear binding pass {@code null} for {@code network}. Using individually bound
4904 * Sockets created by Network.getSocketFactory().createSocket() and
4905 * performing network-specific host name resolutions via
4906 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4907 * {@code bindProcessToNetwork}.
4908 *
4909 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4910 * the current binding.
4911 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4912 */
4913 public boolean bindProcessToNetwork(@Nullable Network network) {
4914 // Forcing callers to call through non-static function ensures ConnectivityManager
4915 // instantiated.
4916 return setProcessDefaultNetwork(network);
4917 }
4918
4919 /**
4920 * Binds the current process to {@code network}. All Sockets created in the future
4921 * (and not explicitly bound via a bound SocketFactory from
4922 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4923 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4924 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4925 * work and all host name resolutions will fail. This is by design so an application doesn't
4926 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4927 * To clear binding pass {@code null} for {@code network}. Using individually bound
4928 * Sockets created by Network.getSocketFactory().createSocket() and
4929 * performing network-specific host name resolutions via
4930 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4931 * {@code setProcessDefaultNetwork}.
4932 *
4933 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4934 * the current binding.
4935 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4936 * @deprecated This function can throw {@link IllegalStateException}. Use
4937 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4938 * is a direct replacement.
4939 */
4940 @Deprecated
4941 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
4942 int netId = (network == null) ? NETID_UNSET : network.netId;
4943 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4944
4945 if (netId != NETID_UNSET) {
4946 netId = network.getNetIdForResolv();
4947 }
4948
4949 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4950 return false;
4951 }
4952
4953 if (!isSameNetId) {
4954 // Set HTTP proxy system properties to match network.
4955 // TODO: Deprecate this static method and replace it with a non-static version.
4956 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09004957 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004958 } catch (SecurityException e) {
4959 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4960 Log.e(TAG, "Can't set proxy properties", e);
4961 }
4962 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09004963 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004964 // Must flush socket pool as idle sockets will be bound to previous network and may
4965 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01004966 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004967 }
4968
4969 return true;
4970 }
4971
4972 /**
4973 * Returns the {@link Network} currently bound to this process via
4974 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4975 *
4976 * @return {@code Network} to which this process is bound, or {@code null}.
4977 */
4978 @Nullable
4979 public Network getBoundNetworkForProcess() {
4980 // Forcing callers to call thru non-static function ensures ConnectivityManager
4981 // instantiated.
4982 return getProcessDefaultNetwork();
4983 }
4984
4985 /**
4986 * Returns the {@link Network} currently bound to this process via
4987 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4988 *
4989 * @return {@code Network} to which this process is bound, or {@code null}.
4990 * @deprecated Using this function can lead to other functions throwing
4991 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4992 * {@code getBoundNetworkForProcess} is a direct replacement.
4993 */
4994 @Deprecated
4995 @Nullable
4996 public static Network getProcessDefaultNetwork() {
4997 int netId = NetworkUtils.getBoundNetworkForProcess();
4998 if (netId == NETID_UNSET) return null;
4999 return new Network(netId);
5000 }
5001
5002 private void unsupportedStartingFrom(int version) {
5003 if (Process.myUid() == Process.SYSTEM_UID) {
5004 // The getApplicationInfo() call we make below is not supported in system context. Let
5005 // the call through here, and rely on the fact that ConnectivityService will refuse to
5006 // allow the system to use these APIs anyway.
5007 return;
5008 }
5009
5010 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5011 throw new UnsupportedOperationException(
5012 "This method is not supported in target SDK version " + version + " and above");
5013 }
5014 }
5015
5016 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5017 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5018 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5019 // remove these exemptions. Note that this check is not secure, and apps can still access these
5020 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5021 // so is unsupported and may break in the future. http://b/22728205
5022 private void checkLegacyRoutingApiAccess() {
5023 unsupportedStartingFrom(VERSION_CODES.M);
5024 }
5025
5026 /**
5027 * Binds host resolutions performed by this process to {@code network}.
5028 * {@link #bindProcessToNetwork} takes precedence over this setting.
5029 *
5030 * @param network The {@link Network} to bind host resolutions from the current process to, or
5031 * {@code null} to clear the current binding.
5032 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5033 * @hide
5034 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5035 */
5036 @Deprecated
5037 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5038 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5039 return NetworkUtils.bindProcessToNetworkForHostResolution(
5040 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5041 }
5042
5043 /**
5044 * Device is not restricting metered network activity while application is running on
5045 * background.
5046 */
5047 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5048
5049 /**
5050 * Device is restricting metered network activity while application is running on background,
5051 * but application is allowed to bypass it.
5052 * <p>
5053 * In this state, application should take action to mitigate metered network access.
5054 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5055 */
5056 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5057
5058 /**
5059 * Device is restricting metered network activity while application is running on background.
5060 * <p>
5061 * In this state, application should not try to use the network while running on background,
5062 * because it would be denied.
5063 */
5064 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5065
5066 /**
5067 * A change in the background metered network activity restriction has occurred.
5068 * <p>
5069 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5070 * applies to them.
5071 * <p>
5072 * This is only sent to registered receivers, not manifest receivers.
5073 */
5074 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5075 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5076 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5077
Aaron Huangcff22942021-05-27 16:31:26 +08005078 /** @hide */
5079 @Retention(RetentionPolicy.SOURCE)
5080 @IntDef(flag = false, value = {
5081 RESTRICT_BACKGROUND_STATUS_DISABLED,
5082 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5083 RESTRICT_BACKGROUND_STATUS_ENABLED,
5084 })
5085 public @interface RestrictBackgroundStatus {
5086 }
5087
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005088 /**
5089 * Determines if the calling application is subject to metered network restrictions while
5090 * running on background.
5091 *
5092 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5093 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5094 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5095 */
5096 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5097 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005098 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005099 } catch (RemoteException e) {
5100 throw e.rethrowFromSystemServer();
5101 }
5102 }
5103
5104 /**
5105 * The network watchlist is a list of domains and IP addresses that are associated with
5106 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5107 * currently used by the system for validation purposes.
5108 *
5109 * @return Hash of network watchlist config file. Null if config does not exist.
5110 */
5111 @Nullable
5112 public byte[] getNetworkWatchlistConfigHash() {
5113 try {
5114 return mService.getNetworkWatchlistConfigHash();
5115 } catch (RemoteException e) {
5116 Log.e(TAG, "Unable to get watchlist config hash");
5117 throw e.rethrowFromSystemServer();
5118 }
5119 }
5120
5121 /**
5122 * Returns the {@code uid} of the owner of a network connection.
5123 *
5124 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5125 * IPPROTO_UDP} currently supported.
5126 * @param local The local {@link InetSocketAddress} of a connection.
5127 * @param remote The remote {@link InetSocketAddress} of a connection.
5128 * @return {@code uid} if the connection is found and the app has permission to observe it
5129 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5130 * android.os.Process#INVALID_UID} if the connection is not found.
5131 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5132 * user.
5133 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5134 */
5135 public int getConnectionOwnerUid(
5136 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5137 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5138 try {
5139 return mService.getConnectionOwnerUid(connectionInfo);
5140 } catch (RemoteException e) {
5141 throw e.rethrowFromSystemServer();
5142 }
5143 }
5144
5145 private void printStackTrace() {
5146 if (DEBUG) {
5147 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5148 final StringBuffer sb = new StringBuffer();
5149 for (int i = 3; i < callStack.length; i++) {
5150 final String stackTrace = callStack[i].toString();
5151 if (stackTrace == null || stackTrace.contains("android.os")) {
5152 break;
5153 }
5154 sb.append(" [").append(stackTrace).append("]");
5155 }
5156 Log.d(TAG, "StackLog:" + sb.toString());
5157 }
5158 }
5159
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005160 /** @hide */
5161 public TestNetworkManager startOrGetTestNetworkManager() {
5162 final IBinder tnBinder;
5163 try {
5164 tnBinder = mService.startOrGetTestNetworkService();
5165 } catch (RemoteException e) {
5166 throw e.rethrowFromSystemServer();
5167 }
5168
5169 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5170 }
5171
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005172 /** @hide */
5173 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5174 return new ConnectivityDiagnosticsManager(mContext, mService);
5175 }
5176
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005177 /**
5178 * Simulates a Data Stall for the specified Network.
5179 *
5180 * <p>This method should only be used for tests.
5181 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005182 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5183 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005184 *
5185 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005186 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5187 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5188 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005189 * @param network The Network for which a Data Stall is being simluated.
5190 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5191 * @throws SecurityException if the caller is not the owner of the given network.
5192 * @hide
5193 */
5194 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5195 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5196 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005197 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005198 @NonNull Network network, @NonNull PersistableBundle extras) {
5199 try {
5200 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5201 } catch (RemoteException e) {
5202 e.rethrowFromSystemServer();
5203 }
5204 }
5205
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005206 @NonNull
5207 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5208
5209 /**
5210 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5211 * receive available QoS events related to the {@link Network} and local ip + port
5212 * specified within socketInfo.
5213 * <p/>
5214 * The same {@link QosCallback} must be unregistered before being registered a second time,
5215 * otherwise {@link QosCallbackRegistrationException} is thrown.
5216 * <p/>
5217 * This API does not, in itself, require any permission if called with a network that is not
5218 * restricted. However, the underlying implementation currently only supports the IMS network,
5219 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5220 * useful, because they'd never be called back on networks that they would have access to.
5221 *
5222 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5223 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5224 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5225 * @throws RuntimeException if the app already has too many callbacks registered.
5226 *
5227 * Exceptions after the time of registration is passed through
5228 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5229 *
5230 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005231 * @param executor The executor on which the callback will be invoked. The provided
5232 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005233 * callbacks cannot be guaranteed.onQosCallbackRegistered
5234 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005235 *
5236 * @hide
5237 */
5238 @SystemApi
5239 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005240 @CallbackExecutor @NonNull final Executor executor,
5241 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005242 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005243 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005244 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005245
5246 try {
5247 synchronized (mQosCallbackConnections) {
5248 if (getQosCallbackConnection(callback) == null) {
5249 final QosCallbackConnection connection =
5250 new QosCallbackConnection(this, callback, executor);
5251 mQosCallbackConnections.add(connection);
5252 mService.registerQosSocketCallback(socketInfo, connection);
5253 } else {
5254 Log.e(TAG, "registerQosCallback: Callback already registered");
5255 throw new QosCallbackRegistrationException();
5256 }
5257 }
5258 } catch (final RemoteException e) {
5259 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5260
5261 // The same unregister method method is called for consistency even though nothing
5262 // will be sent to the ConnectivityService since the callback was never successfully
5263 // registered.
5264 unregisterQosCallback(callback);
5265 e.rethrowFromSystemServer();
5266 } catch (final ServiceSpecificException e) {
5267 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5268 unregisterQosCallback(callback);
5269 throw convertServiceException(e);
5270 }
5271 }
5272
5273 /**
5274 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5275 * events once unregistered and can be registered a second time.
5276 * <p/>
5277 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5278 *
5279 * @param callback the callback being unregistered
5280 *
5281 * @hide
5282 */
5283 @SystemApi
5284 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5285 Objects.requireNonNull(callback, "The callback must be non-null");
5286 try {
5287 synchronized (mQosCallbackConnections) {
5288 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5289 if (connection != null) {
5290 connection.stopReceivingMessages();
5291 mService.unregisterQosCallback(connection);
5292 mQosCallbackConnections.remove(connection);
5293 } else {
5294 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5295 }
5296 }
5297 } catch (final RemoteException e) {
5298 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5299 e.rethrowFromSystemServer();
5300 }
5301 }
5302
5303 /**
5304 * Gets the connection related to the callback.
5305 *
5306 * @param callback the callback to look up
5307 * @return the related connection
5308 */
5309 @Nullable
5310 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5311 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5312 // Checking by reference here is intentional
5313 if (connection.getCallback() == callback) {
5314 return connection;
5315 }
5316 }
5317 return null;
5318 }
5319
5320 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005321 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005322 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5323 * be used to request that the system provide a network without causing the network to be
5324 * in the foreground.
5325 *
5326 * <p>This method will attempt to find the best network that matches the passed
5327 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5328 * criteria. The platform will evaluate which network is the best at its own discretion.
5329 * Throughput, latency, cost per byte, policy, user preference and other considerations
5330 * may be factored in the decision of what is considered the best network.
5331 *
5332 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5333 * matching this request, while always attempting to match the request to a better network if
5334 * possible. If a better match is found, the platform will switch this request to the now-best
5335 * network and inform the app of the newly best network by invoking
5336 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5337 * will not try to maintain any other network than the best one currently matching the request:
5338 * a network not matching any network request may be disconnected at any time.
5339 *
5340 * <p>For example, an application could use this method to obtain a connected cellular network
5341 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5342 * radio to consume additional power. Or, an application could inform the system that it wants
5343 * a network supporting sending MMSes and have the system let it know about the currently best
5344 * MMS-supporting network through the provided {@link NetworkCallback}.
5345 *
5346 * <p>The status of the request can be followed by listening to the various callbacks described
5347 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5348 * used to direct traffic to the network (although accessing some networks may be subject to
5349 * holding specific permissions). Callers will learn about the specific characteristics of the
5350 * network through
5351 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5352 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5353 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5354 * matching the request at any given time; therefore when a better network matching the request
5355 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5356 * with the new network after which no further updates are given about the previously-best
5357 * network, unless it becomes the best again at some later time. All callbacks are invoked
5358 * in order on the same thread, which by default is a thread created by the framework running
5359 * in the app.
5360 *
5361 * <p>This{@link NetworkRequest} will live until released via
5362 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5363 * which point the system may let go of the network at any time.
5364 *
5365 * <p>It is presently unsupported to request a network with mutable
5366 * {@link NetworkCapabilities} such as
5367 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5368 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5369 * as these {@code NetworkCapabilities} represent states that a particular
5370 * network may never attain, and whether a network will attain these states
5371 * is unknown prior to bringing up the network so the framework does not
5372 * know how to go about satisfying a request with these capabilities.
5373 *
5374 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5375 * number of outstanding requests to 100 per app (identified by their UID), shared with
5376 * all variants of this method, of {@link #registerNetworkCallback} as well as
5377 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5378 * Requesting a network with this method will count toward this limit. If this limit is
5379 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5380 * make sure to unregister the callbacks with
5381 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5382 *
5383 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005384 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5385 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005386 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5387 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005388 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5389 * @throws SecurityException if missing the appropriate permissions.
5390 * @throws RuntimeException if the app already has too many callbacks registered.
5391 *
5392 * @hide
5393 */
5394 @SystemApi(client = MODULE_LIBRARIES)
5395 @SuppressLint("ExecutorRegistration")
5396 @RequiresPermission(anyOf = {
5397 android.Manifest.permission.NETWORK_SETTINGS,
5398 android.Manifest.permission.NETWORK_STACK,
5399 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5400 })
5401 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005402 @NonNull NetworkCallback networkCallback,
5403 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005404 final NetworkCapabilities nc = request.networkCapabilities;
5405 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005406 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005407 }
James Mattis12aeab82021-01-10 14:24:24 -08005408
5409 /**
James Mattis12aeab82021-01-10 14:24:24 -08005410 * Used by automotive devices to set the network preferences used to direct traffic at an
5411 * application level as per the given OemNetworkPreferences. An example use-case would be an
5412 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5413 * vehicle via a particular network.
5414 *
5415 * Calling this will overwrite the existing preference.
5416 *
5417 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5418 * @param executor the executor on which listener will be invoked.
5419 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5420 * communicate completion of setOemNetworkPreference(). This will only be
5421 * called once upon successful completion of setOemNetworkPreference().
5422 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5423 * @throws SecurityException if missing the appropriate permissions.
5424 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005425 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005426 */
James Mattis6e2d7022021-01-26 16:23:52 -08005427 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005428 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005429 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005430 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005431 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005432 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5433 if (null != listener) {
5434 Objects.requireNonNull(executor, "Executor must be non-null");
5435 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005436 final IOnCompleteListener listenerInternal = listener == null ? null :
5437 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005438 @Override
5439 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005440 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005441 }
5442 };
5443
5444 try {
5445 mService.setOemNetworkPreference(preference, listenerInternal);
5446 } catch (RemoteException e) {
5447 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5448 throw e.rethrowFromSystemServer();
5449 }
5450 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005451
Chalard Jeanad565e22021-02-25 17:23:40 +09005452 /**
5453 * Request that a user profile is put by default on a network matching a given preference.
5454 *
5455 * See the documentation for the individual preferences for a description of the supported
5456 * behaviors.
5457 *
5458 * @param profile the profile concerned.
5459 * @param preference the preference for this profile.
5460 * @param executor an executor to execute the listener on. Optional if listener is null.
5461 * @param listener an optional listener to listen for completion of the operation.
5462 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5463 * @throws SecurityException if missing the appropriate permissions.
5464 * @hide
5465 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005466 // This function is for establishing per-profile default networking and can only be called by
5467 // the device policy manager, running as the system server. It would make no sense to call it
5468 // on a context for a user because it does not establish a setting on behalf of a user, rather
5469 // it establishes a setting for a user on behalf of the DPM.
5470 @SuppressLint({"UserHandle"})
5471 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005472 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5473 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5474 @ProfileNetworkPreference final int preference,
5475 @Nullable @CallbackExecutor final Executor executor,
5476 @Nullable final Runnable listener) {
5477 if (null != listener) {
5478 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5479 }
5480 final IOnCompleteListener proxy;
5481 if (null == listener) {
5482 proxy = null;
5483 } else {
5484 proxy = new IOnCompleteListener.Stub() {
5485 @Override
5486 public void onComplete() {
5487 executor.execute(listener::run);
5488 }
5489 };
5490 }
5491 try {
5492 mService.setProfileNetworkPreference(profile, preference, proxy);
5493 } catch (RemoteException e) {
5494 throw e.rethrowFromSystemServer();
5495 }
5496 }
5497
lucaslin5cdbcfb2021-03-12 00:46:33 +08005498 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005499 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005500 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005501 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005502
5503 /**
5504 * Get the network ID range reserved for IPSec tunnel interfaces.
5505 *
5506 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5507 * @hide
5508 */
5509 @SystemApi(client = MODULE_LIBRARIES)
5510 @NonNull
5511 public static Range<Integer> getIpSecNetIdRange() {
5512 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5513 }
markchien738ad912021-12-09 18:15:45 +08005514
5515 /**
5516 * Allow target application using metered network.
5517 *
5518 * @param uid uid of target app
5519 * @hide
5520 */
5521 @SystemApi(client = MODULE_LIBRARIES)
5522 @RequiresPermission(anyOf = {
5523 android.Manifest.permission.NETWORK_SETTINGS,
5524 android.Manifest.permission.NETWORK_STACK,
5525 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5526 })
5527 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
5528 try {
5529 mService.updateMeteredNetworkAllowList(uid, add);
5530 } catch (RemoteException e) {
5531 throw e.rethrowFromSystemServer();
5532 } catch (IllegalStateException ie) {
5533 throw ie;
5534 }
5535 }
5536
5537 /**
5538 * Disallow target application using metered network.
5539 *
5540 * @param uid uid of target app
5541 * @hide
5542 */
5543 @SystemApi(client = MODULE_LIBRARIES)
5544 @RequiresPermission(anyOf = {
5545 android.Manifest.permission.NETWORK_SETTINGS,
5546 android.Manifest.permission.NETWORK_STACK,
5547 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5548 })
5549 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
5550 try {
5551 mService.updateMeteredNetworkDenyList(uid, add);
5552 } catch (RemoteException e) {
5553 throw e.rethrowFromSystemServer();
5554 } catch (IllegalStateException ie) {
5555 throw ie;
5556 }
5557 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005558}