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