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