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