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