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