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