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