blob: 75934822c74eb0e1557e038c71528d4d3aa1880d [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;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080019import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
21import static android.net.NetworkRequest.Type.LISTEN;
junyulai7664f622021-03-12 20:05:08 +080022import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090023import static android.net.NetworkRequest.Type.REQUEST;
24import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colittia77d05e2021-01-29 20:14:04 +090025import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090026import static android.net.QosCallback.QosCallbackRegistrationException;
27
28import android.annotation.CallbackExecutor;
29import android.annotation.IntDef;
30import android.annotation.NonNull;
31import android.annotation.Nullable;
32import android.annotation.RequiresPermission;
33import android.annotation.SdkConstant;
34import android.annotation.SdkConstant.SdkConstantType;
35import android.annotation.SuppressLint;
36import android.annotation.SystemApi;
37import android.annotation.SystemService;
38import android.app.PendingIntent;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090039import android.app.admin.DevicePolicyManager;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090040import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090041import android.content.ComponentName;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090042import android.content.Context;
43import android.content.Intent;
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +090044import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090045import android.net.IpSecManager.UdpEncapsulationSocket;
46import android.net.SocketKeepalive.Callback;
47import android.net.TetheringManager.StartTetheringCallback;
48import android.net.TetheringManager.TetheringEventCallback;
49import android.net.TetheringManager.TetheringRequest;
50import android.os.Binder;
51import android.os.Build;
52import android.os.Build.VERSION_CODES;
53import android.os.Bundle;
54import android.os.Handler;
55import android.os.IBinder;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090056import android.os.Looper;
57import android.os.Message;
58import android.os.Messenger;
59import android.os.ParcelFileDescriptor;
60import android.os.PersistableBundle;
61import android.os.Process;
62import android.os.RemoteException;
63import android.os.ResultReceiver;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090064import android.os.ServiceSpecificException;
Chalard Jeanad565e22021-02-25 17:23:40 +090065import android.os.UserHandle;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090066import android.provider.Settings;
67import android.telephony.SubscriptionManager;
68import android.telephony.TelephonyManager;
69import android.util.ArrayMap;
70import android.util.Log;
71import android.util.Range;
72import android.util.SparseIntArray;
73
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090074import com.android.internal.annotations.GuardedBy;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090075
76import libcore.net.event.NetworkEventDispatcher;
77
78import java.io.IOException;
79import java.io.UncheckedIOException;
80import java.lang.annotation.Retention;
81import java.lang.annotation.RetentionPolicy;
82import java.net.DatagramSocket;
83import java.net.InetAddress;
84import java.net.InetSocketAddress;
85import java.net.Socket;
86import java.util.ArrayList;
87import java.util.Collection;
88import java.util.HashMap;
89import java.util.List;
90import java.util.Map;
91import java.util.Objects;
92import java.util.concurrent.Executor;
93import java.util.concurrent.ExecutorService;
94import java.util.concurrent.Executors;
95import java.util.concurrent.RejectedExecutionException;
96
97/**
98 * Class that answers queries about the state of network connectivity. It also
99 * notifies applications when network connectivity changes.
100 * <p>
101 * The primary responsibilities of this class are to:
102 * <ol>
103 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
104 * <li>Send broadcast intents when network connectivity changes</li>
105 * <li>Attempt to "fail over" to another network when connectivity to a network
106 * is lost</li>
107 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
108 * state of the available networks</li>
109 * <li>Provide an API that allows applications to request and select networks for their data
110 * traffic</li>
111 * </ol>
112 */
113@SystemService(Context.CONNECTIVITY_SERVICE)
114public class ConnectivityManager {
115 private static final String TAG = "ConnectivityManager";
116 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
117
118 /**
119 * A change in network connectivity has occurred. A default connection has either
120 * been established or lost. The NetworkInfo for the affected network is
121 * sent as an extra; it should be consulted to see what kind of
122 * connectivity event occurred.
123 * <p/>
124 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
125 * broadcast if they declare the broadcast receiver in their manifest. Apps
126 * will still receive broadcasts if they register their
127 * {@link android.content.BroadcastReceiver} with
128 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
129 * and that context is still valid.
130 * <p/>
131 * If this is a connection that was the result of failing over from a
132 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
133 * set to true.
134 * <p/>
135 * For a loss of connectivity, if the connectivity manager is attempting
136 * to connect (or has already connected) to another network, the
137 * NetworkInfo for the new network is also passed as an extra. This lets
138 * any receivers of the broadcast know that they should not necessarily
139 * tell the user that no data traffic will be possible. Instead, the
140 * receiver should expect another broadcast soon, indicating either that
141 * the failover attempt succeeded (and so there is still overall data
142 * connectivity), or that the failover attempt failed, meaning that all
143 * connectivity has been lost.
144 * <p/>
145 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
146 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900147 * <p />
148 * Note that this broadcast is deprecated and generally tries to implement backwards
149 * compatibility with older versions of Android. As such, it may not reflect new
150 * capabilities of the system, like multiple networks being connected at the same
151 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900152 *
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 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800427 * This action includes a {@link Network} typed extra which is called
428 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
429 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900430 * @hide
431 */
lucaslincf6d4502021-03-04 17:09:51 +0800432 @SystemApi(client = MODULE_LIBRARIES)
433 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900434
435 /**
436 * Action used to display a dialog that asks the user whether to avoid a network that is no
437 * longer validated. This intent is used to start the dialog in settings via startActivity.
438 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800439 * This action includes a {@link Network} typed extra which is called
440 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
441 * validated.
442 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900443 * @hide
444 */
lucaslincf6d4502021-03-04 17:09:51 +0800445 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900446 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800447 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900448
449 /**
450 * Action used to display a dialog that asks the user whether to stay connected to a network
451 * that has not validated. This intent is used to start the dialog in settings via
452 * startActivity.
453 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800454 * This action includes a {@link Network} typed extra which is called
455 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
456 * connectivity.
457 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900458 * @hide
459 */
lucaslincf6d4502021-03-04 17:09:51 +0800460 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900461 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800462 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900463
464 /**
paulhub49c8422021-04-07 16:18:13 +0800465 * Clear DNS Cache Action: This is broadcast when networks have changed and old
466 * DNS entries should be cleared.
467 * @hide
468 */
469 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
470 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
471 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
472
473 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900474 * Invalid tethering type.
475 * @see #startTethering(int, boolean, OnStartTetheringCallback)
476 * @hide
477 */
478 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
479
480 /**
481 * Wifi tethering type.
482 * @see #startTethering(int, boolean, OnStartTetheringCallback)
483 * @hide
484 */
485 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900486 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900487
488 /**
489 * USB tethering type.
490 * @see #startTethering(int, boolean, OnStartTetheringCallback)
491 * @hide
492 */
493 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900494 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900495
496 /**
497 * Bluetooth tethering type.
498 * @see #startTethering(int, boolean, OnStartTetheringCallback)
499 * @hide
500 */
501 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900502 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900503
504 /**
505 * Wifi P2p tethering type.
506 * Wifi P2p tethering is set through events automatically, and don't
507 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
508 * @hide
509 */
510 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
511
512 /**
513 * Extra used for communicating with the TetherService. Includes the type of tethering to
514 * enable if any.
515 * @hide
516 */
517 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
518
519 /**
520 * Extra used for communicating with the TetherService. Includes the type of tethering for
521 * which to cancel provisioning.
522 * @hide
523 */
524 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
525
526 /**
527 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
528 * provisioning.
529 * @hide
530 */
531 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
532
533 /**
534 * Tells the TetherService to run a provision check now.
535 * @hide
536 */
537 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
538
539 /**
540 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
541 * which will receive provisioning results. Can be left empty.
542 * @hide
543 */
544 public static final String EXTRA_PROVISION_CALLBACK =
545 TetheringConstants.EXTRA_PROVISION_CALLBACK;
546
547 /**
548 * The absence of a connection type.
549 * @hide
550 */
551 @SystemApi
552 public static final int TYPE_NONE = -1;
553
554 /**
555 * A Mobile data connection. Devices may support more than one.
556 *
557 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
558 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
559 * appropriate network. {@see NetworkCapabilities} for supported transports.
560 */
561 @Deprecated
562 public static final int TYPE_MOBILE = 0;
563
564 /**
565 * A WIFI data connection. Devices may support more than one.
566 *
567 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
568 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
569 * appropriate network. {@see NetworkCapabilities} for supported transports.
570 */
571 @Deprecated
572 public static final int TYPE_WIFI = 1;
573
574 /**
575 * An MMS-specific Mobile data connection. This network type may use the
576 * same network interface as {@link #TYPE_MOBILE} or it may use a different
577 * one. This is used by applications needing to talk to the carrier's
578 * Multimedia Messaging Service servers.
579 *
580 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
581 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
582 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
583 */
584 @Deprecated
585 public static final int TYPE_MOBILE_MMS = 2;
586
587 /**
588 * A SUPL-specific Mobile data connection. This network type may use the
589 * same network interface as {@link #TYPE_MOBILE} or it may use a different
590 * one. This is used by applications needing to talk to the carrier's
591 * Secure User Plane Location servers for help locating the device.
592 *
593 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
594 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
595 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
596 */
597 @Deprecated
598 public static final int TYPE_MOBILE_SUPL = 3;
599
600 /**
601 * A DUN-specific Mobile data connection. This network type may use the
602 * same network interface as {@link #TYPE_MOBILE} or it may use a different
603 * one. This is sometimes by the system when setting up an upstream connection
604 * for tethering so that the carrier is aware of DUN traffic.
605 *
606 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
607 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
608 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
609 */
610 @Deprecated
611 public static final int TYPE_MOBILE_DUN = 4;
612
613 /**
614 * A High Priority Mobile data connection. This network type uses the
615 * same network interface as {@link #TYPE_MOBILE} but the routing setup
616 * is different.
617 *
618 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
619 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
620 * appropriate network. {@see NetworkCapabilities} for supported transports.
621 */
622 @Deprecated
623 public static final int TYPE_MOBILE_HIPRI = 5;
624
625 /**
626 * A WiMAX data connection.
627 *
628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
630 * appropriate network. {@see NetworkCapabilities} for supported transports.
631 */
632 @Deprecated
633 public static final int TYPE_WIMAX = 6;
634
635 /**
636 * A Bluetooth data connection.
637 *
638 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
639 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
640 * appropriate network. {@see NetworkCapabilities} for supported transports.
641 */
642 @Deprecated
643 public static final int TYPE_BLUETOOTH = 7;
644
645 /**
646 * Fake data connection. This should not be used on shipping devices.
647 * @deprecated This is not used any more.
648 */
649 @Deprecated
650 public static final int TYPE_DUMMY = 8;
651
652 /**
653 * An Ethernet data connection.
654 *
655 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
656 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
657 * appropriate network. {@see NetworkCapabilities} for supported transports.
658 */
659 @Deprecated
660 public static final int TYPE_ETHERNET = 9;
661
662 /**
663 * Over the air Administration.
664 * @deprecated Use {@link NetworkCapabilities} instead.
665 * {@hide}
666 */
667 @Deprecated
668 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
669 public static final int TYPE_MOBILE_FOTA = 10;
670
671 /**
672 * IP Multimedia Subsystem.
673 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
674 * {@hide}
675 */
676 @Deprecated
677 @UnsupportedAppUsage
678 public static final int TYPE_MOBILE_IMS = 11;
679
680 /**
681 * Carrier Branded Services.
682 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
683 * {@hide}
684 */
685 @Deprecated
686 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
687 public static final int TYPE_MOBILE_CBS = 12;
688
689 /**
690 * A Wi-Fi p2p connection. Only requesting processes will have access to
691 * the peers connected.
692 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
693 * {@hide}
694 */
695 @Deprecated
696 @SystemApi
697 public static final int TYPE_WIFI_P2P = 13;
698
699 /**
700 * The network to use for initially attaching to the network
701 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
702 * {@hide}
703 */
704 @Deprecated
705 @UnsupportedAppUsage
706 public static final int TYPE_MOBILE_IA = 14;
707
708 /**
709 * Emergency PDN connection for emergency services. This
710 * may include IMS and MMS in emergency situations.
711 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
712 * {@hide}
713 */
714 @Deprecated
715 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
716 public static final int TYPE_MOBILE_EMERGENCY = 15;
717
718 /**
719 * The network that uses proxy to achieve connectivity.
720 * @deprecated Use {@link NetworkCapabilities} instead.
721 * {@hide}
722 */
723 @Deprecated
724 @SystemApi
725 public static final int TYPE_PROXY = 16;
726
727 /**
728 * A virtual network using one or more native bearers.
729 * It may or may not be providing security services.
730 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
731 */
732 @Deprecated
733 public static final int TYPE_VPN = 17;
734
735 /**
736 * A network that is exclusively meant to be used for testing
737 *
738 * @deprecated Use {@link NetworkCapabilities} instead.
739 * @hide
740 */
741 @Deprecated
742 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
743
744 /**
745 * @deprecated Use {@link NetworkCapabilities} instead.
746 * @hide
747 */
748 @Deprecated
749 @Retention(RetentionPolicy.SOURCE)
750 @IntDef(prefix = { "TYPE_" }, value = {
751 TYPE_NONE,
752 TYPE_MOBILE,
753 TYPE_WIFI,
754 TYPE_MOBILE_MMS,
755 TYPE_MOBILE_SUPL,
756 TYPE_MOBILE_DUN,
757 TYPE_MOBILE_HIPRI,
758 TYPE_WIMAX,
759 TYPE_BLUETOOTH,
760 TYPE_DUMMY,
761 TYPE_ETHERNET,
762 TYPE_MOBILE_FOTA,
763 TYPE_MOBILE_IMS,
764 TYPE_MOBILE_CBS,
765 TYPE_WIFI_P2P,
766 TYPE_MOBILE_IA,
767 TYPE_MOBILE_EMERGENCY,
768 TYPE_PROXY,
769 TYPE_VPN,
770 TYPE_TEST
771 })
772 public @interface LegacyNetworkType {}
773
774 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
775 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
776 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
777 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
778 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
779
780 /** {@hide} */
781 public static final int MAX_RADIO_TYPE = TYPE_TEST;
782
783 /** {@hide} */
784 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
785
786 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
787
788 /**
789 * If you want to set the default network preference,you can directly
790 * change the networkAttributes array in framework's config.xml.
791 *
792 * @deprecated Since we support so many more networks now, the single
793 * network default network preference can't really express
794 * the hierarchy. Instead, the default is defined by the
795 * networkAttributes in config.xml. You can determine
796 * the current value by calling {@link #getNetworkPreference()}
797 * from an App.
798 */
799 @Deprecated
800 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
801
802 /**
803 * @hide
804 */
805 public static final int REQUEST_ID_UNSET = 0;
806
807 /**
808 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
809 * This allows to distinguish when unregistering NetworkCallbacks those that were never
810 * registered from those that were already unregistered.
811 * @hide
812 */
813 private static final NetworkRequest ALREADY_UNREGISTERED =
814 new NetworkRequest.Builder().clearCapabilities().build();
815
816 /**
817 * A NetID indicating no Network is selected.
818 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
819 * @hide
820 */
821 public static final int NETID_UNSET = 0;
822
823 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000824 * Flag to indicate that an app is not subject to any restrictions that could result in its
825 * network access blocked.
826 *
827 * @hide
828 */
829 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
830 public static final int BLOCKED_REASON_NONE = 0;
831
832 /**
833 * Flag to indicate that an app is subject to Battery saver restrictions that would
834 * result in its network access being blocked.
835 *
836 * @hide
837 */
838 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
839 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
840
841 /**
842 * Flag to indicate that an app is subject to Doze restrictions that would
843 * result in its network access being blocked.
844 *
845 * @hide
846 */
847 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
848 public static final int BLOCKED_REASON_DOZE = 1 << 1;
849
850 /**
851 * Flag to indicate that an app is subject to App Standby restrictions that would
852 * result in its network access being blocked.
853 *
854 * @hide
855 */
856 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
857 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
858
859 /**
860 * Flag to indicate that an app is subject to Restricted mode restrictions that would
861 * result in its network access being blocked.
862 *
863 * @hide
864 */
865 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
866 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
867
868 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900869 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
870 * is not currently connected.
871 *
872 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
873 *
874 * @hide
875 */
876 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
877 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
878
879 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000880 * Flag to indicate that an app is subject to Data saver restrictions that would
881 * result in its metered network access being blocked.
882 *
883 * @hide
884 */
885 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
886 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
887
888 /**
889 * Flag to indicate that an app is subject to user restrictions that would
890 * result in its metered network access being blocked.
891 *
892 * @hide
893 */
894 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
895 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
896
897 /**
898 * Flag to indicate that an app is subject to Device admin restrictions that would
899 * result in its metered network access being blocked.
900 *
901 * @hide
902 */
903 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
904 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
905
906 /**
907 * @hide
908 */
909 @Retention(RetentionPolicy.SOURCE)
910 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
911 BLOCKED_REASON_NONE,
912 BLOCKED_REASON_BATTERY_SAVER,
913 BLOCKED_REASON_DOZE,
914 BLOCKED_REASON_APP_STANDBY,
915 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900916 BLOCKED_REASON_LOCKDOWN_VPN,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000917 BLOCKED_METERED_REASON_DATA_SAVER,
918 BLOCKED_METERED_REASON_USER_RESTRICTED,
919 BLOCKED_METERED_REASON_ADMIN_DISABLED,
920 })
921 public @interface BlockedReason {}
922
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900923 /**
924 * Set of blocked reasons that are only applicable on metered networks.
925 *
926 * @hide
927 */
928 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
929 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
930
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900931 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
932 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900933
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900934 /**
markchiene1561fa2021-12-09 22:00:56 +0800935 * Firewall chain for device idle (doze mode).
936 * Allowlist of apps that have network access in device idle.
937 * @hide
938 */
939 @SystemApi(client = MODULE_LIBRARIES)
940 public static final int FIREWALL_CHAIN_DOZABLE = 1;
941
942 /**
943 * Firewall chain used for app standby.
944 * Denylist of apps that do not have network access.
945 * @hide
946 */
947 @SystemApi(client = MODULE_LIBRARIES)
948 public static final int FIREWALL_CHAIN_STANDBY = 2;
949
950 /**
951 * Firewall chain used for battery saver.
952 * Allowlist of apps that have network access when battery saver is on.
953 * @hide
954 */
955 @SystemApi(client = MODULE_LIBRARIES)
956 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
957
958 /**
959 * Firewall chain used for restricted networking mode.
960 * Allowlist of apps that have access in restricted networking mode.
961 * @hide
962 */
963 @SystemApi(client = MODULE_LIBRARIES)
964 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
965
966 /** @hide */
967 @Retention(RetentionPolicy.SOURCE)
968 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
969 FIREWALL_CHAIN_DOZABLE,
970 FIREWALL_CHAIN_STANDBY,
971 FIREWALL_CHAIN_POWERSAVE,
972 FIREWALL_CHAIN_RESTRICTED
973 })
974 public @interface FirewallChain {}
975
976 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900977 * A kludge to facilitate static access where a Context pointer isn't available, like in the
978 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
979 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
980 * methods that take a Context argument.
981 */
982 private static ConnectivityManager sInstance;
983
984 private final Context mContext;
985
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +0900986 @GuardedBy("mTetheringEventCallbacks")
987 private TetheringManager mTetheringManager;
988
989 private TetheringManager getTetheringManager() {
990 synchronized (mTetheringEventCallbacks) {
991 if (mTetheringManager == null) {
992 mTetheringManager = mContext.getSystemService(TetheringManager.class);
993 }
994 return mTetheringManager;
995 }
996 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900997
998 /**
999 * Tests if a given integer represents a valid network type.
1000 * @param networkType the type to be tested
1001 * @return a boolean. {@code true} if the type is valid, else {@code false}
1002 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1003 * validate a network type.
1004 */
1005 @Deprecated
1006 public static boolean isNetworkTypeValid(int networkType) {
1007 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1008 }
1009
1010 /**
1011 * Returns a non-localized string representing a given network type.
1012 * ONLY used for debugging output.
1013 * @param type the type needing naming
1014 * @return a String for the given type, or a string version of the type ("87")
1015 * if no name is known.
1016 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1017 * {@hide}
1018 */
1019 @Deprecated
1020 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1021 public static String getNetworkTypeName(int type) {
1022 switch (type) {
1023 case TYPE_NONE:
1024 return "NONE";
1025 case TYPE_MOBILE:
1026 return "MOBILE";
1027 case TYPE_WIFI:
1028 return "WIFI";
1029 case TYPE_MOBILE_MMS:
1030 return "MOBILE_MMS";
1031 case TYPE_MOBILE_SUPL:
1032 return "MOBILE_SUPL";
1033 case TYPE_MOBILE_DUN:
1034 return "MOBILE_DUN";
1035 case TYPE_MOBILE_HIPRI:
1036 return "MOBILE_HIPRI";
1037 case TYPE_WIMAX:
1038 return "WIMAX";
1039 case TYPE_BLUETOOTH:
1040 return "BLUETOOTH";
1041 case TYPE_DUMMY:
1042 return "DUMMY";
1043 case TYPE_ETHERNET:
1044 return "ETHERNET";
1045 case TYPE_MOBILE_FOTA:
1046 return "MOBILE_FOTA";
1047 case TYPE_MOBILE_IMS:
1048 return "MOBILE_IMS";
1049 case TYPE_MOBILE_CBS:
1050 return "MOBILE_CBS";
1051 case TYPE_WIFI_P2P:
1052 return "WIFI_P2P";
1053 case TYPE_MOBILE_IA:
1054 return "MOBILE_IA";
1055 case TYPE_MOBILE_EMERGENCY:
1056 return "MOBILE_EMERGENCY";
1057 case TYPE_PROXY:
1058 return "PROXY";
1059 case TYPE_VPN:
1060 return "VPN";
1061 default:
1062 return Integer.toString(type);
1063 }
1064 }
1065
1066 /**
1067 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001068 */
lucaslin10774b72021-03-17 14:16:01 +08001069 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001070 public void systemReady() {
1071 try {
1072 mService.systemReady();
1073 } catch (RemoteException e) {
1074 throw e.rethrowFromSystemServer();
1075 }
1076 }
1077
1078 /**
1079 * Checks if a given type uses the cellular data connection.
1080 * This should be replaced in the future by a network property.
1081 * @param networkType the type to check
1082 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1083 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1084 * {@hide}
1085 */
1086 @Deprecated
1087 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1088 public static boolean isNetworkTypeMobile(int networkType) {
1089 switch (networkType) {
1090 case TYPE_MOBILE:
1091 case TYPE_MOBILE_MMS:
1092 case TYPE_MOBILE_SUPL:
1093 case TYPE_MOBILE_DUN:
1094 case TYPE_MOBILE_HIPRI:
1095 case TYPE_MOBILE_FOTA:
1096 case TYPE_MOBILE_IMS:
1097 case TYPE_MOBILE_CBS:
1098 case TYPE_MOBILE_IA:
1099 case TYPE_MOBILE_EMERGENCY:
1100 return true;
1101 default:
1102 return false;
1103 }
1104 }
1105
1106 /**
1107 * Checks if the given network type is backed by a Wi-Fi radio.
1108 *
1109 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1110 * @hide
1111 */
1112 @Deprecated
1113 public static boolean isNetworkTypeWifi(int networkType) {
1114 switch (networkType) {
1115 case TYPE_WIFI:
1116 case TYPE_WIFI_P2P:
1117 return true;
1118 default:
1119 return false;
1120 }
1121 }
1122
1123 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001124 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1125 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001126 * Specify that the traffic for this user should by follow the default rules.
1127 * @hide
1128 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001129 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001130 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1131
1132 /**
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001133 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1134 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001135 * Specify that the traffic for this user should by default go on a network with
1136 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1137 * if no such network is available.
1138 * @hide
1139 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001140 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001141 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1142
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001143 /**
1144 * Preference for {@link ProfileNetworkPreference#setPreference(int)}.
1145 * {@see #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1146 * Specify that the traffic for this user should by default go on a network with
1147 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
1148 * should not go on the system default network
1149 * @hide
1150 */
1151 @SystemApi(client = MODULE_LIBRARIES)
1152 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1153
Chalard Jeanad565e22021-02-25 17:23:40 +09001154 /** @hide */
1155 @Retention(RetentionPolicy.SOURCE)
1156 @IntDef(value = {
1157 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001158 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1159 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001160 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001161 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001162 }
1163
1164 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001165 * Specifies the preferred network type. When the device has more
1166 * than one type available the preferred network type will be used.
1167 *
1168 * @param preference the network type to prefer over all others. It is
1169 * unspecified what happens to the old preferred network in the
1170 * overall ordering.
1171 * @deprecated Functionality has been removed as it no longer makes sense,
1172 * with many more than two networks - we'd need an array to express
1173 * preference. Instead we use dynamic network properties of
1174 * the networks to describe their precedence.
1175 */
1176 @Deprecated
1177 public void setNetworkPreference(int preference) {
1178 }
1179
1180 /**
1181 * Retrieves the current preferred network type.
1182 *
1183 * @return an integer representing the preferred network type
1184 *
1185 * @deprecated Functionality has been removed as it no longer makes sense,
1186 * with many more than two networks - we'd need an array to express
1187 * preference. Instead we use dynamic network properties of
1188 * the networks to describe their precedence.
1189 */
1190 @Deprecated
1191 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1192 public int getNetworkPreference() {
1193 return TYPE_NONE;
1194 }
1195
1196 /**
1197 * Returns details about the currently active default data network. When
1198 * connected, this network is the default route for outgoing connections.
1199 * You should always check {@link NetworkInfo#isConnected()} before initiating
1200 * network traffic. This may return {@code null} when there is no default
1201 * network.
1202 * Note that if the default network is a VPN, this method will return the
1203 * NetworkInfo for one of its underlying networks instead, or null if the
1204 * VPN agent did not specify any. Apps interested in learning about VPNs
1205 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1206 *
1207 * @return a {@link NetworkInfo} object for the current default network
1208 * or {@code null} if no default network is currently active
1209 * @deprecated See {@link NetworkInfo}.
1210 */
1211 @Deprecated
1212 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1213 @Nullable
1214 public NetworkInfo getActiveNetworkInfo() {
1215 try {
1216 return mService.getActiveNetworkInfo();
1217 } catch (RemoteException e) {
1218 throw e.rethrowFromSystemServer();
1219 }
1220 }
1221
1222 /**
1223 * Returns a {@link Network} object corresponding to the currently active
1224 * default data network. In the event that the current active default data
1225 * network disconnects, the returned {@code Network} object will no longer
1226 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001227 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001228 *
1229 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001230 * {@code null} if no default network is currently active or if
1231 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001232 */
1233 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1234 @Nullable
1235 public Network getActiveNetwork() {
1236 try {
1237 return mService.getActiveNetwork();
1238 } catch (RemoteException e) {
1239 throw e.rethrowFromSystemServer();
1240 }
1241 }
1242
1243 /**
1244 * Returns a {@link Network} object corresponding to the currently active
1245 * default data network for a specific UID. In the event that the default data
1246 * network disconnects, the returned {@code Network} object will no longer
1247 * be usable. This will return {@code null} when there is no default
1248 * network for the UID.
1249 *
1250 * @return a {@link Network} object for the current default network for the
1251 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001252 *
1253 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001254 */
1255 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1256 @Nullable
1257 public Network getActiveNetworkForUid(int uid) {
1258 return getActiveNetworkForUid(uid, false);
1259 }
1260
1261 /** {@hide} */
1262 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1263 try {
1264 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1265 } catch (RemoteException e) {
1266 throw e.rethrowFromSystemServer();
1267 }
1268 }
1269
1270 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001271 * Adds or removes a requirement for given UID ranges to use the VPN.
1272 *
1273 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1274 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1275 * otherwise have permission to bypass the VPN (e.g., because they have the
1276 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1277 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1278 * set to {@code false}, a previously-added restriction is removed.
1279 * <p>
1280 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1281 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1282 * remove a previously-added range, the exact range must be removed as is.
1283 * <p>
1284 * The changes are applied asynchronously and may not have been applied by the time the method
1285 * returns. Apps will be notified about any changes that apply to them via
1286 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1287 * effect.
1288 * <p>
1289 * This method should be called only by the VPN code.
1290 *
1291 * @param ranges the UID ranges to restrict
1292 * @param requireVpn whether the specified UID ranges must use a VPN
1293 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001294 * @hide
1295 */
1296 @RequiresPermission(anyOf = {
1297 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001298 android.Manifest.permission.NETWORK_STACK,
1299 android.Manifest.permission.NETWORK_SETTINGS})
1300 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001301 public void setRequireVpnForUids(boolean requireVpn,
1302 @NonNull Collection<Range<Integer>> ranges) {
1303 Objects.requireNonNull(ranges);
1304 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1305 // This method is not necessarily expected to be used outside the system server, so
1306 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1307 // stack process, or by tests.
1308 UidRange[] rangesArray = new UidRange[ranges.size()];
1309 int index = 0;
1310 for (Range<Integer> range : ranges) {
1311 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1312 }
1313 try {
1314 mService.setRequireVpnForUids(requireVpn, rangesArray);
1315 } catch (RemoteException e) {
1316 throw e.rethrowFromSystemServer();
1317 }
1318 }
1319
1320 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001321 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1322 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1323 * but is still supported for backwards compatibility.
1324 * <p>
1325 * This type of VPN is assumed always to use the system default network, and must always declare
1326 * exactly one underlying network, which is the network that was the default when the VPN
1327 * connected.
1328 * <p>
1329 * Calling this method with {@code true} enables legacy behaviour, specifically:
1330 * <ul>
1331 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1332 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1333 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1334 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1335 * underlying the VPN.</li>
1336 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1337 * similarly replaced by the VPN network state.</li>
1338 * <li>Information on current network interfaces passed to NetworkStatsService will not
1339 * include any VPN interfaces.</li>
1340 * </ul>
1341 *
1342 * @param enabled whether legacy lockdown VPN is enabled or disabled
1343 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001344 * @hide
1345 */
1346 @RequiresPermission(anyOf = {
1347 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001348 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001349 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001350 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001351 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1352 try {
1353 mService.setLegacyLockdownVpnEnabled(enabled);
1354 } catch (RemoteException e) {
1355 throw e.rethrowFromSystemServer();
1356 }
1357 }
1358
1359 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001360 * Returns details about the currently active default data network
1361 * for a given uid. This is for internal use only to avoid spying
1362 * other apps.
1363 *
1364 * @return a {@link NetworkInfo} object for the current default network
1365 * for the given uid or {@code null} if no default network is
1366 * available for the specified uid.
1367 *
1368 * {@hide}
1369 */
1370 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1371 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1372 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1373 return getActiveNetworkInfoForUid(uid, false);
1374 }
1375
1376 /** {@hide} */
1377 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1378 try {
1379 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1380 } catch (RemoteException e) {
1381 throw e.rethrowFromSystemServer();
1382 }
1383 }
1384
1385 /**
1386 * Returns connection status information about a particular
1387 * network type.
1388 *
1389 * @param networkType integer specifying which networkType in
1390 * which you're interested.
1391 * @return a {@link NetworkInfo} object for the requested
1392 * network type or {@code null} if the type is not
1393 * supported by the device. If {@code networkType} is
1394 * TYPE_VPN and a VPN is active for the calling app,
1395 * then this method will try to return one of the
1396 * underlying networks for the VPN or null if the
1397 * VPN agent didn't specify any.
1398 *
1399 * @deprecated This method does not support multiple connected networks
1400 * of the same type. Use {@link #getAllNetworks} and
1401 * {@link #getNetworkInfo(android.net.Network)} instead.
1402 */
1403 @Deprecated
1404 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1405 @Nullable
1406 public NetworkInfo getNetworkInfo(int networkType) {
1407 try {
1408 return mService.getNetworkInfo(networkType);
1409 } catch (RemoteException e) {
1410 throw e.rethrowFromSystemServer();
1411 }
1412 }
1413
1414 /**
1415 * Returns connection status information about a particular
1416 * Network.
1417 *
1418 * @param network {@link Network} specifying which network
1419 * in which you're interested.
1420 * @return a {@link NetworkInfo} object for the requested
1421 * network or {@code null} if the {@code Network}
1422 * is not valid.
1423 * @deprecated See {@link NetworkInfo}.
1424 */
1425 @Deprecated
1426 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1427 @Nullable
1428 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1429 return getNetworkInfoForUid(network, Process.myUid(), false);
1430 }
1431
1432 /** {@hide} */
1433 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1434 try {
1435 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1436 } catch (RemoteException e) {
1437 throw e.rethrowFromSystemServer();
1438 }
1439 }
1440
1441 /**
1442 * Returns connection status information about all network
1443 * types supported by the device.
1444 *
1445 * @return an array of {@link NetworkInfo} objects. Check each
1446 * {@link NetworkInfo#getType} for which type each applies.
1447 *
1448 * @deprecated This method does not support multiple connected networks
1449 * of the same type. Use {@link #getAllNetworks} and
1450 * {@link #getNetworkInfo(android.net.Network)} instead.
1451 */
1452 @Deprecated
1453 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1454 @NonNull
1455 public NetworkInfo[] getAllNetworkInfo() {
1456 try {
1457 return mService.getAllNetworkInfo();
1458 } catch (RemoteException e) {
1459 throw e.rethrowFromSystemServer();
1460 }
1461 }
1462
1463 /**
junyulaib1211372021-03-03 12:09:05 +08001464 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1465 * connected.
1466 * @hide
1467 */
1468 @SystemApi(client = MODULE_LIBRARIES)
1469 @RequiresPermission(anyOf = {
1470 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1471 android.Manifest.permission.NETWORK_STACK,
1472 android.Manifest.permission.NETWORK_SETTINGS})
1473 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001474 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001475 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001476 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001477 } catch (RemoteException e) {
1478 throw e.rethrowFromSystemServer();
1479 }
1480 }
1481
1482 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001483 * Returns the {@link Network} object currently serving a given type, or
1484 * null if the given type is not connected.
1485 *
1486 * @hide
1487 * @deprecated This method does not support multiple connected networks
1488 * of the same type. Use {@link #getAllNetworks} and
1489 * {@link #getNetworkInfo(android.net.Network)} instead.
1490 */
1491 @Deprecated
1492 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1493 @UnsupportedAppUsage
1494 public Network getNetworkForType(int networkType) {
1495 try {
1496 return mService.getNetworkForType(networkType);
1497 } catch (RemoteException e) {
1498 throw e.rethrowFromSystemServer();
1499 }
1500 }
1501
1502 /**
1503 * Returns an array of all {@link Network} currently tracked by the
1504 * framework.
1505 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001506 * @deprecated This method does not provide any notification of network state changes, forcing
1507 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1508 * Apps should use methods such as
1509 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1510 * Apps that desire to obtain information about networks that do not apply to them
1511 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1512 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001513 * @return an array of {@link Network} objects.
1514 */
1515 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1516 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001517 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001518 public Network[] getAllNetworks() {
1519 try {
1520 return mService.getAllNetworks();
1521 } catch (RemoteException e) {
1522 throw e.rethrowFromSystemServer();
1523 }
1524 }
1525
1526 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001527 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001528 * the Networks that applications run by the given user will use by default.
1529 * @hide
1530 */
1531 @UnsupportedAppUsage
1532 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1533 try {
1534 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001535 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001536 } catch (RemoteException e) {
1537 throw e.rethrowFromSystemServer();
1538 }
1539 }
1540
1541 /**
1542 * Returns the IP information for the current default network.
1543 *
1544 * @return a {@link LinkProperties} object describing the IP info
1545 * for the current default network, or {@code null} if there
1546 * is no current default network.
1547 *
1548 * {@hide}
1549 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1550 * value of {@link #getActiveNetwork()} instead. In particular,
1551 * this method will return non-null LinkProperties even if the
1552 * app is blocked by policy from using this network.
1553 */
1554 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1555 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1556 public LinkProperties getActiveLinkProperties() {
1557 try {
1558 return mService.getActiveLinkProperties();
1559 } catch (RemoteException e) {
1560 throw e.rethrowFromSystemServer();
1561 }
1562 }
1563
1564 /**
1565 * Returns the IP information for a given network type.
1566 *
1567 * @param networkType the network type of interest.
1568 * @return a {@link LinkProperties} object describing the IP info
1569 * for the given networkType, or {@code null} if there is
1570 * no current default network.
1571 *
1572 * {@hide}
1573 * @deprecated This method does not support multiple connected networks
1574 * of the same type. Use {@link #getAllNetworks},
1575 * {@link #getNetworkInfo(android.net.Network)}, and
1576 * {@link #getLinkProperties(android.net.Network)} instead.
1577 */
1578 @Deprecated
1579 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1580 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1581 public LinkProperties getLinkProperties(int networkType) {
1582 try {
1583 return mService.getLinkPropertiesForType(networkType);
1584 } catch (RemoteException e) {
1585 throw e.rethrowFromSystemServer();
1586 }
1587 }
1588
1589 /**
1590 * Get the {@link LinkProperties} for the given {@link Network}. This
1591 * will return {@code null} if the network is unknown.
1592 *
1593 * @param network The {@link Network} object identifying the network in question.
1594 * @return The {@link LinkProperties} for the network, or {@code null}.
1595 */
1596 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1597 @Nullable
1598 public LinkProperties getLinkProperties(@Nullable Network network) {
1599 try {
1600 return mService.getLinkProperties(network);
1601 } catch (RemoteException e) {
1602 throw e.rethrowFromSystemServer();
1603 }
1604 }
1605
1606 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001607 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Chalard Jean070bdd42021-04-30 20:22:10 +09001608 * will return {@code null} if the network is unknown or if the |network| argument is null.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001609 *
Roshan Piuse08bc182020-12-22 15:10:42 -08001610 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1611 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1612 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1613 * this location sensitive information (subject to app's location permissions) will be
1614 * noted by system. To include any location sensitive data in {@link TransportInfo},
1615 * use a {@link NetworkCallback} with
1616 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1617 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001618 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001619 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001620 */
1621 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1622 @Nullable
1623 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1624 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001625 return mService.getNetworkCapabilities(
1626 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001627 } catch (RemoteException e) {
1628 throw e.rethrowFromSystemServer();
1629 }
1630 }
1631
1632 /**
1633 * Gets a URL that can be used for resolving whether a captive portal is present.
1634 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1635 * portal is present.
1636 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1637 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1638 *
1639 * The system network validation may be using different strategies to detect captive portals,
1640 * so this method does not necessarily return a URL used by the system. It only returns a URL
1641 * that may be relevant for other components trying to detect captive portals.
1642 *
1643 * @hide
1644 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1645 * system.
1646 */
1647 @Deprecated
1648 @SystemApi
1649 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1650 public String getCaptivePortalServerUrl() {
1651 try {
1652 return mService.getCaptivePortalServerUrl();
1653 } catch (RemoteException e) {
1654 throw e.rethrowFromSystemServer();
1655 }
1656 }
1657
1658 /**
1659 * Tells the underlying networking system that the caller wants to
1660 * begin using the named feature. The interpretation of {@code feature}
1661 * is completely up to each networking implementation.
1662 *
1663 * <p>This method requires the caller to hold either the
1664 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1665 * or the ability to modify system settings as determined by
1666 * {@link android.provider.Settings.System#canWrite}.</p>
1667 *
1668 * @param networkType specifies which network the request pertains to
1669 * @param feature the name of the feature to be used
1670 * @return an integer value representing the outcome of the request.
1671 * The interpretation of this value is specific to each networking
1672 * implementation+feature combination, except that the value {@code -1}
1673 * always indicates failure.
1674 *
1675 * @deprecated Deprecated in favor of the cleaner
1676 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1677 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1678 * throw {@code UnsupportedOperationException} if called.
1679 * @removed
1680 */
1681 @Deprecated
1682 public int startUsingNetworkFeature(int networkType, String feature) {
1683 checkLegacyRoutingApiAccess();
1684 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1685 if (netCap == null) {
1686 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1687 feature);
1688 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1689 }
1690
1691 NetworkRequest request = null;
1692 synchronized (sLegacyRequests) {
1693 LegacyRequest l = sLegacyRequests.get(netCap);
1694 if (l != null) {
1695 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1696 renewRequestLocked(l);
1697 if (l.currentNetwork != null) {
1698 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1699 } else {
1700 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1701 }
1702 }
1703
1704 request = requestNetworkForFeatureLocked(netCap);
1705 }
1706 if (request != null) {
1707 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1708 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1709 } else {
1710 Log.d(TAG, " request Failed");
1711 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1712 }
1713 }
1714
1715 /**
1716 * Tells the underlying networking system that the caller is finished
1717 * using the named feature. The interpretation of {@code feature}
1718 * is completely up to each networking implementation.
1719 *
1720 * <p>This method requires the caller to hold either the
1721 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1722 * or the ability to modify system settings as determined by
1723 * {@link android.provider.Settings.System#canWrite}.</p>
1724 *
1725 * @param networkType specifies which network the request pertains to
1726 * @param feature the name of the feature that is no longer needed
1727 * @return an integer value representing the outcome of the request.
1728 * The interpretation of this value is specific to each networking
1729 * implementation+feature combination, except that the value {@code -1}
1730 * always indicates failure.
1731 *
1732 * @deprecated Deprecated in favor of the cleaner
1733 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1734 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1735 * throw {@code UnsupportedOperationException} if called.
1736 * @removed
1737 */
1738 @Deprecated
1739 public int stopUsingNetworkFeature(int networkType, String feature) {
1740 checkLegacyRoutingApiAccess();
1741 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1742 if (netCap == null) {
1743 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1744 feature);
1745 return -1;
1746 }
1747
1748 if (removeRequestForFeature(netCap)) {
1749 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1750 }
1751 return 1;
1752 }
1753
1754 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1755 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1756 if (networkType == TYPE_MOBILE) {
1757 switch (feature) {
1758 case "enableCBS":
1759 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1760 case "enableDUN":
1761 case "enableDUNAlways":
1762 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1763 case "enableFOTA":
1764 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1765 case "enableHIPRI":
1766 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1767 case "enableIMS":
1768 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1769 case "enableMMS":
1770 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1771 case "enableSUPL":
1772 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1773 default:
1774 return null;
1775 }
1776 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1777 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1778 }
1779 return null;
1780 }
1781
1782 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1783 if (netCap == null) return TYPE_NONE;
1784 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1785 return TYPE_MOBILE_CBS;
1786 }
1787 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1788 return TYPE_MOBILE_IMS;
1789 }
1790 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1791 return TYPE_MOBILE_FOTA;
1792 }
1793 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1794 return TYPE_MOBILE_DUN;
1795 }
1796 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1797 return TYPE_MOBILE_SUPL;
1798 }
1799 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1800 return TYPE_MOBILE_MMS;
1801 }
1802 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1803 return TYPE_MOBILE_HIPRI;
1804 }
1805 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1806 return TYPE_WIFI_P2P;
1807 }
1808 return TYPE_NONE;
1809 }
1810
1811 private static class LegacyRequest {
1812 NetworkCapabilities networkCapabilities;
1813 NetworkRequest networkRequest;
1814 int expireSequenceNumber;
1815 Network currentNetwork;
1816 int delay = -1;
1817
1818 private void clearDnsBinding() {
1819 if (currentNetwork != null) {
1820 currentNetwork = null;
1821 setProcessDefaultNetworkForHostResolution(null);
1822 }
1823 }
1824
1825 NetworkCallback networkCallback = new NetworkCallback() {
1826 @Override
1827 public void onAvailable(Network network) {
1828 currentNetwork = network;
1829 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1830 setProcessDefaultNetworkForHostResolution(network);
1831 }
1832 @Override
1833 public void onLost(Network network) {
1834 if (network.equals(currentNetwork)) clearDnsBinding();
1835 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1836 }
1837 };
1838 }
1839
1840 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1841 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1842 new HashMap<>();
1843
1844 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1845 synchronized (sLegacyRequests) {
1846 LegacyRequest l = sLegacyRequests.get(netCap);
1847 if (l != null) return l.networkRequest;
1848 }
1849 return null;
1850 }
1851
1852 private void renewRequestLocked(LegacyRequest l) {
1853 l.expireSequenceNumber++;
1854 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1855 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1856 }
1857
1858 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1859 int ourSeqNum = -1;
1860 synchronized (sLegacyRequests) {
1861 LegacyRequest l = sLegacyRequests.get(netCap);
1862 if (l == null) return;
1863 ourSeqNum = l.expireSequenceNumber;
1864 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
1865 }
1866 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1867 }
1868
1869 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1870 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1871 int delay = -1;
1872 int type = legacyTypeForNetworkCapabilities(netCap);
1873 try {
1874 delay = mService.getRestoreDefaultNetworkDelay(type);
1875 } catch (RemoteException e) {
1876 throw e.rethrowFromSystemServer();
1877 }
1878 LegacyRequest l = new LegacyRequest();
1879 l.networkCapabilities = netCap;
1880 l.delay = delay;
1881 l.expireSequenceNumber = 0;
1882 l.networkRequest = sendRequestForNetwork(
1883 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
1884 if (l.networkRequest == null) return null;
1885 sLegacyRequests.put(netCap, l);
1886 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1887 return l.networkRequest;
1888 }
1889
1890 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1891 if (delay >= 0) {
1892 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
1893 CallbackHandler handler = getDefaultHandler();
1894 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1895 handler.sendMessageDelayed(msg, delay);
1896 }
1897 }
1898
1899 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1900 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1901 final LegacyRequest l;
1902 synchronized (sLegacyRequests) {
1903 l = sLegacyRequests.remove(netCap);
1904 }
1905 if (l == null) return false;
1906 unregisterNetworkCallback(l.networkCallback);
1907 l.clearDnsBinding();
1908 return true;
1909 }
1910
1911 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1912 static {
1913 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1914 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1915 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1916 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1917 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1918 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1919 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1920 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1921 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1922 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1923 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1924 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1925 }
1926
1927 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1928 static {
1929 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1930 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1931 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1932 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1933 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1934 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1935 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1936 }
1937
1938 /**
1939 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1940 * instance suitable for registering a request or callback. Throws an
1941 * IllegalArgumentException if no mapping from the legacy type to
1942 * NetworkCapabilities is known.
1943 *
1944 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1945 * to find the network instead.
1946 * @hide
1947 */
1948 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1949 final NetworkCapabilities nc = new NetworkCapabilities();
1950
1951 // Map from type to transports.
1952 final int NOT_FOUND = -1;
1953 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00001954 if (transport == NOT_FOUND) {
1955 throw new IllegalArgumentException("unknown legacy type: " + type);
1956 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001957 nc.addTransportType(transport);
1958
1959 // Map from type to capabilities.
1960 nc.addCapability(sLegacyTypeToCapability.get(
1961 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1962 nc.maybeMarkCapabilitiesRestricted();
1963 return nc;
1964 }
1965
1966 /** @hide */
1967 public static class PacketKeepaliveCallback {
1968 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1969 public PacketKeepaliveCallback() {
1970 }
1971 /** The requested keepalive was successfully started. */
1972 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1973 public void onStarted() {}
1974 /** The keepalive was successfully stopped. */
1975 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1976 public void onStopped() {}
1977 /** An error occurred. */
1978 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1979 public void onError(int error) {}
1980 }
1981
1982 /**
1983 * Allows applications to request that the system periodically send specific packets on their
1984 * behalf, using hardware offload to save battery power.
1985 *
1986 * To request that the system send keepalives, call one of the methods that return a
1987 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1988 * passing in a non-null callback. If the callback is successfully started, the callback's
1989 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1990 * specifying one of the {@code ERROR_*} constants in this class.
1991 *
1992 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1993 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1994 * {@link PacketKeepaliveCallback#onError} if an error occurred.
1995 *
1996 * @deprecated Use {@link SocketKeepalive} instead.
1997 *
1998 * @hide
1999 */
2000 public class PacketKeepalive {
2001
2002 private static final String TAG = "PacketKeepalive";
2003
2004 /** @hide */
2005 public static final int SUCCESS = 0;
2006
2007 /** @hide */
2008 public static final int NO_KEEPALIVE = -1;
2009
2010 /** @hide */
2011 public static final int BINDER_DIED = -10;
2012
2013 /** The specified {@code Network} is not connected. */
2014 public static final int ERROR_INVALID_NETWORK = -20;
2015 /** The specified IP addresses are invalid. For example, the specified source IP address is
2016 * not configured on the specified {@code Network}. */
2017 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2018 /** The requested port is invalid. */
2019 public static final int ERROR_INVALID_PORT = -22;
2020 /** The packet length is invalid (e.g., too long). */
2021 public static final int ERROR_INVALID_LENGTH = -23;
2022 /** The packet transmission interval is invalid (e.g., too short). */
2023 public static final int ERROR_INVALID_INTERVAL = -24;
2024
2025 /** The hardware does not support this request. */
2026 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2027 /** The hardware returned an error. */
2028 public static final int ERROR_HARDWARE_ERROR = -31;
2029
2030 /** The NAT-T destination port for IPsec */
2031 public static final int NATT_PORT = 4500;
2032
2033 /** The minimum interval in seconds between keepalive packet transmissions */
2034 public static final int MIN_INTERVAL = 10;
2035
2036 private final Network mNetwork;
2037 private final ISocketKeepaliveCallback mCallback;
2038 private final ExecutorService mExecutor;
2039
2040 private volatile Integer mSlot;
2041
2042 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2043 public void stop() {
2044 try {
2045 mExecutor.execute(() -> {
2046 try {
2047 if (mSlot != null) {
2048 mService.stopKeepalive(mNetwork, mSlot);
2049 }
2050 } catch (RemoteException e) {
2051 Log.e(TAG, "Error stopping packet keepalive: ", e);
2052 throw e.rethrowFromSystemServer();
2053 }
2054 });
2055 } catch (RejectedExecutionException e) {
2056 // The internal executor has already stopped due to previous event.
2057 }
2058 }
2059
2060 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002061 Objects.requireNonNull(network, "network cannot be null");
2062 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002063 mNetwork = network;
2064 mExecutor = Executors.newSingleThreadExecutor();
2065 mCallback = new ISocketKeepaliveCallback.Stub() {
2066 @Override
2067 public void onStarted(int slot) {
2068 final long token = Binder.clearCallingIdentity();
2069 try {
2070 mExecutor.execute(() -> {
2071 mSlot = slot;
2072 callback.onStarted();
2073 });
2074 } finally {
2075 Binder.restoreCallingIdentity(token);
2076 }
2077 }
2078
2079 @Override
2080 public void onStopped() {
2081 final long token = Binder.clearCallingIdentity();
2082 try {
2083 mExecutor.execute(() -> {
2084 mSlot = null;
2085 callback.onStopped();
2086 });
2087 } finally {
2088 Binder.restoreCallingIdentity(token);
2089 }
2090 mExecutor.shutdown();
2091 }
2092
2093 @Override
2094 public void onError(int error) {
2095 final long token = Binder.clearCallingIdentity();
2096 try {
2097 mExecutor.execute(() -> {
2098 mSlot = null;
2099 callback.onError(error);
2100 });
2101 } finally {
2102 Binder.restoreCallingIdentity(token);
2103 }
2104 mExecutor.shutdown();
2105 }
2106
2107 @Override
2108 public void onDataReceived() {
2109 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2110 // this callback when data is received.
2111 }
2112 };
2113 }
2114 }
2115
2116 /**
2117 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2118 *
2119 * @deprecated Use {@link #createSocketKeepalive} instead.
2120 *
2121 * @hide
2122 */
2123 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2124 public PacketKeepalive startNattKeepalive(
2125 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2126 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2127 final PacketKeepalive k = new PacketKeepalive(network, callback);
2128 try {
2129 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2130 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2131 } catch (RemoteException e) {
2132 Log.e(TAG, "Error starting packet keepalive: ", e);
2133 throw e.rethrowFromSystemServer();
2134 }
2135 return k;
2136 }
2137
2138 // Construct an invalid fd.
2139 private ParcelFileDescriptor createInvalidFd() {
2140 final int invalidFd = -1;
2141 return ParcelFileDescriptor.adoptFd(invalidFd);
2142 }
2143
2144 /**
2145 * Request that keepalives be started on a IPsec NAT-T socket.
2146 *
2147 * @param network The {@link Network} the socket is on.
2148 * @param socket The socket that needs to be kept alive.
2149 * @param source The source address of the {@link UdpEncapsulationSocket}.
2150 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2151 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2152 * must run callback sequentially, otherwise the order of callbacks cannot be
2153 * guaranteed.
2154 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2155 * changes. Must be extended by applications that use this API.
2156 *
2157 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2158 * given socket.
2159 **/
2160 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2161 @NonNull UdpEncapsulationSocket socket,
2162 @NonNull InetAddress source,
2163 @NonNull InetAddress destination,
2164 @NonNull @CallbackExecutor Executor executor,
2165 @NonNull Callback callback) {
2166 ParcelFileDescriptor dup;
2167 try {
2168 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2169 // which cannot be obtained by the app process.
2170 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2171 } catch (IOException ignored) {
2172 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2173 // ERROR_INVALID_SOCKET.
2174 dup = createInvalidFd();
2175 }
2176 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2177 destination, executor, callback);
2178 }
2179
2180 /**
2181 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2182 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2183 *
2184 * @param network The {@link Network} the socket is on.
2185 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2186 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2187 * from that port.
2188 * @param source The source address of the {@link UdpEncapsulationSocket}.
2189 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2190 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2191 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2192 * must run callback sequentially, otherwise the order of callbacks cannot be
2193 * guaranteed.
2194 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2195 * changes. Must be extended by applications that use this API.
2196 *
2197 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2198 * given socket.
2199 * @hide
2200 */
2201 @SystemApi
2202 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2203 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2204 @NonNull ParcelFileDescriptor pfd,
2205 @NonNull InetAddress source,
2206 @NonNull InetAddress destination,
2207 @NonNull @CallbackExecutor Executor executor,
2208 @NonNull Callback callback) {
2209 ParcelFileDescriptor dup;
2210 try {
2211 // TODO: Consider remove unnecessary dup.
2212 dup = pfd.dup();
2213 } catch (IOException ignored) {
2214 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2215 // ERROR_INVALID_SOCKET.
2216 dup = createInvalidFd();
2217 }
2218 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002219 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002220 }
2221
2222 /**
2223 * Request that keepalives be started on a TCP socket.
2224 * The socket must be established.
2225 *
2226 * @param network The {@link Network} the socket is on.
2227 * @param socket The socket that needs to be kept alive.
2228 * @param executor The executor on which callback will be invoked. This implementation assumes
2229 * the provided {@link Executor} runs the callbacks in sequence with no
2230 * concurrency. Failing this, no guarantee of correctness can be made. It is
2231 * the responsibility of the caller to ensure the executor provides this
2232 * guarantee. A simple way of creating such an executor is with the standard
2233 * tool {@code Executors.newSingleThreadExecutor}.
2234 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2235 * changes. Must be extended by applications that use this API.
2236 *
2237 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2238 * given socket.
2239 * @hide
2240 */
2241 @SystemApi
2242 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2243 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2244 @NonNull Socket socket,
2245 @NonNull Executor executor,
2246 @NonNull Callback callback) {
2247 ParcelFileDescriptor dup;
2248 try {
2249 dup = ParcelFileDescriptor.fromSocket(socket);
2250 } catch (UncheckedIOException ignored) {
2251 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2252 // ERROR_INVALID_SOCKET.
2253 dup = createInvalidFd();
2254 }
2255 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2256 }
2257
2258 /**
2259 * Ensure that a network route exists to deliver traffic to the specified
2260 * host via the specified network interface. An attempt to add a route that
2261 * already exists is ignored, but treated as successful.
2262 *
2263 * <p>This method requires the caller to hold either the
2264 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2265 * or the ability to modify system settings as determined by
2266 * {@link android.provider.Settings.System#canWrite}.</p>
2267 *
2268 * @param networkType the type of the network over which traffic to the specified
2269 * host is to be routed
2270 * @param hostAddress the IP address of the host to which the route is desired
2271 * @return {@code true} on success, {@code false} on failure
2272 *
2273 * @deprecated Deprecated in favor of the
2274 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2275 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2276 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2277 * throw {@code UnsupportedOperationException} if called.
2278 * @removed
2279 */
2280 @Deprecated
2281 public boolean requestRouteToHost(int networkType, int hostAddress) {
2282 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2283 }
2284
2285 /**
2286 * Ensure that a network route exists to deliver traffic to the specified
2287 * host via the specified network interface. An attempt to add a route that
2288 * already exists is ignored, but treated as successful.
2289 *
2290 * <p>This method requires the caller to hold either the
2291 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2292 * or the ability to modify system settings as determined by
2293 * {@link android.provider.Settings.System#canWrite}.</p>
2294 *
2295 * @param networkType the type of the network over which traffic to the specified
2296 * host is to be routed
2297 * @param hostAddress the IP address of the host to which the route is desired
2298 * @return {@code true} on success, {@code false} on failure
2299 * @hide
2300 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2301 * {@link #bindProcessToNetwork} API.
2302 */
2303 @Deprecated
2304 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002305 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002306 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2307 checkLegacyRoutingApiAccess();
2308 try {
2309 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2310 mContext.getOpPackageName(), getAttributionTag());
2311 } catch (RemoteException e) {
2312 throw e.rethrowFromSystemServer();
2313 }
2314 }
2315
2316 /**
2317 * @return the context's attribution tag
2318 */
2319 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2320 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002321 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002322 }
2323
2324 /**
2325 * Returns the value of the setting for background data usage. If false,
2326 * applications should not use the network if the application is not in the
2327 * foreground. Developers should respect this setting, and check the value
2328 * of this before performing any background data operations.
2329 * <p>
2330 * All applications that have background services that use the network
2331 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2332 * <p>
2333 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2334 * background data depends on several combined factors, and this method will
2335 * always return {@code true}. Instead, when background data is unavailable,
2336 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2337 *
2338 * @return Whether background data usage is allowed.
2339 */
2340 @Deprecated
2341 public boolean getBackgroundDataSetting() {
2342 // assume that background data is allowed; final authority is
2343 // NetworkInfo which may be blocked.
2344 return true;
2345 }
2346
2347 /**
2348 * Sets the value of the setting for background data usage.
2349 *
2350 * @param allowBackgroundData Whether an application should use data while
2351 * it is in the background.
2352 *
2353 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2354 * @see #getBackgroundDataSetting()
2355 * @hide
2356 */
2357 @Deprecated
2358 @UnsupportedAppUsage
2359 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2360 // ignored
2361 }
2362
2363 /**
2364 * @hide
2365 * @deprecated Talk to TelephonyManager directly
2366 */
2367 @Deprecated
2368 @UnsupportedAppUsage
2369 public boolean getMobileDataEnabled() {
2370 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2371 if (tm != null) {
2372 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2373 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2374 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2375 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2376 + " retVal=" + retVal);
2377 return retVal;
2378 }
2379 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2380 return false;
2381 }
2382
2383 /**
2384 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2385 * to find out when the system default network has gone in to a high power state.
2386 */
2387 public interface OnNetworkActiveListener {
2388 /**
2389 * Called on the main thread of the process to report that the current data network
2390 * has become active, and it is now a good time to perform any pending network
2391 * operations. Note that this listener only tells you when the network becomes
2392 * active; if at any other time you want to know whether it is active (and thus okay
2393 * to initiate network traffic), you can retrieve its instantaneous state with
2394 * {@link ConnectivityManager#isDefaultNetworkActive}.
2395 */
2396 void onNetworkActive();
2397 }
2398
Chiachang Wang2de41682021-09-23 10:46:03 +08002399 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002400 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2401 mNetworkActivityListeners = new ArrayMap<>();
2402
2403 /**
2404 * Start listening to reports when the system's default data network is active, meaning it is
2405 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2406 * to determine the current state of the system's default network after registering the
2407 * listener.
2408 * <p>
2409 * If the process default network has been set with
2410 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2411 * reflect the process's default, but the system default.
2412 *
2413 * @param l The listener to be told when the network is active.
2414 */
2415 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002416 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002417 @Override
2418 public void onNetworkActive() throws RemoteException {
2419 l.onNetworkActive();
2420 }
2421 };
2422
Chiachang Wang2de41682021-09-23 10:46:03 +08002423 synchronized (mNetworkActivityListeners) {
2424 try {
2425 mService.registerNetworkActivityListener(rl);
2426 mNetworkActivityListeners.put(l, rl);
2427 } catch (RemoteException e) {
2428 throw e.rethrowFromSystemServer();
2429 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002430 }
2431 }
2432
2433 /**
2434 * Remove network active listener previously registered with
2435 * {@link #addDefaultNetworkActiveListener}.
2436 *
2437 * @param l Previously registered listener.
2438 */
2439 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002440 synchronized (mNetworkActivityListeners) {
2441 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2442 if (rl == null) {
2443 throw new IllegalArgumentException("Listener was not registered.");
2444 }
2445 try {
2446 mService.unregisterNetworkActivityListener(rl);
2447 mNetworkActivityListeners.remove(l);
2448 } catch (RemoteException e) {
2449 throw e.rethrowFromSystemServer();
2450 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002451 }
2452 }
2453
2454 /**
2455 * Return whether the data network is currently active. An active network means that
2456 * it is currently in a high power state for performing data transmission. On some
2457 * types of networks, it may be expensive to move and stay in such a state, so it is
2458 * more power efficient to batch network traffic together when the radio is already in
2459 * this state. This method tells you whether right now is currently a good time to
2460 * initiate network traffic, as the network is already active.
2461 */
2462 public boolean isDefaultNetworkActive() {
2463 try {
lucaslin709eb842021-01-21 02:04:15 +08002464 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002465 } catch (RemoteException e) {
2466 throw e.rethrowFromSystemServer();
2467 }
2468 }
2469
2470 /**
2471 * {@hide}
2472 */
2473 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002474 mContext = Objects.requireNonNull(context, "missing context");
2475 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002476 sInstance = this;
2477 }
2478
2479 /** {@hide} */
2480 @UnsupportedAppUsage
2481 public static ConnectivityManager from(Context context) {
2482 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2483 }
2484
2485 /** @hide */
2486 public NetworkRequest getDefaultRequest() {
2487 try {
2488 // This is not racy as the default request is final in ConnectivityService.
2489 return mService.getDefaultRequest();
2490 } catch (RemoteException e) {
2491 throw e.rethrowFromSystemServer();
2492 }
2493 }
2494
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002495 /**
2496 * Check if the package is a allowed to write settings. This also accounts that such an access
2497 * happened.
2498 *
2499 * @return {@code true} iff the package is allowed to write settings.
2500 */
2501 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2502 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2503 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2504 boolean throwException) {
2505 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002506 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002507 }
2508
2509 /**
2510 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2511 * situations where a Context pointer is unavailable.
2512 * @hide
2513 */
2514 @Deprecated
2515 static ConnectivityManager getInstanceOrNull() {
2516 return sInstance;
2517 }
2518
2519 /**
2520 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2521 * situations where a Context pointer is unavailable.
2522 * @hide
2523 */
2524 @Deprecated
2525 @UnsupportedAppUsage
2526 private static ConnectivityManager getInstance() {
2527 if (getInstanceOrNull() == null) {
2528 throw new IllegalStateException("No ConnectivityManager yet constructed");
2529 }
2530 return getInstanceOrNull();
2531 }
2532
2533 /**
2534 * Get the set of tetherable, available interfaces. This list is limited by
2535 * device configuration and current interface existence.
2536 *
2537 * @return an array of 0 or more Strings of tetherable interface names.
2538 *
2539 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2540 * {@hide}
2541 */
2542 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2543 @UnsupportedAppUsage
2544 @Deprecated
2545 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002546 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002547 }
2548
2549 /**
2550 * Get the set of tethered interfaces.
2551 *
2552 * @return an array of 0 or more String of currently tethered interface names.
2553 *
2554 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2555 * {@hide}
2556 */
2557 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2558 @UnsupportedAppUsage
2559 @Deprecated
2560 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002561 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002562 }
2563
2564 /**
2565 * Get the set of interface names which attempted to tether but
2566 * failed. Re-attempting to tether may cause them to reset to the Tethered
2567 * state. Alternatively, causing the interface to be destroyed and recreated
2568 * may cause them to reset to the available state.
2569 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2570 * information on the cause of the errors.
2571 *
2572 * @return an array of 0 or more String indicating the interface names
2573 * which failed to tether.
2574 *
2575 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2576 * {@hide}
2577 */
2578 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2579 @UnsupportedAppUsage
2580 @Deprecated
2581 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002582 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002583 }
2584
2585 /**
2586 * Get the set of tethered dhcp ranges.
2587 *
2588 * @deprecated This method is not supported.
2589 * TODO: remove this function when all of clients are removed.
2590 * {@hide}
2591 */
2592 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2593 @Deprecated
2594 public String[] getTetheredDhcpRanges() {
2595 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2596 }
2597
2598 /**
2599 * Attempt to tether the named interface. This will setup a dhcp server
2600 * on the interface, forward and NAT IP packets and forward DNS requests
2601 * to the best active upstream network interface. Note that if no upstream
2602 * IP network interface is available, dhcp will still run and traffic will be
2603 * allowed between the tethered devices and this device, though upstream net
2604 * access will of course fail until an upstream network interface becomes
2605 * active.
2606 *
2607 * <p>This method requires the caller to hold either the
2608 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2609 * or the ability to modify system settings as determined by
2610 * {@link android.provider.Settings.System#canWrite}.</p>
2611 *
2612 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2613 * and WifiStateMachine which need direct access. All other clients should use
2614 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2615 * logic.</p>
2616 *
2617 * @param iface the interface name to tether.
2618 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2619 * @deprecated Use {@link TetheringManager#startTethering} instead
2620 *
2621 * {@hide}
2622 */
2623 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2624 @Deprecated
2625 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002626 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002627 }
2628
2629 /**
2630 * Stop tethering the named interface.
2631 *
2632 * <p>This method requires the caller to hold either the
2633 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2634 * or the ability to modify system settings as determined by
2635 * {@link android.provider.Settings.System#canWrite}.</p>
2636 *
2637 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2638 * and WifiStateMachine which need direct access. All other clients should use
2639 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2640 * logic.</p>
2641 *
2642 * @param iface the interface name to untether.
2643 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2644 *
2645 * {@hide}
2646 */
2647 @UnsupportedAppUsage
2648 @Deprecated
2649 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002650 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002651 }
2652
2653 /**
2654 * Check if the device allows for tethering. It may be disabled via
2655 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2656 * due to device configuration.
2657 *
2658 * <p>If this app does not have permission to use this API, it will always
2659 * return false rather than throw an exception.</p>
2660 *
2661 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2662 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2663 *
2664 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2665 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2666 *
2667 * @return a boolean - {@code true} indicating Tethering is supported.
2668 *
2669 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2670 * {@hide}
2671 */
2672 @SystemApi
2673 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2674 android.Manifest.permission.WRITE_SETTINGS})
2675 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002676 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002677 }
2678
2679 /**
2680 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2681 *
2682 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2683 * @hide
2684 */
2685 @SystemApi
2686 @Deprecated
2687 public static abstract class OnStartTetheringCallback {
2688 /**
2689 * Called when tethering has been successfully started.
2690 */
2691 public void onTetheringStarted() {}
2692
2693 /**
2694 * Called when starting tethering failed.
2695 */
2696 public void onTetheringFailed() {}
2697 }
2698
2699 /**
2700 * Convenient overload for
2701 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2702 * handler to run on the current thread's {@link Looper}.
2703 *
2704 * @deprecated Use {@link TetheringManager#startTethering} instead.
2705 * @hide
2706 */
2707 @SystemApi
2708 @Deprecated
2709 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2710 public void startTethering(int type, boolean showProvisioningUi,
2711 final OnStartTetheringCallback callback) {
2712 startTethering(type, showProvisioningUi, callback, null);
2713 }
2714
2715 /**
2716 * Runs tether provisioning for the given type if needed and then starts tethering if
2717 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2718 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2719 * schedules tether provisioning re-checks if appropriate.
2720 *
2721 * @param type The type of tethering to start. Must be one of
2722 * {@link ConnectivityManager.TETHERING_WIFI},
2723 * {@link ConnectivityManager.TETHERING_USB}, or
2724 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2725 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2726 * is one. This should be true the first time this function is called and also any time
2727 * the user can see this UI. It gives users information from their carrier about the
2728 * check failing and how they can sign up for tethering if possible.
2729 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2730 * of the result of trying to tether.
2731 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2732 *
2733 * @deprecated Use {@link TetheringManager#startTethering} instead.
2734 * @hide
2735 */
2736 @SystemApi
2737 @Deprecated
2738 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2739 public void startTethering(int type, boolean showProvisioningUi,
2740 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002741 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002742
2743 final Executor executor = new Executor() {
2744 @Override
2745 public void execute(Runnable command) {
2746 if (handler == null) {
2747 command.run();
2748 } else {
2749 handler.post(command);
2750 }
2751 }
2752 };
2753
2754 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2755 @Override
2756 public void onTetheringStarted() {
2757 callback.onTetheringStarted();
2758 }
2759
2760 @Override
2761 public void onTetheringFailed(final int error) {
2762 callback.onTetheringFailed();
2763 }
2764 };
2765
2766 final TetheringRequest request = new TetheringRequest.Builder(type)
2767 .setShouldShowEntitlementUi(showProvisioningUi).build();
2768
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002769 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002770 }
2771
2772 /**
2773 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2774 * applicable.
2775 *
2776 * @param type The type of tethering to stop. Must be one of
2777 * {@link ConnectivityManager.TETHERING_WIFI},
2778 * {@link ConnectivityManager.TETHERING_USB}, or
2779 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2780 *
2781 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2782 * @hide
2783 */
2784 @SystemApi
2785 @Deprecated
2786 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2787 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002788 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002789 }
2790
2791 /**
2792 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2793 * upstream status.
2794 *
2795 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2796 * @hide
2797 */
2798 @SystemApi
2799 @Deprecated
2800 public abstract static class OnTetheringEventCallback {
2801
2802 /**
2803 * Called when tethering upstream changed. This can be called multiple times and can be
2804 * called any time.
2805 *
2806 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2807 * have any upstream.
2808 */
2809 public void onUpstreamChanged(@Nullable Network network) {}
2810 }
2811
2812 @GuardedBy("mTetheringEventCallbacks")
2813 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2814 mTetheringEventCallbacks = new ArrayMap<>();
2815
2816 /**
2817 * Start listening to tethering change events. Any new added callback will receive the last
2818 * tethering status right away. If callback is registered when tethering has no upstream or
2819 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2820 * with a null argument. The same callback object cannot be registered twice.
2821 *
2822 * @param executor the executor on which callback will be invoked.
2823 * @param callback the callback to be called when tethering has change events.
2824 *
2825 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2826 * @hide
2827 */
2828 @SystemApi
2829 @Deprecated
2830 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2831 public void registerTetheringEventCallback(
2832 @NonNull @CallbackExecutor Executor executor,
2833 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002834 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002835
2836 final TetheringEventCallback tetherCallback =
2837 new TetheringEventCallback() {
2838 @Override
2839 public void onUpstreamChanged(@Nullable Network network) {
2840 callback.onUpstreamChanged(network);
2841 }
2842 };
2843
2844 synchronized (mTetheringEventCallbacks) {
2845 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002846 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002847 }
2848 }
2849
2850 /**
2851 * Remove tethering event callback previously registered with
2852 * {@link #registerTetheringEventCallback}.
2853 *
2854 * @param callback previously registered callback.
2855 *
2856 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
2857 * @hide
2858 */
2859 @SystemApi
2860 @Deprecated
2861 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2862 public void unregisterTetheringEventCallback(
2863 @NonNull final OnTetheringEventCallback callback) {
2864 Objects.requireNonNull(callback, "The callback must be non-null");
2865 synchronized (mTetheringEventCallbacks) {
2866 final TetheringEventCallback tetherCallback =
2867 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002868 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002869 }
2870 }
2871
2872
2873 /**
2874 * Get the list of regular expressions that define any tetherable
2875 * USB network interfaces. If USB tethering is not supported by the
2876 * device, this list should be empty.
2877 *
2878 * @return an array of 0 or more regular expression Strings defining
2879 * what interfaces are considered tetherable usb interfaces.
2880 *
2881 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2882 * {@hide}
2883 */
2884 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2885 @UnsupportedAppUsage
2886 @Deprecated
2887 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002888 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002889 }
2890
2891 /**
2892 * Get the list of regular expressions that define any tetherable
2893 * Wifi network interfaces. If Wifi tethering is not supported by the
2894 * device, this list should be empty.
2895 *
2896 * @return an array of 0 or more regular expression Strings defining
2897 * what interfaces are considered tetherable wifi interfaces.
2898 *
2899 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2900 * {@hide}
2901 */
2902 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2903 @UnsupportedAppUsage
2904 @Deprecated
2905 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002906 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002907 }
2908
2909 /**
2910 * Get the list of regular expressions that define any tetherable
2911 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2912 * device, this list should be empty.
2913 *
2914 * @return an array of 0 or more regular expression Strings defining
2915 * what interfaces are considered tetherable bluetooth interfaces.
2916 *
2917 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2918 *TetheringManager.TetheringInterfaceRegexps)} instead.
2919 * {@hide}
2920 */
2921 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2922 @UnsupportedAppUsage
2923 @Deprecated
2924 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002925 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002926 }
2927
2928 /**
2929 * Attempt to both alter the mode of USB and Tethering of USB. A
2930 * utility method to deal with some of the complexity of USB - will
2931 * attempt to switch to Rndis and subsequently tether the resulting
2932 * interface on {@code true} or turn off tethering and switch off
2933 * Rndis on {@code false}.
2934 *
2935 * <p>This method requires the caller to hold either the
2936 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2937 * or the ability to modify system settings as determined by
2938 * {@link android.provider.Settings.System#canWrite}.</p>
2939 *
2940 * @param enable a boolean - {@code true} to enable tethering
2941 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2942 * @deprecated Use {@link TetheringManager#startTethering} instead
2943 *
2944 * {@hide}
2945 */
2946 @UnsupportedAppUsage
2947 @Deprecated
2948 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002949 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002950 }
2951
2952 /**
2953 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2954 * {@hide}
2955 */
2956 @SystemApi
2957 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002958 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002959 /**
2960 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2961 * {@hide}
2962 */
2963 @Deprecated
2964 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2965 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2966 /**
2967 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2968 * {@hide}
2969 */
2970 @Deprecated
2971 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2972 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2973 /**
2974 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2975 * {@hide}
2976 */
2977 @Deprecated
2978 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2979 /**
2980 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2981 * {@hide}
2982 */
2983 @Deprecated
2984 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2985 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2986 /**
2987 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
2988 * {@hide}
2989 */
2990 @Deprecated
2991 public static final int TETHER_ERROR_MASTER_ERROR =
2992 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
2993 /**
2994 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2995 * {@hide}
2996 */
2997 @Deprecated
2998 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2999 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3000 /**
3001 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3002 * {@hide}
3003 */
3004 @Deprecated
3005 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3006 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3007 /**
3008 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3009 * {@hide}
3010 */
3011 @Deprecated
3012 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3013 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3014 /**
3015 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3016 * {@hide}
3017 */
3018 @Deprecated
3019 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3020 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3021 /**
3022 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3023 * {@hide}
3024 */
3025 @Deprecated
3026 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3027 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3028 /**
3029 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3030 * {@hide}
3031 */
3032 @SystemApi
3033 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003034 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003035 /**
3036 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3037 * {@hide}
3038 */
3039 @Deprecated
3040 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3041 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3042 /**
3043 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3044 * {@hide}
3045 */
3046 @SystemApi
3047 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003048 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003049
3050 /**
3051 * Get a more detailed error code after a Tethering or Untethering
3052 * request asynchronously failed.
3053 *
3054 * @param iface The name of the interface of interest
3055 * @return error The error code of the last error tethering or untethering the named
3056 * interface
3057 *
3058 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3059 * {@hide}
3060 */
3061 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3062 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3063 @Deprecated
3064 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003065 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003066 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3067 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3068 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3069 // instead.
3070 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3071 }
3072 return error;
3073 }
3074
3075 /** @hide */
3076 @Retention(RetentionPolicy.SOURCE)
3077 @IntDef(value = {
3078 TETHER_ERROR_NO_ERROR,
3079 TETHER_ERROR_PROVISION_FAILED,
3080 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3081 })
3082 public @interface EntitlementResultCode {
3083 }
3084
3085 /**
3086 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3087 * entitlement succeeded.
3088 *
3089 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3090 * @hide
3091 */
3092 @SystemApi
3093 @Deprecated
3094 public interface OnTetheringEntitlementResultListener {
3095 /**
3096 * Called to notify entitlement result.
3097 *
3098 * @param resultCode an int value of entitlement result. It may be one of
3099 * {@link #TETHER_ERROR_NO_ERROR},
3100 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3101 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3102 */
3103 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3104 }
3105
3106 /**
3107 * Get the last value of the entitlement check on this downstream. If the cached value is
3108 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3109 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3110 * guaranteed that the UI-based entitlement check will complete in any specific time period
3111 * and may in fact never complete. Any successful entitlement check the platform performs for
3112 * any reason will update the cached value.
3113 *
3114 * @param type the downstream type of tethering. Must be one of
3115 * {@link #TETHERING_WIFI},
3116 * {@link #TETHERING_USB}, or
3117 * {@link #TETHERING_BLUETOOTH}.
3118 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3119 * @param executor the executor on which callback will be invoked.
3120 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3121 * notify the caller of the result of entitlement check. The listener may be called zero
3122 * or one time.
3123 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3124 * {@hide}
3125 */
3126 @SystemApi
3127 @Deprecated
3128 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3129 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3130 @NonNull @CallbackExecutor Executor executor,
3131 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003132 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003133 ResultReceiver wrappedListener = new ResultReceiver(null) {
3134 @Override
3135 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003136 final long token = Binder.clearCallingIdentity();
3137 try {
3138 executor.execute(() -> {
3139 listener.onTetheringEntitlementResult(resultCode);
3140 });
3141 } finally {
3142 Binder.restoreCallingIdentity(token);
3143 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003144 }
3145 };
3146
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003147 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003148 showEntitlementUi);
3149 }
3150
3151 /**
3152 * Report network connectivity status. This is currently used only
3153 * to alter status bar UI.
3154 * <p>This method requires the caller to hold the permission
3155 * {@link android.Manifest.permission#STATUS_BAR}.
3156 *
3157 * @param networkType The type of network you want to report on
3158 * @param percentage The quality of the connection 0 is bad, 100 is good
3159 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3160 * {@hide}
3161 */
3162 public void reportInetCondition(int networkType, int percentage) {
3163 printStackTrace();
3164 try {
3165 mService.reportInetCondition(networkType, percentage);
3166 } catch (RemoteException e) {
3167 throw e.rethrowFromSystemServer();
3168 }
3169 }
3170
3171 /**
3172 * Report a problem network to the framework. This provides a hint to the system
3173 * that there might be connectivity problems on this network and may cause
3174 * the framework to re-evaluate network connectivity and/or switch to another
3175 * network.
3176 *
3177 * @param network The {@link Network} the application was attempting to use
3178 * or {@code null} to indicate the current default network.
3179 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3180 * working and non-working connectivity.
3181 */
3182 @Deprecated
3183 public void reportBadNetwork(@Nullable Network network) {
3184 printStackTrace();
3185 try {
3186 // One of these will be ignored because it matches system's current state.
3187 // The other will trigger the necessary reevaluation.
3188 mService.reportNetworkConnectivity(network, true);
3189 mService.reportNetworkConnectivity(network, false);
3190 } catch (RemoteException e) {
3191 throw e.rethrowFromSystemServer();
3192 }
3193 }
3194
3195 /**
3196 * Report to the framework whether a network has working connectivity.
3197 * This provides a hint to the system that a particular network is providing
3198 * working connectivity or not. In response the framework may re-evaluate
3199 * the network's connectivity and might take further action thereafter.
3200 *
3201 * @param network The {@link Network} the application was attempting to use
3202 * or {@code null} to indicate the current default network.
3203 * @param hasConnectivity {@code true} if the application was able to successfully access the
3204 * Internet using {@code network} or {@code false} if not.
3205 */
3206 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3207 printStackTrace();
3208 try {
3209 mService.reportNetworkConnectivity(network, hasConnectivity);
3210 } catch (RemoteException e) {
3211 throw e.rethrowFromSystemServer();
3212 }
3213 }
3214
3215 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003216 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003217 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003218 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3219 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3220 * accessing any network, regardless of what the settings for that network are.
3221 *
3222 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3223 * proxy is likely to break networking on multiple networks. This method is only meant
3224 * for device policy clients looking to do general internal filtering or similar use cases.
3225 *
3226 * {@see #getGlobalProxy}
3227 * {@see LinkProperties#getHttpProxy}
3228 *
3229 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3230 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003231 * @hide
3232 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003233 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003234 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003235 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003236 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003237 try {
3238 mService.setGlobalProxy(p);
3239 } catch (RemoteException e) {
3240 throw e.rethrowFromSystemServer();
3241 }
3242 }
3243
3244 /**
3245 * Retrieve any network-independent global HTTP proxy.
3246 *
3247 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3248 * if no global HTTP proxy is set.
3249 * @hide
3250 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003251 @SystemApi(client = MODULE_LIBRARIES)
3252 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003253 public ProxyInfo getGlobalProxy() {
3254 try {
3255 return mService.getGlobalProxy();
3256 } catch (RemoteException e) {
3257 throw e.rethrowFromSystemServer();
3258 }
3259 }
3260
3261 /**
3262 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3263 * network-specific HTTP proxy. If {@code network} is null, the
3264 * network-specific proxy returned is the proxy of the default active
3265 * network.
3266 *
3267 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3268 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3269 * or when {@code network} is {@code null},
3270 * the {@code ProxyInfo} for the default active network. Returns
3271 * {@code null} when no proxy applies or the caller doesn't have
3272 * permission to use {@code network}.
3273 * @hide
3274 */
3275 public ProxyInfo getProxyForNetwork(Network network) {
3276 try {
3277 return mService.getProxyForNetwork(network);
3278 } catch (RemoteException e) {
3279 throw e.rethrowFromSystemServer();
3280 }
3281 }
3282
3283 /**
3284 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3285 * otherwise if this process is bound to a {@link Network} using
3286 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3287 * the default network's proxy is returned.
3288 *
3289 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3290 * HTTP proxy is active.
3291 */
3292 @Nullable
3293 public ProxyInfo getDefaultProxy() {
3294 return getProxyForNetwork(getBoundNetworkForProcess());
3295 }
3296
3297 /**
3298 * Returns true if the hardware supports the given network type
3299 * else it returns false. This doesn't indicate we have coverage
3300 * or are authorized onto a network, just whether or not the
3301 * hardware supports it. For example a GSM phone without a SIM
3302 * should still return {@code true} for mobile data, but a wifi only
3303 * tablet would return {@code false}.
3304 *
3305 * @param networkType The network type we'd like to check
3306 * @return {@code true} if supported, else {@code false}
3307 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3308 * @hide
3309 */
3310 @Deprecated
3311 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3312 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3313 public boolean isNetworkSupported(int networkType) {
3314 try {
3315 return mService.isNetworkSupported(networkType);
3316 } catch (RemoteException e) {
3317 throw e.rethrowFromSystemServer();
3318 }
3319 }
3320
3321 /**
3322 * Returns if the currently active data network is metered. A network is
3323 * classified as metered when the user is sensitive to heavy data usage on
3324 * that connection due to monetary costs, data limitations or
3325 * battery/performance issues. You should check this before doing large
3326 * data transfers, and warn the user or delay the operation until another
3327 * network is available.
3328 *
3329 * @return {@code true} if large transfers should be avoided, otherwise
3330 * {@code false}.
3331 */
3332 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3333 public boolean isActiveNetworkMetered() {
3334 try {
3335 return mService.isActiveNetworkMetered();
3336 } catch (RemoteException e) {
3337 throw e.rethrowFromSystemServer();
3338 }
3339 }
3340
3341 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003342 * Set sign in error notification to visible or invisible
3343 *
3344 * @hide
3345 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3346 */
3347 @Deprecated
3348 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3349 String action) {
3350 try {
3351 mService.setProvisioningNotificationVisible(visible, networkType, action);
3352 } catch (RemoteException e) {
3353 throw e.rethrowFromSystemServer();
3354 }
3355 }
3356
3357 /**
3358 * Set the value for enabling/disabling airplane mode
3359 *
3360 * @param enable whether to enable airplane mode or not
3361 *
3362 * @hide
3363 */
3364 @RequiresPermission(anyOf = {
3365 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3366 android.Manifest.permission.NETWORK_SETTINGS,
3367 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3368 android.Manifest.permission.NETWORK_STACK})
3369 @SystemApi
3370 public void setAirplaneMode(boolean enable) {
3371 try {
3372 mService.setAirplaneMode(enable);
3373 } catch (RemoteException e) {
3374 throw e.rethrowFromSystemServer();
3375 }
3376 }
3377
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003378 /**
3379 * Registers the specified {@link NetworkProvider}.
3380 * Each listener must only be registered once. The listener can be unregistered with
3381 * {@link #unregisterNetworkProvider}.
3382 *
3383 * @param provider the provider to register
3384 * @return the ID of the provider. This ID must be used by the provider when registering
3385 * {@link android.net.NetworkAgent}s.
3386 * @hide
3387 */
3388 @SystemApi
3389 @RequiresPermission(anyOf = {
3390 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3391 android.Manifest.permission.NETWORK_FACTORY})
3392 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3393 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3394 throw new IllegalStateException("NetworkProviders can only be registered once");
3395 }
3396
3397 try {
3398 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3399 provider.getName());
3400 provider.setProviderId(providerId);
3401 } catch (RemoteException e) {
3402 throw e.rethrowFromSystemServer();
3403 }
3404 return provider.getProviderId();
3405 }
3406
3407 /**
3408 * Unregisters the specified NetworkProvider.
3409 *
3410 * @param provider the provider to unregister
3411 * @hide
3412 */
3413 @SystemApi
3414 @RequiresPermission(anyOf = {
3415 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3416 android.Manifest.permission.NETWORK_FACTORY})
3417 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3418 try {
3419 mService.unregisterNetworkProvider(provider.getMessenger());
3420 } catch (RemoteException e) {
3421 throw e.rethrowFromSystemServer();
3422 }
3423 provider.setProviderId(NetworkProvider.ID_NONE);
3424 }
3425
Chalard Jeand1b498b2021-01-05 08:40:09 +09003426 /**
3427 * Register or update a network offer with ConnectivityService.
3428 *
3429 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003430 * them to networking requests made by apps or the system. A callback identifies an offer
3431 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3432 * score and the capabilities of the network it might be able to bring up ; these act as
3433 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003434 * provider.
3435 *
3436 * The provider is under no obligation to be able to bring up the network it offers at any
3437 * given time. Instead, this mechanism is meant to limit requests received by providers
3438 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3439 * the quality of the network satisfying a given request to their own offer.
3440 *
3441 * An offer can be updated by calling this again with the same callback object. This is
3442 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3443 * provider with the changes caused by the changes in the offer.
3444 *
3445 * @param provider The provider making this offer.
3446 * @param score The prospective score of the network.
3447 * @param caps The prospective capabilities of the network.
3448 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003449 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003450 */
3451 @RequiresPermission(anyOf = {
3452 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3453 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003454 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003455 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3456 @NonNull final INetworkOfferCallback callback) {
3457 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003458 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003459 Objects.requireNonNull(score, "null score"),
3460 Objects.requireNonNull(caps, "null caps"),
3461 Objects.requireNonNull(callback, "null callback"));
3462 } catch (RemoteException e) {
3463 throw e.rethrowFromSystemServer();
3464 }
3465 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003466
Chalard Jeand1b498b2021-01-05 08:40:09 +09003467 /**
3468 * Withdraw a network offer made with {@link #offerNetwork}.
3469 *
3470 * @param callback The callback passed at registration time. This must be the same object
3471 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003472 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003473 */
3474 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3475 try {
3476 mService.unofferNetwork(Objects.requireNonNull(callback));
3477 } catch (RemoteException e) {
3478 throw e.rethrowFromSystemServer();
3479 }
3480 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003481 /** @hide exposed via the NetworkProvider class. */
3482 @RequiresPermission(anyOf = {
3483 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3484 android.Manifest.permission.NETWORK_FACTORY})
3485 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3486 try {
3487 mService.declareNetworkRequestUnfulfillable(request);
3488 } catch (RemoteException e) {
3489 throw e.rethrowFromSystemServer();
3490 }
3491 }
3492
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003493 /**
3494 * @hide
3495 * Register a NetworkAgent with ConnectivityService.
3496 * @return Network corresponding to NetworkAgent.
3497 */
3498 @RequiresPermission(anyOf = {
3499 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3500 android.Manifest.permission.NETWORK_FACTORY})
3501 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003502 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3503 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003504 try {
3505 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3506 } catch (RemoteException e) {
3507 throw e.rethrowFromSystemServer();
3508 }
3509 }
3510
3511 /**
3512 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3513 * changes. Should be extended by applications wanting notifications.
3514 *
3515 * A {@code NetworkCallback} is registered by calling
3516 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3517 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3518 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3519 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3520 * A {@code NetworkCallback} should be registered at most once at any time.
3521 * A {@code NetworkCallback} that has been unregistered can be registered again.
3522 */
3523 public static class NetworkCallback {
3524 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003525 * No flags associated with this callback.
3526 * @hide
3527 */
3528 public static final int FLAG_NONE = 0;
3529 /**
3530 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3531 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3532 * <p>
3533 * These include:
3534 * <li> Some transport info instances (retrieved via
3535 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3536 * contain location sensitive information.
3537 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003538 * sensitive for wifi suggestor apps (i.e using
3539 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003540 * </p>
3541 * <p>
3542 * Note:
3543 * <li> Retrieving this location sensitive information (subject to app's location
3544 * permissions) will be noted by system. </li>
3545 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3546 * not include location sensitive info.
3547 * </p>
3548 */
Roshan Pius189d0092021-03-11 21:16:44 -08003549 // Note: Some existing fields which are location sensitive may still be included without
3550 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003551 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3552
3553 /** @hide */
3554 @Retention(RetentionPolicy.SOURCE)
3555 @IntDef(flag = true, prefix = "FLAG_", value = {
3556 FLAG_NONE,
3557 FLAG_INCLUDE_LOCATION_INFO
3558 })
3559 public @interface Flag { }
3560
3561 /**
3562 * All the valid flags for error checking.
3563 */
3564 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3565
3566 public NetworkCallback() {
3567 this(FLAG_NONE);
3568 }
3569
3570 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003571 if ((flags & VALID_FLAGS) != flags) {
3572 throw new IllegalArgumentException("Invalid flags");
3573 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003574 mFlags = flags;
3575 }
3576
3577 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003578 * Called when the framework connects to a new network to evaluate whether it satisfies this
3579 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3580 * callback. There is no guarantee that this new network will satisfy any requests, or that
3581 * the network will stay connected for longer than the time necessary to evaluate it.
3582 * <p>
3583 * Most applications <b>should not</b> act on this callback, and should instead use
3584 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3585 * the framework in properly evaluating the network &mdash; for example, an application that
3586 * can automatically log in to a captive portal without user intervention.
3587 *
3588 * @param network The {@link Network} of the network that is being evaluated.
3589 *
3590 * @hide
3591 */
3592 public void onPreCheck(@NonNull Network network) {}
3593
3594 /**
3595 * Called when the framework connects and has declared a new network ready for use.
3596 * This callback may be called more than once if the {@link Network} that is
3597 * satisfying the request changes.
3598 *
3599 * @param network The {@link Network} of the satisfying network.
3600 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3601 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3602 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3603 * @hide
3604 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003605 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003606 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003607 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003608 // Internally only this method is called when a new network is available, and
3609 // it calls the callback in the same way and order that older versions used
3610 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003611 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3612 onBlockedStatusChanged(network, blocked);
3613 }
3614
3615 /**
3616 * Legacy variant of onAvailable that takes a boolean blocked reason.
3617 *
3618 * This method has never been public API, but it's not final, so there may be apps that
3619 * implemented it and rely on it being called. Do our best not to break them.
3620 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3621 * this method is called. There does not seem to be a way to avoid this.
3622 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3623 *
3624 * @hide
3625 */
3626 public void onAvailable(@NonNull Network network,
3627 @NonNull NetworkCapabilities networkCapabilities,
3628 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003629 onAvailable(network);
3630 if (!networkCapabilities.hasCapability(
3631 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3632 onNetworkSuspended(network);
3633 }
3634 onCapabilitiesChanged(network, networkCapabilities);
3635 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003636 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003637 }
3638
3639 /**
3640 * Called when the framework connects and has declared a new network ready for use.
3641 *
3642 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3643 * be available at the same time, and onAvailable will be called for each of these as they
3644 * appear.
3645 *
3646 * <p>For callbacks registered with {@link #requestNetwork} and
3647 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3648 * is the new best network for this request and is now tracked by this callback ; this
3649 * callback will no longer receive method calls about other networks that may have been
3650 * passed to this method previously. The previously-best network may have disconnected, or
3651 * it may still be around and the newly-best network may simply be better.
3652 *
3653 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3654 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3655 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3656 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3657 *
3658 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3659 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3660 * this callback as this is prone to race conditions (there is no guarantee the objects
3661 * returned by these methods will be current). Instead, wait for a call to
3662 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3663 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3664 * to be well-ordered with respect to other callbacks.
3665 *
3666 * @param network The {@link Network} of the satisfying network.
3667 */
3668 public void onAvailable(@NonNull Network network) {}
3669
3670 /**
3671 * Called when the network is about to be lost, typically because there are no outstanding
3672 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3673 * with the new replacement network for graceful handover. This method is not guaranteed
3674 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3675 * network is suddenly disconnected.
3676 *
3677 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3678 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3679 * this callback as this is prone to race conditions ; calling these methods while in a
3680 * callback may return an outdated or even a null object.
3681 *
3682 * @param network The {@link Network} that is about to be lost.
3683 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3684 * connected for graceful handover; note that the network may still
3685 * suffer a hard loss at any time.
3686 */
3687 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3688
3689 /**
3690 * Called when a network disconnects or otherwise no longer satisfies this request or
3691 * callback.
3692 *
3693 * <p>If the callback was registered with requestNetwork() or
3694 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3695 * returned by onAvailable() when that network is lost and no other network satisfies
3696 * the criteria of the request.
3697 *
3698 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3699 * each network which no longer satisfies the criteria of the callback.
3700 *
3701 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3702 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3703 * this callback as this is prone to race conditions ; calling these methods while in a
3704 * callback may return an outdated or even a null object.
3705 *
3706 * @param network The {@link Network} lost.
3707 */
3708 public void onLost(@NonNull Network network) {}
3709
3710 /**
3711 * Called if no network is found within the timeout time specified in
3712 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3713 * requested network request cannot be fulfilled (whether or not a timeout was
3714 * specified). When this callback is invoked the associated
3715 * {@link NetworkRequest} will have already been removed and released, as if
3716 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3717 */
3718 public void onUnavailable() {}
3719
3720 /**
3721 * Called when the network corresponding to this request changes capabilities but still
3722 * satisfies the requested criteria.
3723 *
3724 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3725 * to be called immediately after {@link #onAvailable}.
3726 *
3727 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3728 * ConnectivityManager methods in this callback as this is prone to race conditions :
3729 * calling these methods while in a callback may return an outdated or even a null object.
3730 *
3731 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003732 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003733 * network.
3734 */
3735 public void onCapabilitiesChanged(@NonNull Network network,
3736 @NonNull NetworkCapabilities networkCapabilities) {}
3737
3738 /**
3739 * Called when the network corresponding to this request changes {@link LinkProperties}.
3740 *
3741 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3742 * to be called immediately after {@link #onAvailable}.
3743 *
3744 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3745 * ConnectivityManager methods in this callback as this is prone to race conditions :
3746 * calling these methods while in a callback may return an outdated or even a null object.
3747 *
3748 * @param network The {@link Network} whose link properties have changed.
3749 * @param linkProperties The new {@link LinkProperties} for this network.
3750 */
3751 public void onLinkPropertiesChanged(@NonNull Network network,
3752 @NonNull LinkProperties linkProperties) {}
3753
3754 /**
3755 * Called when the network the framework connected to for this request suspends data
3756 * transmission temporarily.
3757 *
3758 * <p>This generally means that while the TCP connections are still live temporarily
3759 * network data fails to transfer. To give a specific example, this is used on cellular
3760 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3761 * means read operations on sockets on this network will block once the buffers are
3762 * drained, and write operations will block once the buffers are full.
3763 *
3764 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3765 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3766 * this callback as this is prone to race conditions (there is no guarantee the objects
3767 * returned by these methods will be current).
3768 *
3769 * @hide
3770 */
3771 public void onNetworkSuspended(@NonNull Network network) {}
3772
3773 /**
3774 * Called when the network the framework connected to for this request
3775 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3776 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3777
3778 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3779 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3780 * this callback as this is prone to race conditions : calling these methods while in a
3781 * callback may return an outdated or even a null object.
3782 *
3783 * @hide
3784 */
3785 public void onNetworkResumed(@NonNull Network network) {}
3786
3787 /**
3788 * Called when access to the specified network is blocked or unblocked.
3789 *
3790 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3791 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3792 * this callback as this is prone to race conditions : calling these methods while in a
3793 * callback may return an outdated or even a null object.
3794 *
3795 * @param network The {@link Network} whose blocked status has changed.
3796 * @param blocked The blocked status of this {@link Network}.
3797 */
3798 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3799
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003800 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09003801 * Called when access to the specified network is blocked or unblocked, or the reason for
3802 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003803 *
3804 * If a NetworkCallback object implements this method,
3805 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3806 *
3807 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3808 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3809 * this callback as this is prone to race conditions : calling these methods while in a
3810 * callback may return an outdated or even a null object.
3811 *
3812 * @param network The {@link Network} whose blocked status has changed.
3813 * @param blocked The blocked status of this {@link Network}.
3814 * @hide
3815 */
3816 @SystemApi(client = MODULE_LIBRARIES)
3817 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3818 onBlockedStatusChanged(network, blocked != 0);
3819 }
3820
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003821 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08003822 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003823 }
3824
3825 /**
3826 * Constant error codes used by ConnectivityService to communicate about failures and errors
3827 * across a Binder boundary.
3828 * @hide
3829 */
3830 public interface Errors {
3831 int TOO_MANY_REQUESTS = 1;
3832 }
3833
3834 /** @hide */
3835 public static class TooManyRequestsException extends RuntimeException {}
3836
3837 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3838 switch (e.errorCode) {
3839 case Errors.TOO_MANY_REQUESTS:
3840 return new TooManyRequestsException();
3841 default:
3842 Log.w(TAG, "Unknown service error code " + e.errorCode);
3843 return new RuntimeException(e);
3844 }
3845 }
3846
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003847 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003848 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003849 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003850 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003851 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003852 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003853 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003854 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003855 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003856 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003857 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003858 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003859 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003860 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003861 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003862 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003863 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003864 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003865 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003866 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003867 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003868 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003869
3870 /** @hide */
3871 public static String getCallbackName(int whichCallback) {
3872 switch (whichCallback) {
3873 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3874 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3875 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3876 case CALLBACK_LOST: return "CALLBACK_LOST";
3877 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3878 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3879 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
3880 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3881 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3882 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
3883 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
3884 default:
3885 return Integer.toString(whichCallback);
3886 }
3887 }
3888
3889 private class CallbackHandler extends Handler {
3890 private static final String TAG = "ConnectivityManager.CallbackHandler";
3891 private static final boolean DBG = false;
3892
3893 CallbackHandler(Looper looper) {
3894 super(looper);
3895 }
3896
3897 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003898 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003899 }
3900
3901 @Override
3902 public void handleMessage(Message message) {
3903 if (message.what == EXPIRE_LEGACY_REQUEST) {
3904 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3905 return;
3906 }
3907
3908 final NetworkRequest request = getObject(message, NetworkRequest.class);
3909 final Network network = getObject(message, Network.class);
3910 final NetworkCallback callback;
3911 synchronized (sCallbacks) {
3912 callback = sCallbacks.get(request);
3913 if (callback == null) {
3914 Log.w(TAG,
3915 "callback not found for " + getCallbackName(message.what) + " message");
3916 return;
3917 }
3918 if (message.what == CALLBACK_UNAVAIL) {
3919 sCallbacks.remove(request);
3920 callback.networkRequest = ALREADY_UNREGISTERED;
3921 }
3922 }
3923 if (DBG) {
3924 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
3925 }
3926
3927 switch (message.what) {
3928 case CALLBACK_PRECHECK: {
3929 callback.onPreCheck(network);
3930 break;
3931 }
3932 case CALLBACK_AVAILABLE: {
3933 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3934 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003935 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003936 break;
3937 }
3938 case CALLBACK_LOSING: {
3939 callback.onLosing(network, message.arg1);
3940 break;
3941 }
3942 case CALLBACK_LOST: {
3943 callback.onLost(network);
3944 break;
3945 }
3946 case CALLBACK_UNAVAIL: {
3947 callback.onUnavailable();
3948 break;
3949 }
3950 case CALLBACK_CAP_CHANGED: {
3951 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3952 callback.onCapabilitiesChanged(network, cap);
3953 break;
3954 }
3955 case CALLBACK_IP_CHANGED: {
3956 LinkProperties lp = getObject(message, LinkProperties.class);
3957 callback.onLinkPropertiesChanged(network, lp);
3958 break;
3959 }
3960 case CALLBACK_SUSPENDED: {
3961 callback.onNetworkSuspended(network);
3962 break;
3963 }
3964 case CALLBACK_RESUMED: {
3965 callback.onNetworkResumed(network);
3966 break;
3967 }
3968 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003969 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003970 }
3971 }
3972 }
3973
3974 private <T> T getObject(Message msg, Class<T> c) {
3975 return (T) msg.getData().getParcelable(c.getSimpleName());
3976 }
3977 }
3978
3979 private CallbackHandler getDefaultHandler() {
3980 synchronized (sCallbacks) {
3981 if (sCallbackHandler == null) {
3982 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
3983 }
3984 return sCallbackHandler;
3985 }
3986 }
3987
3988 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3989 private static CallbackHandler sCallbackHandler;
3990
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003991 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3992 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3993 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003994 printStackTrace();
3995 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003996 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3997 throw new IllegalArgumentException("null NetworkCapabilities");
3998 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003999 final NetworkRequest request;
4000 final String callingPackageName = mContext.getOpPackageName();
4001 try {
4002 synchronized(sCallbacks) {
4003 if (callback.networkRequest != null
4004 && callback.networkRequest != ALREADY_UNREGISTERED) {
4005 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4006 // and requests (http://b/20701525).
4007 Log.e(TAG, "NetworkCallback was already registered");
4008 }
4009 Messenger messenger = new Messenger(handler);
4010 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004011 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004012 if (reqType == LISTEN) {
4013 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004014 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004015 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004016 } else {
4017 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004018 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4019 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004020 }
4021 if (request != null) {
4022 sCallbacks.put(request, callback);
4023 }
4024 callback.networkRequest = request;
4025 }
4026 } catch (RemoteException e) {
4027 throw e.rethrowFromSystemServer();
4028 } catch (ServiceSpecificException e) {
4029 throw convertServiceException(e);
4030 }
4031 return request;
4032 }
4033
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004034 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4035 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4036 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4037 legacyType, handler);
4038 }
4039
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004040 /**
4041 * Helper function to request a network with a particular legacy type.
4042 *
4043 * This API is only for use in internal system code that requests networks with legacy type and
4044 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4045 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4046 *
4047 * @param request {@link NetworkRequest} describing this request.
4048 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4049 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4050 * be a positive value (i.e. >0).
4051 * @param legacyType to specify the network type(#TYPE_*).
4052 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4053 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4054 * the callback must not be shared - it uniquely specifies this request.
4055 *
4056 * @hide
4057 */
4058 @SystemApi
4059 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4060 public void requestNetwork(@NonNull NetworkRequest request,
4061 int timeoutMs, int legacyType, @NonNull Handler handler,
4062 @NonNull NetworkCallback networkCallback) {
4063 if (legacyType == TYPE_NONE) {
4064 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4065 }
4066 CallbackHandler cbHandler = new CallbackHandler(handler);
4067 NetworkCapabilities nc = request.networkCapabilities;
4068 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4069 }
4070
4071 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004072 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004073 *
4074 * <p>This method will attempt to find the best network that matches the passed
4075 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4076 * criteria. The platform will evaluate which network is the best at its own discretion.
4077 * Throughput, latency, cost per byte, policy, user preference and other considerations
4078 * may be factored in the decision of what is considered the best network.
4079 *
4080 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4081 * matching this request, while always attempting to match the request to a better network if
4082 * possible. If a better match is found, the platform will switch this request to the now-best
4083 * network and inform the app of the newly best network by invoking
4084 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4085 * will not try to maintain any other network than the best one currently matching the request:
4086 * a network not matching any network request may be disconnected at any time.
4087 *
4088 * <p>For example, an application could use this method to obtain a connected cellular network
4089 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4090 * radio to consume additional power. Or, an application could inform the system that it wants
4091 * a network supporting sending MMSes and have the system let it know about the currently best
4092 * MMS-supporting network through the provided {@link NetworkCallback}.
4093 *
4094 * <p>The status of the request can be followed by listening to the various callbacks described
4095 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4096 * used to direct traffic to the network (although accessing some networks may be subject to
4097 * holding specific permissions). Callers will learn about the specific characteristics of the
4098 * network through
4099 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4100 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4101 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4102 * matching the request at any given time; therefore when a better network matching the request
4103 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4104 * with the new network after which no further updates are given about the previously-best
4105 * network, unless it becomes the best again at some later time. All callbacks are invoked
4106 * in order on the same thread, which by default is a thread created by the framework running
4107 * in the app.
4108 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4109 * callbacks are invoked.
4110 *
4111 * <p>This{@link NetworkRequest} will live until released via
4112 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4113 * which point the system may let go of the network at any time.
4114 *
4115 * <p>A version of this method which takes a timeout is
4116 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4117 * wait for a limited amount of time for the network to become unavailable.
4118 *
4119 * <p>It is presently unsupported to request a network with mutable
4120 * {@link NetworkCapabilities} such as
4121 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4122 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4123 * as these {@code NetworkCapabilities} represent states that a particular
4124 * network may never attain, and whether a network will attain these states
4125 * is unknown prior to bringing up the network so the framework does not
4126 * know how to go about satisfying a request with these capabilities.
4127 *
4128 * <p>This method requires the caller to hold either the
4129 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4130 * or the ability to modify system settings as determined by
4131 * {@link android.provider.Settings.System#canWrite}.</p>
4132 *
4133 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4134 * number of outstanding requests to 100 per app (identified by their UID), shared with
4135 * all variants of this method, of {@link #registerNetworkCallback} as well as
4136 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4137 * Requesting a network with this method will count toward this limit. If this limit is
4138 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4139 * make sure to unregister the callbacks with
4140 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4141 *
4142 * @param request {@link NetworkRequest} describing this request.
4143 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4144 * the callback must not be shared - it uniquely specifies this request.
4145 * The callback is invoked on the default internal Handler.
4146 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4147 * @throws SecurityException if missing the appropriate permissions.
4148 * @throws RuntimeException if the app already has too many callbacks registered.
4149 */
4150 public void requestNetwork(@NonNull NetworkRequest request,
4151 @NonNull NetworkCallback networkCallback) {
4152 requestNetwork(request, networkCallback, getDefaultHandler());
4153 }
4154
4155 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004156 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004157 *
4158 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4159 * but runs all the callbacks on the passed Handler.
4160 *
4161 * <p>This method has the same permission requirements as
4162 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4163 * and throws the same exceptions in the same conditions.
4164 *
4165 * @param request {@link NetworkRequest} describing this request.
4166 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4167 * the callback must not be shared - it uniquely specifies this request.
4168 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4169 */
4170 public void requestNetwork(@NonNull NetworkRequest request,
4171 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4172 CallbackHandler cbHandler = new CallbackHandler(handler);
4173 NetworkCapabilities nc = request.networkCapabilities;
4174 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4175 }
4176
4177 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004178 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004179 * by a timeout.
4180 *
4181 * This function behaves identically to the non-timed-out version
4182 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4183 * is not found within the given time (in milliseconds) the
4184 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4185 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4186 * not have to be released if timed-out (it is automatically released). Unregistering a
4187 * request that timed out is not an error.
4188 *
4189 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4190 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4191 * for that purpose. Calling this method will attempt to bring up the requested network.
4192 *
4193 * <p>This method has the same permission requirements as
4194 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4195 * and throws the same exceptions in the same conditions.
4196 *
4197 * @param request {@link NetworkRequest} describing this request.
4198 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4199 * the callback must not be shared - it uniquely specifies this request.
4200 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4201 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4202 * be a positive value (i.e. >0).
4203 */
4204 public void requestNetwork(@NonNull NetworkRequest request,
4205 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4206 checkTimeout(timeoutMs);
4207 NetworkCapabilities nc = request.networkCapabilities;
4208 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4209 getDefaultHandler());
4210 }
4211
4212 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004213 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004214 * by a timeout.
4215 *
4216 * This method behaves identically to
4217 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4218 * on the passed Handler.
4219 *
4220 * <p>This method has the same permission requirements as
4221 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4222 * and throws the same exceptions in the same conditions.
4223 *
4224 * @param request {@link NetworkRequest} describing this request.
4225 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4226 * the callback must not be shared - it uniquely specifies this request.
4227 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4228 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4229 * before {@link NetworkCallback#onUnavailable} is called.
4230 */
4231 public void requestNetwork(@NonNull NetworkRequest request,
4232 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4233 checkTimeout(timeoutMs);
4234 CallbackHandler cbHandler = new CallbackHandler(handler);
4235 NetworkCapabilities nc = request.networkCapabilities;
4236 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4237 }
4238
4239 /**
4240 * The lookup key for a {@link Network} object included with the intent after
4241 * successfully finding a network for the applications request. Retrieve it with
4242 * {@link android.content.Intent#getParcelableExtra(String)}.
4243 * <p>
4244 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4245 * then you must get a ConnectivityManager instance before doing so.
4246 */
4247 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4248
4249 /**
4250 * The lookup key for a {@link NetworkRequest} object included with the intent after
4251 * successfully finding a network for the applications request. Retrieve it with
4252 * {@link android.content.Intent#getParcelableExtra(String)}.
4253 */
4254 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4255
4256
4257 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004258 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004259 *
4260 * This function behaves identically to the version that takes a NetworkCallback, but instead
4261 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4262 * the request may outlive the calling application and get called back when a suitable
4263 * network is found.
4264 * <p>
4265 * The operation is an Intent broadcast that goes to a broadcast receiver that
4266 * you registered with {@link Context#registerReceiver} or through the
4267 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4268 * <p>
4269 * The operation Intent is delivered with two extras, a {@link Network} typed
4270 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4271 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4272 * the original requests parameters. It is important to create a new,
4273 * {@link NetworkCallback} based request before completing the processing of the
4274 * Intent to reserve the network or it will be released shortly after the Intent
4275 * is processed.
4276 * <p>
4277 * If there is already a request for this Intent registered (with the equality of
4278 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4279 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4280 * <p>
4281 * The request may be released normally by calling
4282 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4283 * <p>It is presently unsupported to request a network with either
4284 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4285 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4286 * as these {@code NetworkCapabilities} represent states that a particular
4287 * network may never attain, and whether a network will attain these states
4288 * is unknown prior to bringing up the network so the framework does not
4289 * know how to go about satisfying a request with these capabilities.
4290 *
4291 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4292 * number of outstanding requests to 100 per app (identified by their UID), shared with
4293 * all variants of this method, of {@link #registerNetworkCallback} as well as
4294 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4295 * Requesting a network with this method will count toward this limit. If this limit is
4296 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4297 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4298 * or {@link #releaseNetworkRequest(PendingIntent)}.
4299 *
4300 * <p>This method requires the caller to hold either the
4301 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4302 * or the ability to modify system settings as determined by
4303 * {@link android.provider.Settings.System#canWrite}.</p>
4304 *
4305 * @param request {@link NetworkRequest} describing this request.
4306 * @param operation Action to perform when the network is available (corresponds
4307 * to the {@link NetworkCallback#onAvailable} call. Typically
4308 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4309 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4310 * @throws SecurityException if missing the appropriate permissions.
4311 * @throws RuntimeException if the app already has too many callbacks registered.
4312 */
4313 public void requestNetwork(@NonNull NetworkRequest request,
4314 @NonNull PendingIntent operation) {
4315 printStackTrace();
4316 checkPendingIntentNotNull(operation);
4317 try {
4318 mService.pendingRequestForNetwork(
4319 request.networkCapabilities, operation, mContext.getOpPackageName(),
4320 getAttributionTag());
4321 } catch (RemoteException e) {
4322 throw e.rethrowFromSystemServer();
4323 } catch (ServiceSpecificException e) {
4324 throw convertServiceException(e);
4325 }
4326 }
4327
4328 /**
4329 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4330 * <p>
4331 * This method has the same behavior as
4332 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4333 * releasing network resources and disconnecting.
4334 *
4335 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4336 * PendingIntent passed to
4337 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4338 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4339 */
4340 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4341 printStackTrace();
4342 checkPendingIntentNotNull(operation);
4343 try {
4344 mService.releasePendingNetworkRequest(operation);
4345 } catch (RemoteException e) {
4346 throw e.rethrowFromSystemServer();
4347 }
4348 }
4349
4350 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004351 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004352 }
4353
4354 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004355 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004356 }
4357
4358 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004359 if (timeoutMs <= 0) {
4360 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4361 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004362 }
4363
4364 /**
4365 * Registers to receive notifications about all networks which satisfy the given
4366 * {@link NetworkRequest}. The callbacks will continue to be called until
4367 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4368 * called.
4369 *
4370 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4371 * number of outstanding requests to 100 per app (identified by their UID), shared with
4372 * all variants of this method, of {@link #requestNetwork} as well as
4373 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4374 * Requesting a network with this method will count toward this limit. If this limit is
4375 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4376 * make sure to unregister the callbacks with
4377 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4378 *
4379 * @param request {@link NetworkRequest} describing this request.
4380 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4381 * networks change state.
4382 * The callback is invoked on the default internal Handler.
4383 * @throws RuntimeException if the app already has too many callbacks registered.
4384 */
4385 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4386 public void registerNetworkCallback(@NonNull NetworkRequest request,
4387 @NonNull NetworkCallback networkCallback) {
4388 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4389 }
4390
4391 /**
4392 * Registers to receive notifications about all networks which satisfy the given
4393 * {@link NetworkRequest}. The callbacks will continue to be called until
4394 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4395 * called.
4396 *
4397 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4398 * number of outstanding requests to 100 per app (identified by their UID), shared with
4399 * all variants of this method, of {@link #requestNetwork} as well as
4400 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4401 * Requesting a network with this method will count toward this limit. If this limit is
4402 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4403 * make sure to unregister the callbacks with
4404 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4405 *
4406 *
4407 * @param request {@link NetworkRequest} describing this request.
4408 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4409 * networks change state.
4410 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4411 * @throws RuntimeException if the app already has too many callbacks registered.
4412 */
4413 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4414 public void registerNetworkCallback(@NonNull NetworkRequest request,
4415 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4416 CallbackHandler cbHandler = new CallbackHandler(handler);
4417 NetworkCapabilities nc = request.networkCapabilities;
4418 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4419 }
4420
4421 /**
4422 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4423 * {@link NetworkRequest}.
4424 *
4425 * This function behaves identically to the version that takes a NetworkCallback, but instead
4426 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4427 * the request may outlive the calling application and get called back when a suitable
4428 * network is found.
4429 * <p>
4430 * The operation is an Intent broadcast that goes to a broadcast receiver that
4431 * you registered with {@link Context#registerReceiver} or through the
4432 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4433 * <p>
4434 * The operation Intent is delivered with two extras, a {@link Network} typed
4435 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4436 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4437 * the original requests parameters.
4438 * <p>
4439 * If there is already a request for this Intent registered (with the equality of
4440 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4441 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4442 * <p>
4443 * The request may be released normally by calling
4444 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4445 *
4446 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4447 * number of outstanding requests to 100 per app (identified by their UID), shared with
4448 * all variants of this method, of {@link #requestNetwork} as well as
4449 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4450 * Requesting a network with this method will count toward this limit. If this limit is
4451 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4452 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4453 * or {@link #releaseNetworkRequest(PendingIntent)}.
4454 *
4455 * @param request {@link NetworkRequest} describing this request.
4456 * @param operation Action to perform when the network is available (corresponds
4457 * to the {@link NetworkCallback#onAvailable} call. Typically
4458 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4459 * @throws RuntimeException if the app already has too many callbacks registered.
4460 */
4461 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4462 public void registerNetworkCallback(@NonNull NetworkRequest request,
4463 @NonNull PendingIntent operation) {
4464 printStackTrace();
4465 checkPendingIntentNotNull(operation);
4466 try {
4467 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004468 request.networkCapabilities, operation, mContext.getOpPackageName(),
4469 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004470 } catch (RemoteException e) {
4471 throw e.rethrowFromSystemServer();
4472 } catch (ServiceSpecificException e) {
4473 throw convertServiceException(e);
4474 }
4475 }
4476
4477 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004478 * Registers to receive notifications about changes in the application's default network. This
4479 * may be a physical network or a virtual network, such as a VPN that applies to the
4480 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004481 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4482 *
4483 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4484 * number of outstanding requests to 100 per app (identified by their UID), shared with
4485 * all variants of this method, of {@link #requestNetwork} as well as
4486 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4487 * Requesting a network with this method will count toward this limit. If this limit is
4488 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4489 * make sure to unregister the callbacks with
4490 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4491 *
4492 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004493 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004494 * The callback is invoked on the default internal Handler.
4495 * @throws RuntimeException if the app already has too many callbacks registered.
4496 */
4497 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4498 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4499 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4500 }
4501
4502 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004503 * Registers to receive notifications about changes in the application's default network. This
4504 * may be a physical network or a virtual network, such as a VPN that applies to the
4505 * application. The callbacks will continue to be called until either the application exits or
4506 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4507 *
4508 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4509 * number of outstanding requests to 100 per app (identified by their UID), shared with
4510 * all variants of this method, of {@link #requestNetwork} as well as
4511 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4512 * Requesting a network with this method will count toward this limit. If this limit is
4513 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4514 * make sure to unregister the callbacks with
4515 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4516 *
4517 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4518 * application's default network changes.
4519 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4520 * @throws RuntimeException if the app already has too many callbacks registered.
4521 */
4522 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4523 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4524 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004525 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004526 }
4527
4528 /**
4529 * Registers to receive notifications about changes in the default network for the specified
4530 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4531 * UID. The callbacks will continue to be called until either the application exits or
4532 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4533 *
4534 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4535 * number of outstanding requests to 100 per app (identified by their UID), shared with
4536 * all variants of this method, of {@link #requestNetwork} as well as
4537 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4538 * Requesting a network with this method will count toward this limit. If this limit is
4539 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4540 * make sure to unregister the callbacks with
4541 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4542 *
4543 * @param uid the UID for which to track default network changes.
4544 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4545 * UID's default network changes.
4546 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4547 * @throws RuntimeException if the app already has too many callbacks registered.
4548 * @hide
4549 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004550 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004551 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4552 @RequiresPermission(anyOf = {
4553 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4554 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004555 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004556 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004557 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004558 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004559 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4560 }
4561
4562 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004563 * Registers to receive notifications about changes in the system default network. The callbacks
4564 * will continue to be called until either the application exits or
4565 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4566 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004567 * This method should not be used to determine networking state seen by applications, because in
4568 * many cases, most or even all application traffic may not use the default network directly,
4569 * and traffic from different applications may go on different networks by default. As an
4570 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4571 * and not onto the system default network. Applications or system components desiring to do
4572 * determine network state as seen by applications should use other methods such as
4573 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4574 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004575 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4576 * number of outstanding requests to 100 per app (identified by their UID), shared with
4577 * all variants of this method, of {@link #requestNetwork} as well as
4578 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4579 * Requesting a network with this method will count toward this limit. If this limit is
4580 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4581 * make sure to unregister the callbacks with
4582 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4583 *
4584 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4585 * system default network changes.
4586 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4587 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004588 *
4589 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004590 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004591 @SystemApi(client = MODULE_LIBRARIES)
4592 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4593 @RequiresPermission(anyOf = {
4594 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4595 android.Manifest.permission.NETWORK_SETTINGS})
4596 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004597 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004598 CallbackHandler cbHandler = new CallbackHandler(handler);
4599 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004600 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004601 }
4602
4603 /**
junyulaibd123062021-03-15 11:48:48 +08004604 * Registers to receive notifications about the best matching network which satisfy the given
4605 * {@link NetworkRequest}. The callbacks will continue to be called until
4606 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4607 * called.
4608 *
4609 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4610 * number of outstanding requests to 100 per app (identified by their UID), shared with
4611 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4612 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4613 * Requesting a network with this method will count toward this limit. If this limit is
4614 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4615 * make sure to unregister the callbacks with
4616 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4617 *
4618 *
4619 * @param request {@link NetworkRequest} describing this request.
4620 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4621 * networks change state.
4622 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4623 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004624 */
junyulai5a5c99b2021-03-05 15:51:17 +08004625 @SuppressLint("ExecutorRegistration")
4626 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4627 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4628 final NetworkCapabilities nc = request.networkCapabilities;
4629 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004630 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004631 }
4632
4633 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004634 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4635 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4636 * network connection for updated bandwidth information. The caller will be notified via
4637 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4638 * method assumes that the caller has previously called
4639 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4640 * changes.
4641 *
4642 * @param network {@link Network} specifying which network you're interested.
4643 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4644 */
4645 public boolean requestBandwidthUpdate(@NonNull Network network) {
4646 try {
4647 return mService.requestBandwidthUpdate(network);
4648 } catch (RemoteException e) {
4649 throw e.rethrowFromSystemServer();
4650 }
4651 }
4652
4653 /**
4654 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4655 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4656 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4657 * If the given {@code NetworkCallback} had previously been used with
4658 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4659 * will be disconnected.
4660 *
4661 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4662 * triggering it as soon as this call returns.
4663 *
4664 * @param networkCallback The {@link NetworkCallback} used when making the request.
4665 */
4666 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4667 printStackTrace();
4668 checkCallbackNotNull(networkCallback);
4669 final List<NetworkRequest> reqs = new ArrayList<>();
4670 // Find all requests associated to this callback and stop callback triggers immediately.
4671 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4672 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004673 if (networkCallback.networkRequest == null) {
4674 throw new IllegalArgumentException("NetworkCallback was not registered");
4675 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004676 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4677 Log.d(TAG, "NetworkCallback was already unregistered");
4678 return;
4679 }
4680 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4681 if (e.getValue() == networkCallback) {
4682 reqs.add(e.getKey());
4683 }
4684 }
4685 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4686 for (NetworkRequest r : reqs) {
4687 try {
4688 mService.releaseNetworkRequest(r);
4689 } catch (RemoteException e) {
4690 throw e.rethrowFromSystemServer();
4691 }
4692 // Only remove mapping if rpc was successful.
4693 sCallbacks.remove(r);
4694 }
4695 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4696 }
4697 }
4698
4699 /**
4700 * Unregisters a callback previously registered via
4701 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4702 *
4703 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4704 * PendingIntent passed to
4705 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4706 * Cannot be null.
4707 */
4708 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4709 releaseNetworkRequest(operation);
4710 }
4711
4712 /**
4713 * Informs the system whether it should switch to {@code network} regardless of whether it is
4714 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4715 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4716 * the system default network regardless of any other network that's currently connected. If
4717 * {@code always} is true, then the choice is remembered, so that the next time the user
4718 * connects to this network, the system will switch to it.
4719 *
4720 * @param network The network to accept.
4721 * @param accept Whether to accept the network even if unvalidated.
4722 * @param always Whether to remember this choice in the future.
4723 *
4724 * @hide
4725 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004726 @SystemApi(client = MODULE_LIBRARIES)
4727 @RequiresPermission(anyOf = {
4728 android.Manifest.permission.NETWORK_SETTINGS,
4729 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4730 android.Manifest.permission.NETWORK_STACK,
4731 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4732 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004733 try {
4734 mService.setAcceptUnvalidated(network, accept, always);
4735 } catch (RemoteException e) {
4736 throw e.rethrowFromSystemServer();
4737 }
4738 }
4739
4740 /**
4741 * Informs the system whether it should consider the network as validated even if it only has
4742 * partial connectivity. If {@code accept} is true, then the network will be considered as
4743 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4744 * is remembered, so that the next time the user connects to this network, the system will
4745 * switch to it.
4746 *
4747 * @param network The network to accept.
4748 * @param accept Whether to consider the network as validated even if it has partial
4749 * connectivity.
4750 * @param always Whether to remember this choice in the future.
4751 *
4752 * @hide
4753 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004754 @SystemApi(client = MODULE_LIBRARIES)
4755 @RequiresPermission(anyOf = {
4756 android.Manifest.permission.NETWORK_SETTINGS,
4757 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4758 android.Manifest.permission.NETWORK_STACK,
4759 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4760 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4761 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004762 try {
4763 mService.setAcceptPartialConnectivity(network, accept, always);
4764 } catch (RemoteException e) {
4765 throw e.rethrowFromSystemServer();
4766 }
4767 }
4768
4769 /**
4770 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4771 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4772 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4773 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4774 *
4775 * @param network The network to accept.
4776 *
4777 * @hide
4778 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004779 @SystemApi(client = MODULE_LIBRARIES)
4780 @RequiresPermission(anyOf = {
4781 android.Manifest.permission.NETWORK_SETTINGS,
4782 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4783 android.Manifest.permission.NETWORK_STACK,
4784 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4785 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004786 try {
4787 mService.setAvoidUnvalidated(network);
4788 } catch (RemoteException e) {
4789 throw e.rethrowFromSystemServer();
4790 }
4791 }
4792
4793 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004794 * Temporarily allow bad wifi to override {@code config_networkAvoidBadWifi} configuration.
4795 *
4796 * @param timeMs The expired current time. The value should be set within a limited time from
4797 * now.
4798 *
4799 * @hide
4800 */
4801 public void setTestAllowBadWifiUntil(long timeMs) {
4802 try {
4803 mService.setTestAllowBadWifiUntil(timeMs);
4804 } catch (RemoteException e) {
4805 throw e.rethrowFromSystemServer();
4806 }
4807 }
4808
4809 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004810 * Requests that the system open the captive portal app on the specified network.
4811 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004812 * <p>This is to be used on networks where a captive portal was detected, as per
4813 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4814 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004815 * @param network The network to log into.
4816 *
4817 * @hide
4818 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004819 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4820 @RequiresPermission(anyOf = {
4821 android.Manifest.permission.NETWORK_SETTINGS,
4822 android.Manifest.permission.NETWORK_STACK,
4823 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4824 })
4825 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004826 try {
4827 mService.startCaptivePortalApp(network);
4828 } catch (RemoteException e) {
4829 throw e.rethrowFromSystemServer();
4830 }
4831 }
4832
4833 /**
4834 * Requests that the system open the captive portal app with the specified extras.
4835 *
4836 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4837 * corresponding permission.
4838 * @param network Network on which the captive portal was detected.
4839 * @param appExtras Extras to include in the app start intent.
4840 * @hide
4841 */
4842 @SystemApi
4843 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4844 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4845 try {
4846 mService.startCaptivePortalAppInternal(network, appExtras);
4847 } catch (RemoteException e) {
4848 throw e.rethrowFromSystemServer();
4849 }
4850 }
4851
4852 /**
4853 * Determine whether the device is configured to avoid bad wifi.
4854 * @hide
4855 */
4856 @SystemApi
4857 @RequiresPermission(anyOf = {
4858 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4859 android.Manifest.permission.NETWORK_STACK})
4860 public boolean shouldAvoidBadWifi() {
4861 try {
4862 return mService.shouldAvoidBadWifi();
4863 } catch (RemoteException e) {
4864 throw e.rethrowFromSystemServer();
4865 }
4866 }
4867
4868 /**
4869 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4870 * time-sensitive user-facing operations when the system default network is temporarily
4871 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4872 * this method), and the operation should be infrequent to ensure that data usage is limited.
4873 *
4874 * An example of such an operation might be a time-sensitive foreground activity, such as a
4875 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4876 */
4877 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4878
4879 /**
4880 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4881 * a backup channel for traffic that is primarily going over another network.
4882 *
4883 * An example might be maintaining backup connections to peers or servers for the purpose of
4884 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4885 * on backup paths should be negligible compared to the traffic on the main path.
4886 */
4887 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4888
4889 /**
4890 * It is acceptable to use metered data to improve network latency and performance.
4891 */
4892 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4893
4894 /**
4895 * Return value to use for unmetered networks. On such networks we currently set all the flags
4896 * to true.
4897 * @hide
4898 */
4899 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4900 MULTIPATH_PREFERENCE_HANDOVER |
4901 MULTIPATH_PREFERENCE_RELIABILITY |
4902 MULTIPATH_PREFERENCE_PERFORMANCE;
4903
Aaron Huangcff22942021-05-27 16:31:26 +08004904 /** @hide */
4905 @Retention(RetentionPolicy.SOURCE)
4906 @IntDef(flag = true, value = {
4907 MULTIPATH_PREFERENCE_HANDOVER,
4908 MULTIPATH_PREFERENCE_RELIABILITY,
4909 MULTIPATH_PREFERENCE_PERFORMANCE,
4910 })
4911 public @interface MultipathPreference {
4912 }
4913
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004914 /**
4915 * Provides a hint to the calling application on whether it is desirable to use the
4916 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4917 * for multipath data transfer on this network when it is not the system default network.
4918 * Applications desiring to use multipath network protocols should call this method before
4919 * each such operation.
4920 *
4921 * @param network The network on which the application desires to use multipath data.
4922 * If {@code null}, this method will return the a preference that will generally
4923 * apply to metered networks.
4924 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4925 */
4926 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4927 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
4928 try {
4929 return mService.getMultipathPreference(network);
4930 } catch (RemoteException e) {
4931 throw e.rethrowFromSystemServer();
4932 }
4933 }
4934
4935 /**
4936 * Resets all connectivity manager settings back to factory defaults.
4937 * @hide
4938 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004939 @SystemApi(client = MODULE_LIBRARIES)
4940 @RequiresPermission(anyOf = {
4941 android.Manifest.permission.NETWORK_SETTINGS,
4942 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004943 public void factoryReset() {
4944 try {
4945 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09004946 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004947 } catch (RemoteException e) {
4948 throw e.rethrowFromSystemServer();
4949 }
4950 }
4951
4952 /**
4953 * Binds the current process to {@code network}. All Sockets created in the future
4954 * (and not explicitly bound via a bound SocketFactory from
4955 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4956 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4957 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4958 * work and all host name resolutions will fail. This is by design so an application doesn't
4959 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4960 * To clear binding pass {@code null} for {@code network}. Using individually bound
4961 * Sockets created by Network.getSocketFactory().createSocket() and
4962 * performing network-specific host name resolutions via
4963 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4964 * {@code bindProcessToNetwork}.
4965 *
4966 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4967 * the current binding.
4968 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4969 */
4970 public boolean bindProcessToNetwork(@Nullable Network network) {
4971 // Forcing callers to call through non-static function ensures ConnectivityManager
4972 // instantiated.
4973 return setProcessDefaultNetwork(network);
4974 }
4975
4976 /**
4977 * Binds the current process to {@code network}. All Sockets created in the future
4978 * (and not explicitly bound via a bound SocketFactory from
4979 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4980 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4981 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4982 * work and all host name resolutions will fail. This is by design so an application doesn't
4983 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4984 * To clear binding pass {@code null} for {@code network}. Using individually bound
4985 * Sockets created by Network.getSocketFactory().createSocket() and
4986 * performing network-specific host name resolutions via
4987 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4988 * {@code setProcessDefaultNetwork}.
4989 *
4990 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4991 * the current binding.
4992 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4993 * @deprecated This function can throw {@link IllegalStateException}. Use
4994 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4995 * is a direct replacement.
4996 */
4997 @Deprecated
4998 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
4999 int netId = (network == null) ? NETID_UNSET : network.netId;
5000 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5001
5002 if (netId != NETID_UNSET) {
5003 netId = network.getNetIdForResolv();
5004 }
5005
5006 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5007 return false;
5008 }
5009
5010 if (!isSameNetId) {
5011 // Set HTTP proxy system properties to match network.
5012 // TODO: Deprecate this static method and replace it with a non-static version.
5013 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005014 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005015 } catch (SecurityException e) {
5016 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5017 Log.e(TAG, "Can't set proxy properties", e);
5018 }
5019 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005020 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005021 // Must flush socket pool as idle sockets will be bound to previous network and may
5022 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005023 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005024 }
5025
5026 return true;
5027 }
5028
5029 /**
5030 * Returns the {@link Network} currently bound to this process via
5031 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5032 *
5033 * @return {@code Network} to which this process is bound, or {@code null}.
5034 */
5035 @Nullable
5036 public Network getBoundNetworkForProcess() {
5037 // Forcing callers to call thru non-static function ensures ConnectivityManager
5038 // instantiated.
5039 return getProcessDefaultNetwork();
5040 }
5041
5042 /**
5043 * Returns the {@link Network} currently bound to this process via
5044 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5045 *
5046 * @return {@code Network} to which this process is bound, or {@code null}.
5047 * @deprecated Using this function can lead to other functions throwing
5048 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5049 * {@code getBoundNetworkForProcess} is a direct replacement.
5050 */
5051 @Deprecated
5052 @Nullable
5053 public static Network getProcessDefaultNetwork() {
5054 int netId = NetworkUtils.getBoundNetworkForProcess();
5055 if (netId == NETID_UNSET) return null;
5056 return new Network(netId);
5057 }
5058
5059 private void unsupportedStartingFrom(int version) {
5060 if (Process.myUid() == Process.SYSTEM_UID) {
5061 // The getApplicationInfo() call we make below is not supported in system context. Let
5062 // the call through here, and rely on the fact that ConnectivityService will refuse to
5063 // allow the system to use these APIs anyway.
5064 return;
5065 }
5066
5067 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5068 throw new UnsupportedOperationException(
5069 "This method is not supported in target SDK version " + version + " and above");
5070 }
5071 }
5072
5073 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5074 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5075 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5076 // remove these exemptions. Note that this check is not secure, and apps can still access these
5077 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5078 // so is unsupported and may break in the future. http://b/22728205
5079 private void checkLegacyRoutingApiAccess() {
5080 unsupportedStartingFrom(VERSION_CODES.M);
5081 }
5082
5083 /**
5084 * Binds host resolutions performed by this process to {@code network}.
5085 * {@link #bindProcessToNetwork} takes precedence over this setting.
5086 *
5087 * @param network The {@link Network} to bind host resolutions from the current process to, or
5088 * {@code null} to clear the current binding.
5089 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5090 * @hide
5091 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5092 */
5093 @Deprecated
5094 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5095 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5096 return NetworkUtils.bindProcessToNetworkForHostResolution(
5097 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5098 }
5099
5100 /**
5101 * Device is not restricting metered network activity while application is running on
5102 * background.
5103 */
5104 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5105
5106 /**
5107 * Device is restricting metered network activity while application is running on background,
5108 * but application is allowed to bypass it.
5109 * <p>
5110 * In this state, application should take action to mitigate metered network access.
5111 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5112 */
5113 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5114
5115 /**
5116 * Device is restricting metered network activity while application is running on background.
5117 * <p>
5118 * In this state, application should not try to use the network while running on background,
5119 * because it would be denied.
5120 */
5121 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5122
5123 /**
5124 * A change in the background metered network activity restriction has occurred.
5125 * <p>
5126 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5127 * applies to them.
5128 * <p>
5129 * This is only sent to registered receivers, not manifest receivers.
5130 */
5131 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5132 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5133 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5134
Aaron Huangcff22942021-05-27 16:31:26 +08005135 /** @hide */
5136 @Retention(RetentionPolicy.SOURCE)
5137 @IntDef(flag = false, value = {
5138 RESTRICT_BACKGROUND_STATUS_DISABLED,
5139 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5140 RESTRICT_BACKGROUND_STATUS_ENABLED,
5141 })
5142 public @interface RestrictBackgroundStatus {
5143 }
5144
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005145 /**
5146 * Determines if the calling application is subject to metered network restrictions while
5147 * running on background.
5148 *
5149 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5150 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5151 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5152 */
5153 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5154 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005155 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005156 } catch (RemoteException e) {
5157 throw e.rethrowFromSystemServer();
5158 }
5159 }
5160
5161 /**
5162 * The network watchlist is a list of domains and IP addresses that are associated with
5163 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5164 * currently used by the system for validation purposes.
5165 *
5166 * @return Hash of network watchlist config file. Null if config does not exist.
5167 */
5168 @Nullable
5169 public byte[] getNetworkWatchlistConfigHash() {
5170 try {
5171 return mService.getNetworkWatchlistConfigHash();
5172 } catch (RemoteException e) {
5173 Log.e(TAG, "Unable to get watchlist config hash");
5174 throw e.rethrowFromSystemServer();
5175 }
5176 }
5177
5178 /**
5179 * Returns the {@code uid} of the owner of a network connection.
5180 *
5181 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5182 * IPPROTO_UDP} currently supported.
5183 * @param local The local {@link InetSocketAddress} of a connection.
5184 * @param remote The remote {@link InetSocketAddress} of a connection.
5185 * @return {@code uid} if the connection is found and the app has permission to observe it
5186 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5187 * android.os.Process#INVALID_UID} if the connection is not found.
5188 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5189 * user.
5190 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5191 */
5192 public int getConnectionOwnerUid(
5193 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5194 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5195 try {
5196 return mService.getConnectionOwnerUid(connectionInfo);
5197 } catch (RemoteException e) {
5198 throw e.rethrowFromSystemServer();
5199 }
5200 }
5201
5202 private void printStackTrace() {
5203 if (DEBUG) {
5204 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5205 final StringBuffer sb = new StringBuffer();
5206 for (int i = 3; i < callStack.length; i++) {
5207 final String stackTrace = callStack[i].toString();
5208 if (stackTrace == null || stackTrace.contains("android.os")) {
5209 break;
5210 }
5211 sb.append(" [").append(stackTrace).append("]");
5212 }
5213 Log.d(TAG, "StackLog:" + sb.toString());
5214 }
5215 }
5216
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005217 /** @hide */
5218 public TestNetworkManager startOrGetTestNetworkManager() {
5219 final IBinder tnBinder;
5220 try {
5221 tnBinder = mService.startOrGetTestNetworkService();
5222 } catch (RemoteException e) {
5223 throw e.rethrowFromSystemServer();
5224 }
5225
5226 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5227 }
5228
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005229 /** @hide */
5230 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5231 return new ConnectivityDiagnosticsManager(mContext, mService);
5232 }
5233
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005234 /**
5235 * Simulates a Data Stall for the specified Network.
5236 *
5237 * <p>This method should only be used for tests.
5238 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005239 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5240 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005241 *
5242 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005243 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5244 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5245 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005246 * @param network The Network for which a Data Stall is being simluated.
5247 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5248 * @throws SecurityException if the caller is not the owner of the given network.
5249 * @hide
5250 */
5251 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5252 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5253 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005254 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005255 @NonNull Network network, @NonNull PersistableBundle extras) {
5256 try {
5257 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5258 } catch (RemoteException e) {
5259 e.rethrowFromSystemServer();
5260 }
5261 }
5262
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005263 @NonNull
5264 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5265
5266 /**
5267 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5268 * receive available QoS events related to the {@link Network} and local ip + port
5269 * specified within socketInfo.
5270 * <p/>
5271 * The same {@link QosCallback} must be unregistered before being registered a second time,
5272 * otherwise {@link QosCallbackRegistrationException} is thrown.
5273 * <p/>
5274 * This API does not, in itself, require any permission if called with a network that is not
5275 * restricted. However, the underlying implementation currently only supports the IMS network,
5276 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5277 * useful, because they'd never be called back on networks that they would have access to.
5278 *
5279 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5280 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5281 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5282 * @throws RuntimeException if the app already has too many callbacks registered.
5283 *
5284 * Exceptions after the time of registration is passed through
5285 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5286 *
5287 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005288 * @param executor The executor on which the callback will be invoked. The provided
5289 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005290 * callbacks cannot be guaranteed.onQosCallbackRegistered
5291 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005292 *
5293 * @hide
5294 */
5295 @SystemApi
5296 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005297 @CallbackExecutor @NonNull final Executor executor,
5298 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005299 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005300 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005301 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005302
5303 try {
5304 synchronized (mQosCallbackConnections) {
5305 if (getQosCallbackConnection(callback) == null) {
5306 final QosCallbackConnection connection =
5307 new QosCallbackConnection(this, callback, executor);
5308 mQosCallbackConnections.add(connection);
5309 mService.registerQosSocketCallback(socketInfo, connection);
5310 } else {
5311 Log.e(TAG, "registerQosCallback: Callback already registered");
5312 throw new QosCallbackRegistrationException();
5313 }
5314 }
5315 } catch (final RemoteException e) {
5316 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5317
5318 // The same unregister method method is called for consistency even though nothing
5319 // will be sent to the ConnectivityService since the callback was never successfully
5320 // registered.
5321 unregisterQosCallback(callback);
5322 e.rethrowFromSystemServer();
5323 } catch (final ServiceSpecificException e) {
5324 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5325 unregisterQosCallback(callback);
5326 throw convertServiceException(e);
5327 }
5328 }
5329
5330 /**
5331 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5332 * events once unregistered and can be registered a second time.
5333 * <p/>
5334 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5335 *
5336 * @param callback the callback being unregistered
5337 *
5338 * @hide
5339 */
5340 @SystemApi
5341 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5342 Objects.requireNonNull(callback, "The callback must be non-null");
5343 try {
5344 synchronized (mQosCallbackConnections) {
5345 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5346 if (connection != null) {
5347 connection.stopReceivingMessages();
5348 mService.unregisterQosCallback(connection);
5349 mQosCallbackConnections.remove(connection);
5350 } else {
5351 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5352 }
5353 }
5354 } catch (final RemoteException e) {
5355 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5356 e.rethrowFromSystemServer();
5357 }
5358 }
5359
5360 /**
5361 * Gets the connection related to the callback.
5362 *
5363 * @param callback the callback to look up
5364 * @return the related connection
5365 */
5366 @Nullable
5367 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5368 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5369 // Checking by reference here is intentional
5370 if (connection.getCallback() == callback) {
5371 return connection;
5372 }
5373 }
5374 return null;
5375 }
5376
5377 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005378 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005379 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5380 * be used to request that the system provide a network without causing the network to be
5381 * in the foreground.
5382 *
5383 * <p>This method will attempt to find the best network that matches the passed
5384 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5385 * criteria. The platform will evaluate which network is the best at its own discretion.
5386 * Throughput, latency, cost per byte, policy, user preference and other considerations
5387 * may be factored in the decision of what is considered the best network.
5388 *
5389 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5390 * matching this request, while always attempting to match the request to a better network if
5391 * possible. If a better match is found, the platform will switch this request to the now-best
5392 * network and inform the app of the newly best network by invoking
5393 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5394 * will not try to maintain any other network than the best one currently matching the request:
5395 * a network not matching any network request may be disconnected at any time.
5396 *
5397 * <p>For example, an application could use this method to obtain a connected cellular network
5398 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5399 * radio to consume additional power. Or, an application could inform the system that it wants
5400 * a network supporting sending MMSes and have the system let it know about the currently best
5401 * MMS-supporting network through the provided {@link NetworkCallback}.
5402 *
5403 * <p>The status of the request can be followed by listening to the various callbacks described
5404 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5405 * used to direct traffic to the network (although accessing some networks may be subject to
5406 * holding specific permissions). Callers will learn about the specific characteristics of the
5407 * network through
5408 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5409 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5410 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5411 * matching the request at any given time; therefore when a better network matching the request
5412 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5413 * with the new network after which no further updates are given about the previously-best
5414 * network, unless it becomes the best again at some later time. All callbacks are invoked
5415 * in order on the same thread, which by default is a thread created by the framework running
5416 * in the app.
5417 *
5418 * <p>This{@link NetworkRequest} will live until released via
5419 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5420 * which point the system may let go of the network at any time.
5421 *
5422 * <p>It is presently unsupported to request a network with mutable
5423 * {@link NetworkCapabilities} such as
5424 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5425 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5426 * as these {@code NetworkCapabilities} represent states that a particular
5427 * network may never attain, and whether a network will attain these states
5428 * is unknown prior to bringing up the network so the framework does not
5429 * know how to go about satisfying a request with these capabilities.
5430 *
5431 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5432 * number of outstanding requests to 100 per app (identified by their UID), shared with
5433 * all variants of this method, of {@link #registerNetworkCallback} as well as
5434 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5435 * Requesting a network with this method will count toward this limit. If this limit is
5436 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5437 * make sure to unregister the callbacks with
5438 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5439 *
5440 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005441 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5442 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005443 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5444 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005445 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5446 * @throws SecurityException if missing the appropriate permissions.
5447 * @throws RuntimeException if the app already has too many callbacks registered.
5448 *
5449 * @hide
5450 */
5451 @SystemApi(client = MODULE_LIBRARIES)
5452 @SuppressLint("ExecutorRegistration")
5453 @RequiresPermission(anyOf = {
5454 android.Manifest.permission.NETWORK_SETTINGS,
5455 android.Manifest.permission.NETWORK_STACK,
5456 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5457 })
5458 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005459 @NonNull NetworkCallback networkCallback,
5460 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005461 final NetworkCapabilities nc = request.networkCapabilities;
5462 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005463 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005464 }
James Mattis12aeab82021-01-10 14:24:24 -08005465
5466 /**
James Mattis12aeab82021-01-10 14:24:24 -08005467 * Used by automotive devices to set the network preferences used to direct traffic at an
5468 * application level as per the given OemNetworkPreferences. An example use-case would be an
5469 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5470 * vehicle via a particular network.
5471 *
5472 * Calling this will overwrite the existing preference.
5473 *
5474 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5475 * @param executor the executor on which listener will be invoked.
5476 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5477 * communicate completion of setOemNetworkPreference(). This will only be
5478 * called once upon successful completion of setOemNetworkPreference().
5479 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5480 * @throws SecurityException if missing the appropriate permissions.
5481 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005482 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005483 */
James Mattis6e2d7022021-01-26 16:23:52 -08005484 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005485 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005486 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005487 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005488 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005489 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5490 if (null != listener) {
5491 Objects.requireNonNull(executor, "Executor must be non-null");
5492 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005493 final IOnCompleteListener listenerInternal = listener == null ? null :
5494 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005495 @Override
5496 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005497 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005498 }
5499 };
5500
5501 try {
5502 mService.setOemNetworkPreference(preference, listenerInternal);
5503 } catch (RemoteException e) {
5504 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5505 throw e.rethrowFromSystemServer();
5506 }
5507 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005508
Chalard Jeanad565e22021-02-25 17:23:40 +09005509 /**
5510 * Request that a user profile is put by default on a network matching a given preference.
5511 *
5512 * See the documentation for the individual preferences for a description of the supported
5513 * behaviors.
5514 *
5515 * @param profile the profile concerned.
5516 * @param preference the preference for this profile.
5517 * @param executor an executor to execute the listener on. Optional if listener is null.
5518 * @param listener an optional listener to listen for completion of the operation.
5519 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5520 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005521 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5522 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005523 * @hide
5524 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005525 // This function is for establishing per-profile default networking and can only be called by
5526 // the device policy manager, running as the system server. It would make no sense to call it
5527 // on a context for a user because it does not establish a setting on behalf of a user, rather
5528 // it establishes a setting for a user on behalf of the DPM.
5529 @SuppressLint({"UserHandle"})
5530 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005531 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005532 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005533 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005534 @ProfileNetworkPreferencePolicy final int preference,
5535 @Nullable @CallbackExecutor final Executor executor,
5536 @Nullable final Runnable listener) {
5537
5538 ProfileNetworkPreference.Builder preferenceBuilder =
5539 new ProfileNetworkPreference.Builder();
5540 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005541 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5542 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5543 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005544 setProfileNetworkPreferences(profile,
5545 List.of(preferenceBuilder.build()), executor, listener);
5546 }
5547
5548 /**
5549 * Set a list of default network selection policies for a user profile.
5550 *
5551 * Calling this API with a user handle defines the entire policy for that user handle.
5552 * It will overwrite any setting previously set for the same user profile,
5553 * and not affect previously set settings for other handles.
5554 *
5555 * Call this API with an empty list to remove settings for this user profile.
5556 *
5557 * See {@link ProfileNetworkPreference} for more details on each preference
5558 * parameter.
5559 *
5560 * @param profile the user profile for which the preference is being set.
5561 * @param profileNetworkPreferences the list of profile network preferences for the
5562 * provided profile.
5563 * @param executor an executor to execute the listener on. Optional if listener is null.
5564 * @param listener an optional listener to listen for completion of the operation.
5565 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5566 * @throws SecurityException if missing the appropriate permissions.
5567 * @hide
5568 */
5569 @SystemApi(client = MODULE_LIBRARIES)
5570 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5571 public void setProfileNetworkPreferences(
5572 @NonNull final UserHandle profile,
5573 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005574 @Nullable @CallbackExecutor final Executor executor,
5575 @Nullable final Runnable listener) {
5576 if (null != listener) {
5577 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5578 }
5579 final IOnCompleteListener proxy;
5580 if (null == listener) {
5581 proxy = null;
5582 } else {
5583 proxy = new IOnCompleteListener.Stub() {
5584 @Override
5585 public void onComplete() {
5586 executor.execute(listener::run);
5587 }
5588 };
5589 }
5590 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005591 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005592 } catch (RemoteException e) {
5593 throw e.rethrowFromSystemServer();
5594 }
5595 }
5596
lucaslin5cdbcfb2021-03-12 00:46:33 +08005597 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005598 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005599 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005600 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005601
5602 /**
5603 * Get the network ID range reserved for IPSec tunnel interfaces.
5604 *
5605 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5606 * @hide
5607 */
5608 @SystemApi(client = MODULE_LIBRARIES)
5609 @NonNull
5610 public static Range<Integer> getIpSecNetIdRange() {
5611 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5612 }
markchien738ad912021-12-09 18:15:45 +08005613
5614 /**
markchiene1561fa2021-12-09 22:00:56 +08005615 * Sets whether the specified UID is allowed to use data on metered networks even when
5616 * background data is restricted.
markchien738ad912021-12-09 18:15:45 +08005617 *
5618 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005619 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005620 * @hide
5621 */
5622 @SystemApi(client = MODULE_LIBRARIES)
5623 @RequiresPermission(anyOf = {
5624 android.Manifest.permission.NETWORK_SETTINGS,
5625 android.Manifest.permission.NETWORK_STACK,
5626 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5627 })
5628 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
5629 try {
5630 mService.updateMeteredNetworkAllowList(uid, add);
5631 } catch (RemoteException e) {
5632 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005633 }
5634 }
5635
5636 /**
markchiene1561fa2021-12-09 22:00:56 +08005637 * Sets whether the specified UID is prevented from using background data on metered networks.
5638 * Takes precedence over {@link #updateMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08005639 *
5640 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005641 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08005642 * @hide
5643 */
5644 @SystemApi(client = MODULE_LIBRARIES)
5645 @RequiresPermission(anyOf = {
5646 android.Manifest.permission.NETWORK_SETTINGS,
5647 android.Manifest.permission.NETWORK_STACK,
5648 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5649 })
5650 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
5651 try {
5652 mService.updateMeteredNetworkDenyList(uid, add);
5653 } catch (RemoteException e) {
5654 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08005655 }
5656 }
5657
5658 /**
5659 * Sets a firewall rule for the specified UID on the specified chain.
5660 *
5661 * @param chain target chain.
5662 * @param uid uid to allow/deny.
markchien68cfadc2022-01-14 13:39:54 +08005663 * @param allow whether networking is allowed or denied.
5664 * @throws IllegalStateException if updating firewall rule failed.
markchiene1561fa2021-12-09 22:00:56 +08005665 * @hide
5666 */
5667 @SystemApi(client = MODULE_LIBRARIES)
5668 @RequiresPermission(anyOf = {
5669 android.Manifest.permission.NETWORK_SETTINGS,
5670 android.Manifest.permission.NETWORK_STACK,
5671 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5672 })
5673 public void updateFirewallRule(@FirewallChain final int chain, final int uid,
5674 final boolean allow) {
5675 try {
5676 mService.updateFirewallRule(chain, uid, allow);
5677 } catch (RemoteException e) {
5678 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08005679 }
5680 }
markchien98a6f952022-01-13 23:43:53 +08005681
5682 /**
5683 * Enables or disables the specified firewall chain.
5684 *
5685 * @param chain target chain.
5686 * @param enable whether the chain should be enabled.
markchien68cfadc2022-01-14 13:39:54 +08005687 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08005688 * @hide
5689 */
5690 @SystemApi(client = MODULE_LIBRARIES)
5691 @RequiresPermission(anyOf = {
5692 android.Manifest.permission.NETWORK_SETTINGS,
5693 android.Manifest.permission.NETWORK_STACK,
5694 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5695 })
5696 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
5697 try {
5698 mService.setFirewallChainEnabled(chain, enable);
5699 } catch (RemoteException e) {
5700 throw e.rethrowFromSystemServer();
5701 }
5702 }
markchien00a0bed2022-01-13 23:46:13 +08005703
5704 /**
5705 * Replaces the contents of the specified UID-based firewall chain.
5706 *
5707 * @param chain target chain to replace.
5708 * @param uids The list of UIDs to be placed into chain.
markchien68cfadc2022-01-14 13:39:54 +08005709 * @throws IllegalStateException if replacing the firewall chain failed.
markchien00a0bed2022-01-13 23:46:13 +08005710 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
5711 * @hide
5712 */
5713 @SystemApi(client = MODULE_LIBRARIES)
5714 @RequiresPermission(anyOf = {
5715 android.Manifest.permission.NETWORK_SETTINGS,
5716 android.Manifest.permission.NETWORK_STACK,
5717 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5718 })
5719 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
5720 Objects.requireNonNull(uids);
5721 try {
5722 mService.replaceFirewallChain(chain, uids);
5723 } catch (RemoteException e) {
5724 throw e.rethrowFromSystemServer();
5725 }
5726 }
markchien9c806112022-01-11 23:28:23 +08005727
5728 /**
5729 * Request to change the current active network stats map.
5730 * STOPSHIP: Remove this API before T sdk finalized, this API is temporary added for the
5731 * NetworkStatsFactory which is platform code but will be moved into connectivity (tethering)
5732 * mainline module.
5733 *
markchien68cfadc2022-01-14 13:39:54 +08005734 * @throws IllegalStateException if swapping active stats map failed.
markchien9c806112022-01-11 23:28:23 +08005735 * @hide
5736 */
5737 @SystemApi(client = MODULE_LIBRARIES)
5738 @RequiresPermission(anyOf = {
5739 android.Manifest.permission.NETWORK_SETTINGS,
5740 android.Manifest.permission.NETWORK_STACK,
5741 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5742 })
5743 public void swapActiveStatsMap() {
5744 try {
5745 mService.swapActiveStatsMap();
5746 } catch (RemoteException e) {
5747 throw e.rethrowFromSystemServer();
5748 }
5749 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005750}