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