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