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