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