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