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