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