blob: ae9b8e6a8eadef4234c39d9f84817beb61a6f307 [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;
lucaslin889dcda2021-03-12 17:56:09 +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;
lucaslin889dcda2021-03-12 17:56:09 +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;
lucaslin889dcda2021-03-12 17:56:09 +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 */
lucaslind89b2982021-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 */
lucaslind89b2982021-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 =
lucaslind89b2982021-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 */
lucaslind89b2982021-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 =
lucaslind89b2982021-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 */
lucaslin889dcda2021-03-12 17:56:09 +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 */
lucaslin889dcda2021-03-12 17:56:09 +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 */
lucaslin889dcda2021-03-12 17:56:09 +0800843 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900844 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin889dcda2021-03-12 17:56:09 +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 Shankaf1520bb2021-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 Shankaf1520bb2021-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 Shankaf1520bb2021-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
lifrb4dab372021-03-11 20:11:09 +08001217 * TODO: b/183465229 Cleanup getActiveNetworkForUid once b/165835257 is fixed
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001218 */
1219 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1220 @Nullable
1221 public Network getActiveNetworkForUid(int uid) {
1222 return getActiveNetworkForUid(uid, false);
1223 }
1224
1225 /** {@hide} */
1226 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1227 try {
1228 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1229 } catch (RemoteException e) {
1230 throw e.rethrowFromSystemServer();
1231 }
1232 }
1233
1234 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001235 * Adds or removes a requirement for given UID ranges to use the VPN.
1236 *
1237 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1238 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1239 * otherwise have permission to bypass the VPN (e.g., because they have the
1240 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1241 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1242 * set to {@code false}, a previously-added restriction is removed.
1243 * <p>
1244 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1245 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1246 * remove a previously-added range, the exact range must be removed as is.
1247 * <p>
1248 * The changes are applied asynchronously and may not have been applied by the time the method
1249 * returns. Apps will be notified about any changes that apply to them via
1250 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1251 * effect.
1252 * <p>
1253 * This method should be called only by the VPN code.
1254 *
1255 * @param ranges the UID ranges to restrict
1256 * @param requireVpn whether the specified UID ranges must use a VPN
1257 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001258 * @hide
1259 */
1260 @RequiresPermission(anyOf = {
1261 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin29278ee2021-03-22 11:51:27 +08001262 android.Manifest.permission.NETWORK_STACK,
1263 android.Manifest.permission.NETWORK_SETTINGS})
1264 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001265 public void setRequireVpnForUids(boolean requireVpn,
1266 @NonNull Collection<Range<Integer>> ranges) {
1267 Objects.requireNonNull(ranges);
1268 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1269 // This method is not necessarily expected to be used outside the system server, so
1270 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1271 // stack process, or by tests.
1272 UidRange[] rangesArray = new UidRange[ranges.size()];
1273 int index = 0;
1274 for (Range<Integer> range : ranges) {
1275 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1276 }
1277 try {
1278 mService.setRequireVpnForUids(requireVpn, rangesArray);
1279 } catch (RemoteException e) {
1280 throw e.rethrowFromSystemServer();
1281 }
1282 }
1283
1284 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001285 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1286 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1287 * but is still supported for backwards compatibility.
1288 * <p>
1289 * This type of VPN is assumed always to use the system default network, and must always declare
1290 * exactly one underlying network, which is the network that was the default when the VPN
1291 * connected.
1292 * <p>
1293 * Calling this method with {@code true} enables legacy behaviour, specifically:
1294 * <ul>
1295 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1296 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1297 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1298 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1299 * underlying the VPN.</li>
1300 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1301 * similarly replaced by the VPN network state.</li>
1302 * <li>Information on current network interfaces passed to NetworkStatsService will not
1303 * include any VPN interfaces.</li>
1304 * </ul>
1305 *
1306 * @param enabled whether legacy lockdown VPN is enabled or disabled
1307 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001308 * @hide
1309 */
1310 @RequiresPermission(anyOf = {
1311 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin29278ee2021-03-22 11:51:27 +08001312 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001313 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin29278ee2021-03-22 11:51:27 +08001314 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001315 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1316 try {
1317 mService.setLegacyLockdownVpnEnabled(enabled);
1318 } catch (RemoteException e) {
1319 throw e.rethrowFromSystemServer();
1320 }
1321 }
1322
1323 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001324 * Returns details about the currently active default data network
1325 * for a given uid. This is for internal use only to avoid spying
1326 * other apps.
1327 *
1328 * @return a {@link NetworkInfo} object for the current default network
1329 * for the given uid or {@code null} if no default network is
1330 * available for the specified uid.
1331 *
1332 * {@hide}
1333 */
1334 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1335 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1336 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1337 return getActiveNetworkInfoForUid(uid, false);
1338 }
1339
1340 /** {@hide} */
1341 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1342 try {
1343 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1344 } catch (RemoteException e) {
1345 throw e.rethrowFromSystemServer();
1346 }
1347 }
1348
1349 /**
1350 * Returns connection status information about a particular
1351 * network type.
1352 *
1353 * @param networkType integer specifying which networkType in
1354 * which you're interested.
1355 * @return a {@link NetworkInfo} object for the requested
1356 * network type or {@code null} if the type is not
1357 * supported by the device. If {@code networkType} is
1358 * TYPE_VPN and a VPN is active for the calling app,
1359 * then this method will try to return one of the
1360 * underlying networks for the VPN or null if the
1361 * VPN agent didn't specify any.
1362 *
1363 * @deprecated This method does not support multiple connected networks
1364 * of the same type. Use {@link #getAllNetworks} and
1365 * {@link #getNetworkInfo(android.net.Network)} instead.
1366 */
1367 @Deprecated
1368 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1369 @Nullable
1370 public NetworkInfo getNetworkInfo(int networkType) {
1371 try {
1372 return mService.getNetworkInfo(networkType);
1373 } catch (RemoteException e) {
1374 throw e.rethrowFromSystemServer();
1375 }
1376 }
1377
1378 /**
1379 * Returns connection status information about a particular
1380 * Network.
1381 *
1382 * @param network {@link Network} specifying which network
1383 * in which you're interested.
1384 * @return a {@link NetworkInfo} object for the requested
1385 * network or {@code null} if the {@code Network}
1386 * is not valid.
1387 * @deprecated See {@link NetworkInfo}.
1388 */
1389 @Deprecated
1390 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1391 @Nullable
1392 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1393 return getNetworkInfoForUid(network, Process.myUid(), false);
1394 }
1395
1396 /** {@hide} */
1397 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1398 try {
1399 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1400 } catch (RemoteException e) {
1401 throw e.rethrowFromSystemServer();
1402 }
1403 }
1404
1405 /**
1406 * Returns connection status information about all network
1407 * types supported by the device.
1408 *
1409 * @return an array of {@link NetworkInfo} objects. Check each
1410 * {@link NetworkInfo#getType} for which type each applies.
1411 *
1412 * @deprecated This method does not support multiple connected networks
1413 * of the same type. Use {@link #getAllNetworks} and
1414 * {@link #getNetworkInfo(android.net.Network)} instead.
1415 */
1416 @Deprecated
1417 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1418 @NonNull
1419 public NetworkInfo[] getAllNetworkInfo() {
1420 try {
1421 return mService.getAllNetworkInfo();
1422 } catch (RemoteException e) {
1423 throw e.rethrowFromSystemServer();
1424 }
1425 }
1426
1427 /**
junyulaib1211372021-03-03 12:09:05 +08001428 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1429 * connected.
1430 * @hide
1431 */
1432 @SystemApi(client = MODULE_LIBRARIES)
1433 @RequiresPermission(anyOf = {
1434 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1435 android.Manifest.permission.NETWORK_STACK,
1436 android.Manifest.permission.NETWORK_SETTINGS})
1437 @NonNull
Aaron Huangda103b32021-04-17 13:46:25 +08001438 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001439 try {
Aaron Huangda103b32021-04-17 13:46:25 +08001440 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001441 } catch (RemoteException e) {
1442 throw e.rethrowFromSystemServer();
1443 }
1444 }
1445
1446 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001447 * Returns the {@link Network} object currently serving a given type, or
1448 * null if the given type is not connected.
1449 *
1450 * @hide
1451 * @deprecated This method does not support multiple connected networks
1452 * of the same type. Use {@link #getAllNetworks} and
1453 * {@link #getNetworkInfo(android.net.Network)} instead.
1454 */
1455 @Deprecated
1456 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1457 @UnsupportedAppUsage
1458 public Network getNetworkForType(int networkType) {
1459 try {
1460 return mService.getNetworkForType(networkType);
1461 } catch (RemoteException e) {
1462 throw e.rethrowFromSystemServer();
1463 }
1464 }
1465
1466 /**
1467 * Returns an array of all {@link Network} currently tracked by the
1468 * framework.
1469 *
1470 * @return an array of {@link Network} objects.
1471 */
1472 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1473 @NonNull
1474 public Network[] getAllNetworks() {
1475 try {
1476 return mService.getAllNetworks();
1477 } catch (RemoteException e) {
1478 throw e.rethrowFromSystemServer();
1479 }
1480 }
1481
1482 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001483 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001484 * the Networks that applications run by the given user will use by default.
1485 * @hide
1486 */
1487 @UnsupportedAppUsage
1488 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1489 try {
1490 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001491 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001492 } catch (RemoteException e) {
1493 throw e.rethrowFromSystemServer();
1494 }
1495 }
1496
1497 /**
1498 * Returns the IP information for the current default network.
1499 *
1500 * @return a {@link LinkProperties} object describing the IP info
1501 * for the current default network, or {@code null} if there
1502 * is no current default network.
1503 *
1504 * {@hide}
1505 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1506 * value of {@link #getActiveNetwork()} instead. In particular,
1507 * this method will return non-null LinkProperties even if the
1508 * app is blocked by policy from using this network.
1509 */
1510 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1511 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1512 public LinkProperties getActiveLinkProperties() {
1513 try {
1514 return mService.getActiveLinkProperties();
1515 } catch (RemoteException e) {
1516 throw e.rethrowFromSystemServer();
1517 }
1518 }
1519
1520 /**
1521 * Returns the IP information for a given network type.
1522 *
1523 * @param networkType the network type of interest.
1524 * @return a {@link LinkProperties} object describing the IP info
1525 * for the given networkType, or {@code null} if there is
1526 * no current default network.
1527 *
1528 * {@hide}
1529 * @deprecated This method does not support multiple connected networks
1530 * of the same type. Use {@link #getAllNetworks},
1531 * {@link #getNetworkInfo(android.net.Network)}, and
1532 * {@link #getLinkProperties(android.net.Network)} instead.
1533 */
1534 @Deprecated
1535 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1536 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1537 public LinkProperties getLinkProperties(int networkType) {
1538 try {
1539 return mService.getLinkPropertiesForType(networkType);
1540 } catch (RemoteException e) {
1541 throw e.rethrowFromSystemServer();
1542 }
1543 }
1544
1545 /**
1546 * Get the {@link LinkProperties} for the given {@link Network}. This
1547 * will return {@code null} if the network is unknown.
1548 *
1549 * @param network The {@link Network} object identifying the network in question.
1550 * @return The {@link LinkProperties} for the network, or {@code null}.
1551 */
1552 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1553 @Nullable
1554 public LinkProperties getLinkProperties(@Nullable Network network) {
1555 try {
1556 return mService.getLinkProperties(network);
1557 } catch (RemoteException e) {
1558 throw e.rethrowFromSystemServer();
1559 }
1560 }
1561
1562 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001563 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001564 * will return {@code null} if the network is unknown.
1565 *
Roshan Piuse08bc182020-12-22 15:10:42 -08001566 * This will remove any location sensitive data in {@link TransportInfo} embedded in
1567 * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
1568 * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
1569 * this location sensitive information (subject to app's location permissions) will be
1570 * noted by system. To include any location sensitive data in {@link TransportInfo},
1571 * use a {@link NetworkCallback} with
1572 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
1573 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001574 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001575 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001576 */
1577 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1578 @Nullable
1579 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1580 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001581 return mService.getNetworkCapabilities(
1582 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001583 } catch (RemoteException e) {
1584 throw e.rethrowFromSystemServer();
1585 }
1586 }
1587
1588 /**
1589 * Gets a URL that can be used for resolving whether a captive portal is present.
1590 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1591 * portal is present.
1592 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1593 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1594 *
1595 * The system network validation may be using different strategies to detect captive portals,
1596 * so this method does not necessarily return a URL used by the system. It only returns a URL
1597 * that may be relevant for other components trying to detect captive portals.
1598 *
1599 * @hide
1600 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1601 * system.
1602 */
1603 @Deprecated
1604 @SystemApi
1605 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1606 public String getCaptivePortalServerUrl() {
1607 try {
1608 return mService.getCaptivePortalServerUrl();
1609 } catch (RemoteException e) {
1610 throw e.rethrowFromSystemServer();
1611 }
1612 }
1613
1614 /**
1615 * Tells the underlying networking system that the caller wants to
1616 * begin using the named feature. The interpretation of {@code feature}
1617 * is completely up to each networking implementation.
1618 *
1619 * <p>This method requires the caller to hold either the
1620 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1621 * or the ability to modify system settings as determined by
1622 * {@link android.provider.Settings.System#canWrite}.</p>
1623 *
1624 * @param networkType specifies which network the request pertains to
1625 * @param feature the name of the feature to be used
1626 * @return an integer value representing the outcome of the request.
1627 * The interpretation of this value is specific to each networking
1628 * implementation+feature combination, except that the value {@code -1}
1629 * always indicates failure.
1630 *
1631 * @deprecated Deprecated in favor of the cleaner
1632 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1633 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1634 * throw {@code UnsupportedOperationException} if called.
1635 * @removed
1636 */
1637 @Deprecated
1638 public int startUsingNetworkFeature(int networkType, String feature) {
1639 checkLegacyRoutingApiAccess();
1640 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1641 if (netCap == null) {
1642 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1643 feature);
1644 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1645 }
1646
1647 NetworkRequest request = null;
1648 synchronized (sLegacyRequests) {
1649 LegacyRequest l = sLegacyRequests.get(netCap);
1650 if (l != null) {
1651 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1652 renewRequestLocked(l);
1653 if (l.currentNetwork != null) {
1654 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1655 } else {
1656 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1657 }
1658 }
1659
1660 request = requestNetworkForFeatureLocked(netCap);
1661 }
1662 if (request != null) {
1663 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1664 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1665 } else {
1666 Log.d(TAG, " request Failed");
1667 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1668 }
1669 }
1670
1671 /**
1672 * Tells the underlying networking system that the caller is finished
1673 * using the named feature. The interpretation of {@code feature}
1674 * is completely up to each networking implementation.
1675 *
1676 * <p>This method requires the caller to hold either the
1677 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1678 * or the ability to modify system settings as determined by
1679 * {@link android.provider.Settings.System#canWrite}.</p>
1680 *
1681 * @param networkType specifies which network the request pertains to
1682 * @param feature the name of the feature that is no longer needed
1683 * @return an integer value representing the outcome of the request.
1684 * The interpretation of this value is specific to each networking
1685 * implementation+feature combination, except that the value {@code -1}
1686 * always indicates failure.
1687 *
1688 * @deprecated Deprecated in favor of the cleaner
1689 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
1690 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1691 * throw {@code UnsupportedOperationException} if called.
1692 * @removed
1693 */
1694 @Deprecated
1695 public int stopUsingNetworkFeature(int networkType, String feature) {
1696 checkLegacyRoutingApiAccess();
1697 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1698 if (netCap == null) {
1699 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1700 feature);
1701 return -1;
1702 }
1703
1704 if (removeRequestForFeature(netCap)) {
1705 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
1706 }
1707 return 1;
1708 }
1709
1710 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1711 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1712 if (networkType == TYPE_MOBILE) {
1713 switch (feature) {
1714 case "enableCBS":
1715 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1716 case "enableDUN":
1717 case "enableDUNAlways":
1718 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1719 case "enableFOTA":
1720 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1721 case "enableHIPRI":
1722 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1723 case "enableIMS":
1724 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1725 case "enableMMS":
1726 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1727 case "enableSUPL":
1728 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1729 default:
1730 return null;
1731 }
1732 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1733 return networkCapabilitiesForType(TYPE_WIFI_P2P);
1734 }
1735 return null;
1736 }
1737
1738 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1739 if (netCap == null) return TYPE_NONE;
1740 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1741 return TYPE_MOBILE_CBS;
1742 }
1743 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1744 return TYPE_MOBILE_IMS;
1745 }
1746 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1747 return TYPE_MOBILE_FOTA;
1748 }
1749 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1750 return TYPE_MOBILE_DUN;
1751 }
1752 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1753 return TYPE_MOBILE_SUPL;
1754 }
1755 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1756 return TYPE_MOBILE_MMS;
1757 }
1758 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1759 return TYPE_MOBILE_HIPRI;
1760 }
1761 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1762 return TYPE_WIFI_P2P;
1763 }
1764 return TYPE_NONE;
1765 }
1766
1767 private static class LegacyRequest {
1768 NetworkCapabilities networkCapabilities;
1769 NetworkRequest networkRequest;
1770 int expireSequenceNumber;
1771 Network currentNetwork;
1772 int delay = -1;
1773
1774 private void clearDnsBinding() {
1775 if (currentNetwork != null) {
1776 currentNetwork = null;
1777 setProcessDefaultNetworkForHostResolution(null);
1778 }
1779 }
1780
1781 NetworkCallback networkCallback = new NetworkCallback() {
1782 @Override
1783 public void onAvailable(Network network) {
1784 currentNetwork = network;
1785 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
1786 setProcessDefaultNetworkForHostResolution(network);
1787 }
1788 @Override
1789 public void onLost(Network network) {
1790 if (network.equals(currentNetwork)) clearDnsBinding();
1791 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1792 }
1793 };
1794 }
1795
1796 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1797 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1798 new HashMap<>();
1799
1800 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1801 synchronized (sLegacyRequests) {
1802 LegacyRequest l = sLegacyRequests.get(netCap);
1803 if (l != null) return l.networkRequest;
1804 }
1805 return null;
1806 }
1807
1808 private void renewRequestLocked(LegacyRequest l) {
1809 l.expireSequenceNumber++;
1810 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1811 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1812 }
1813
1814 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1815 int ourSeqNum = -1;
1816 synchronized (sLegacyRequests) {
1817 LegacyRequest l = sLegacyRequests.get(netCap);
1818 if (l == null) return;
1819 ourSeqNum = l.expireSequenceNumber;
1820 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
1821 }
1822 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1823 }
1824
1825 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1826 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1827 int delay = -1;
1828 int type = legacyTypeForNetworkCapabilities(netCap);
1829 try {
1830 delay = mService.getRestoreDefaultNetworkDelay(type);
1831 } catch (RemoteException e) {
1832 throw e.rethrowFromSystemServer();
1833 }
1834 LegacyRequest l = new LegacyRequest();
1835 l.networkCapabilities = netCap;
1836 l.delay = delay;
1837 l.expireSequenceNumber = 0;
1838 l.networkRequest = sendRequestForNetwork(
1839 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
1840 if (l.networkRequest == null) return null;
1841 sLegacyRequests.put(netCap, l);
1842 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1843 return l.networkRequest;
1844 }
1845
1846 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1847 if (delay >= 0) {
1848 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
1849 CallbackHandler handler = getDefaultHandler();
1850 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1851 handler.sendMessageDelayed(msg, delay);
1852 }
1853 }
1854
1855 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1856 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1857 final LegacyRequest l;
1858 synchronized (sLegacyRequests) {
1859 l = sLegacyRequests.remove(netCap);
1860 }
1861 if (l == null) return false;
1862 unregisterNetworkCallback(l.networkCallback);
1863 l.clearDnsBinding();
1864 return true;
1865 }
1866
1867 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1868 static {
1869 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1870 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1871 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1872 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1873 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1874 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1875 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1876 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1877 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1878 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1879 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1880 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1881 }
1882
1883 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1884 static {
1885 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1886 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1887 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1888 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1889 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1890 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1891 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1892 }
1893
1894 /**
1895 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1896 * instance suitable for registering a request or callback. Throws an
1897 * IllegalArgumentException if no mapping from the legacy type to
1898 * NetworkCapabilities is known.
1899 *
1900 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1901 * to find the network instead.
1902 * @hide
1903 */
1904 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1905 final NetworkCapabilities nc = new NetworkCapabilities();
1906
1907 // Map from type to transports.
1908 final int NOT_FOUND = -1;
1909 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00001910 if (transport == NOT_FOUND) {
1911 throw new IllegalArgumentException("unknown legacy type: " + type);
1912 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001913 nc.addTransportType(transport);
1914
1915 // Map from type to capabilities.
1916 nc.addCapability(sLegacyTypeToCapability.get(
1917 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1918 nc.maybeMarkCapabilitiesRestricted();
1919 return nc;
1920 }
1921
1922 /** @hide */
1923 public static class PacketKeepaliveCallback {
1924 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1925 public PacketKeepaliveCallback() {
1926 }
1927 /** The requested keepalive was successfully started. */
1928 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1929 public void onStarted() {}
1930 /** The keepalive was successfully stopped. */
1931 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1932 public void onStopped() {}
1933 /** An error occurred. */
1934 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1935 public void onError(int error) {}
1936 }
1937
1938 /**
1939 * Allows applications to request that the system periodically send specific packets on their
1940 * behalf, using hardware offload to save battery power.
1941 *
1942 * To request that the system send keepalives, call one of the methods that return a
1943 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1944 * passing in a non-null callback. If the callback is successfully started, the callback's
1945 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1946 * specifying one of the {@code ERROR_*} constants in this class.
1947 *
1948 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1949 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1950 * {@link PacketKeepaliveCallback#onError} if an error occurred.
1951 *
1952 * @deprecated Use {@link SocketKeepalive} instead.
1953 *
1954 * @hide
1955 */
1956 public class PacketKeepalive {
1957
1958 private static final String TAG = "PacketKeepalive";
1959
1960 /** @hide */
1961 public static final int SUCCESS = 0;
1962
1963 /** @hide */
1964 public static final int NO_KEEPALIVE = -1;
1965
1966 /** @hide */
1967 public static final int BINDER_DIED = -10;
1968
1969 /** The specified {@code Network} is not connected. */
1970 public static final int ERROR_INVALID_NETWORK = -20;
1971 /** The specified IP addresses are invalid. For example, the specified source IP address is
1972 * not configured on the specified {@code Network}. */
1973 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1974 /** The requested port is invalid. */
1975 public static final int ERROR_INVALID_PORT = -22;
1976 /** The packet length is invalid (e.g., too long). */
1977 public static final int ERROR_INVALID_LENGTH = -23;
1978 /** The packet transmission interval is invalid (e.g., too short). */
1979 public static final int ERROR_INVALID_INTERVAL = -24;
1980
1981 /** The hardware does not support this request. */
1982 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
1983 /** The hardware returned an error. */
1984 public static final int ERROR_HARDWARE_ERROR = -31;
1985
1986 /** The NAT-T destination port for IPsec */
1987 public static final int NATT_PORT = 4500;
1988
1989 /** The minimum interval in seconds between keepalive packet transmissions */
1990 public static final int MIN_INTERVAL = 10;
1991
1992 private final Network mNetwork;
1993 private final ISocketKeepaliveCallback mCallback;
1994 private final ExecutorService mExecutor;
1995
1996 private volatile Integer mSlot;
1997
1998 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1999 public void stop() {
2000 try {
2001 mExecutor.execute(() -> {
2002 try {
2003 if (mSlot != null) {
2004 mService.stopKeepalive(mNetwork, mSlot);
2005 }
2006 } catch (RemoteException e) {
2007 Log.e(TAG, "Error stopping packet keepalive: ", e);
2008 throw e.rethrowFromSystemServer();
2009 }
2010 });
2011 } catch (RejectedExecutionException e) {
2012 // The internal executor has already stopped due to previous event.
2013 }
2014 }
2015
2016 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002017 Objects.requireNonNull(network, "network cannot be null");
2018 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002019 mNetwork = network;
2020 mExecutor = Executors.newSingleThreadExecutor();
2021 mCallback = new ISocketKeepaliveCallback.Stub() {
2022 @Override
2023 public void onStarted(int slot) {
2024 final long token = Binder.clearCallingIdentity();
2025 try {
2026 mExecutor.execute(() -> {
2027 mSlot = slot;
2028 callback.onStarted();
2029 });
2030 } finally {
2031 Binder.restoreCallingIdentity(token);
2032 }
2033 }
2034
2035 @Override
2036 public void onStopped() {
2037 final long token = Binder.clearCallingIdentity();
2038 try {
2039 mExecutor.execute(() -> {
2040 mSlot = null;
2041 callback.onStopped();
2042 });
2043 } finally {
2044 Binder.restoreCallingIdentity(token);
2045 }
2046 mExecutor.shutdown();
2047 }
2048
2049 @Override
2050 public void onError(int error) {
2051 final long token = Binder.clearCallingIdentity();
2052 try {
2053 mExecutor.execute(() -> {
2054 mSlot = null;
2055 callback.onError(error);
2056 });
2057 } finally {
2058 Binder.restoreCallingIdentity(token);
2059 }
2060 mExecutor.shutdown();
2061 }
2062
2063 @Override
2064 public void onDataReceived() {
2065 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2066 // this callback when data is received.
2067 }
2068 };
2069 }
2070 }
2071
2072 /**
2073 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2074 *
2075 * @deprecated Use {@link #createSocketKeepalive} instead.
2076 *
2077 * @hide
2078 */
2079 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2080 public PacketKeepalive startNattKeepalive(
2081 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2082 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2083 final PacketKeepalive k = new PacketKeepalive(network, callback);
2084 try {
2085 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2086 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2087 } catch (RemoteException e) {
2088 Log.e(TAG, "Error starting packet keepalive: ", e);
2089 throw e.rethrowFromSystemServer();
2090 }
2091 return k;
2092 }
2093
2094 // Construct an invalid fd.
2095 private ParcelFileDescriptor createInvalidFd() {
2096 final int invalidFd = -1;
2097 return ParcelFileDescriptor.adoptFd(invalidFd);
2098 }
2099
2100 /**
2101 * Request that keepalives be started on a IPsec NAT-T socket.
2102 *
2103 * @param network The {@link Network} the socket is on.
2104 * @param socket The socket that needs to be kept alive.
2105 * @param source The source address of the {@link UdpEncapsulationSocket}.
2106 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2107 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2108 * must run callback sequentially, otherwise the order of callbacks cannot be
2109 * guaranteed.
2110 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2111 * changes. Must be extended by applications that use this API.
2112 *
2113 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2114 * given socket.
2115 **/
2116 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2117 @NonNull UdpEncapsulationSocket socket,
2118 @NonNull InetAddress source,
2119 @NonNull InetAddress destination,
2120 @NonNull @CallbackExecutor Executor executor,
2121 @NonNull Callback callback) {
2122 ParcelFileDescriptor dup;
2123 try {
2124 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2125 // which cannot be obtained by the app process.
2126 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2127 } catch (IOException ignored) {
2128 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2129 // ERROR_INVALID_SOCKET.
2130 dup = createInvalidFd();
2131 }
2132 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2133 destination, executor, callback);
2134 }
2135
2136 /**
2137 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2138 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2139 *
2140 * @param network The {@link Network} the socket is on.
2141 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2142 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2143 * from that port.
2144 * @param source The source address of the {@link UdpEncapsulationSocket}.
2145 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2146 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2147 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2148 * must run callback sequentially, otherwise the order of callbacks cannot be
2149 * guaranteed.
2150 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2151 * changes. Must be extended by applications that use this API.
2152 *
2153 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2154 * given socket.
2155 * @hide
2156 */
2157 @SystemApi
2158 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2159 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2160 @NonNull ParcelFileDescriptor pfd,
2161 @NonNull InetAddress source,
2162 @NonNull InetAddress destination,
2163 @NonNull @CallbackExecutor Executor executor,
2164 @NonNull Callback callback) {
2165 ParcelFileDescriptor dup;
2166 try {
2167 // TODO: Consider remove unnecessary dup.
2168 dup = pfd.dup();
2169 } catch (IOException ignored) {
2170 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2171 // ERROR_INVALID_SOCKET.
2172 dup = createInvalidFd();
2173 }
2174 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002175 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002176 }
2177
2178 /**
2179 * Request that keepalives be started on a TCP socket.
2180 * The socket must be established.
2181 *
2182 * @param network The {@link Network} the socket is on.
2183 * @param socket The socket that needs to be kept alive.
2184 * @param executor The executor on which callback will be invoked. This implementation assumes
2185 * the provided {@link Executor} runs the callbacks in sequence with no
2186 * concurrency. Failing this, no guarantee of correctness can be made. It is
2187 * the responsibility of the caller to ensure the executor provides this
2188 * guarantee. A simple way of creating such an executor is with the standard
2189 * tool {@code Executors.newSingleThreadExecutor}.
2190 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2191 * changes. Must be extended by applications that use this API.
2192 *
2193 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2194 * given socket.
2195 * @hide
2196 */
2197 @SystemApi
2198 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2199 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2200 @NonNull Socket socket,
2201 @NonNull Executor executor,
2202 @NonNull Callback callback) {
2203 ParcelFileDescriptor dup;
2204 try {
2205 dup = ParcelFileDescriptor.fromSocket(socket);
2206 } catch (UncheckedIOException ignored) {
2207 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2208 // ERROR_INVALID_SOCKET.
2209 dup = createInvalidFd();
2210 }
2211 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2212 }
2213
2214 /**
2215 * Ensure that a network route exists to deliver traffic to the specified
2216 * host via the specified network interface. An attempt to add a route that
2217 * already exists is ignored, but treated as successful.
2218 *
2219 * <p>This method requires the caller to hold either the
2220 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2221 * or the ability to modify system settings as determined by
2222 * {@link android.provider.Settings.System#canWrite}.</p>
2223 *
2224 * @param networkType the type of the network over which traffic to the specified
2225 * host is to be routed
2226 * @param hostAddress the IP address of the host to which the route is desired
2227 * @return {@code true} on success, {@code false} on failure
2228 *
2229 * @deprecated Deprecated in favor of the
2230 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2231 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2232 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2233 * throw {@code UnsupportedOperationException} if called.
2234 * @removed
2235 */
2236 @Deprecated
2237 public boolean requestRouteToHost(int networkType, int hostAddress) {
2238 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2239 }
2240
2241 /**
2242 * Ensure that a network route exists to deliver traffic to the specified
2243 * host via the specified network interface. An attempt to add a route that
2244 * already exists is ignored, but treated as successful.
2245 *
2246 * <p>This method requires the caller to hold either the
2247 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2248 * or the ability to modify system settings as determined by
2249 * {@link android.provider.Settings.System#canWrite}.</p>
2250 *
2251 * @param networkType the type of the network over which traffic to the specified
2252 * host is to be routed
2253 * @param hostAddress the IP address of the host to which the route is desired
2254 * @return {@code true} on success, {@code false} on failure
2255 * @hide
2256 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2257 * {@link #bindProcessToNetwork} API.
2258 */
2259 @Deprecated
2260 @UnsupportedAppUsage
lucaslin29278ee2021-03-22 11:51:27 +08002261 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002262 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2263 checkLegacyRoutingApiAccess();
2264 try {
2265 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2266 mContext.getOpPackageName(), getAttributionTag());
2267 } catch (RemoteException e) {
2268 throw e.rethrowFromSystemServer();
2269 }
2270 }
2271
2272 /**
2273 * @return the context's attribution tag
2274 */
2275 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2276 private @Nullable String getAttributionTag() {
Roshan Piusa8a477b2020-12-17 14:53:09 -08002277 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002278 }
2279
2280 /**
2281 * Returns the value of the setting for background data usage. If false,
2282 * applications should not use the network if the application is not in the
2283 * foreground. Developers should respect this setting, and check the value
2284 * of this before performing any background data operations.
2285 * <p>
2286 * All applications that have background services that use the network
2287 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2288 * <p>
2289 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2290 * background data depends on several combined factors, and this method will
2291 * always return {@code true}. Instead, when background data is unavailable,
2292 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2293 *
2294 * @return Whether background data usage is allowed.
2295 */
2296 @Deprecated
2297 public boolean getBackgroundDataSetting() {
2298 // assume that background data is allowed; final authority is
2299 // NetworkInfo which may be blocked.
2300 return true;
2301 }
2302
2303 /**
2304 * Sets the value of the setting for background data usage.
2305 *
2306 * @param allowBackgroundData Whether an application should use data while
2307 * it is in the background.
2308 *
2309 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2310 * @see #getBackgroundDataSetting()
2311 * @hide
2312 */
2313 @Deprecated
2314 @UnsupportedAppUsage
2315 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2316 // ignored
2317 }
2318
2319 /**
2320 * @hide
2321 * @deprecated Talk to TelephonyManager directly
2322 */
2323 @Deprecated
2324 @UnsupportedAppUsage
2325 public boolean getMobileDataEnabled() {
2326 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2327 if (tm != null) {
2328 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2329 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2330 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2331 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2332 + " retVal=" + retVal);
2333 return retVal;
2334 }
2335 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2336 return false;
2337 }
2338
2339 /**
2340 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2341 * to find out when the system default network has gone in to a high power state.
2342 */
2343 public interface OnNetworkActiveListener {
2344 /**
2345 * Called on the main thread of the process to report that the current data network
2346 * has become active, and it is now a good time to perform any pending network
2347 * operations. Note that this listener only tells you when the network becomes
2348 * active; if at any other time you want to know whether it is active (and thus okay
2349 * to initiate network traffic), you can retrieve its instantaneous state with
2350 * {@link ConnectivityManager#isDefaultNetworkActive}.
2351 */
2352 void onNetworkActive();
2353 }
2354
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002355 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2356 mNetworkActivityListeners = new ArrayMap<>();
2357
2358 /**
2359 * Start listening to reports when the system's default data network is active, meaning it is
2360 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2361 * to determine the current state of the system's default network after registering the
2362 * listener.
2363 * <p>
2364 * If the process default network has been set with
2365 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2366 * reflect the process's default, but the system default.
2367 *
2368 * @param l The listener to be told when the network is active.
2369 */
2370 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
2371 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2372 @Override
2373 public void onNetworkActive() throws RemoteException {
2374 l.onNetworkActive();
2375 }
2376 };
2377
2378 try {
lucaslin709eb842021-01-21 02:04:15 +08002379 mService.registerNetworkActivityListener(rl);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002380 mNetworkActivityListeners.put(l, rl);
2381 } catch (RemoteException e) {
2382 throw e.rethrowFromSystemServer();
2383 }
2384 }
2385
2386 /**
2387 * Remove network active listener previously registered with
2388 * {@link #addDefaultNetworkActiveListener}.
2389 *
2390 * @param l Previously registered listener.
2391 */
2392 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
2393 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002394 if (rl == null) {
2395 throw new IllegalArgumentException("Listener was not registered.");
2396 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002397 try {
lucaslin709eb842021-01-21 02:04:15 +08002398 mService.registerNetworkActivityListener(rl);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002399 } catch (RemoteException e) {
2400 throw e.rethrowFromSystemServer();
2401 }
2402 }
2403
2404 /**
2405 * Return whether the data network is currently active. An active network means that
2406 * it is currently in a high power state for performing data transmission. On some
2407 * types of networks, it may be expensive to move and stay in such a state, so it is
2408 * more power efficient to batch network traffic together when the radio is already in
2409 * this state. This method tells you whether right now is currently a good time to
2410 * initiate network traffic, as the network is already active.
2411 */
2412 public boolean isDefaultNetworkActive() {
2413 try {
lucaslin709eb842021-01-21 02:04:15 +08002414 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002415 } catch (RemoteException e) {
2416 throw e.rethrowFromSystemServer();
2417 }
2418 }
2419
2420 /**
2421 * {@hide}
2422 */
2423 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002424 mContext = Objects.requireNonNull(context, "missing context");
2425 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002426 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
2427 sInstance = this;
2428 }
2429
2430 /** {@hide} */
2431 @UnsupportedAppUsage
2432 public static ConnectivityManager from(Context context) {
2433 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2434 }
2435
2436 /** @hide */
2437 public NetworkRequest getDefaultRequest() {
2438 try {
2439 // This is not racy as the default request is final in ConnectivityService.
2440 return mService.getDefaultRequest();
2441 } catch (RemoteException e) {
2442 throw e.rethrowFromSystemServer();
2443 }
2444 }
2445
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002446 /**
2447 * Check if the package is a allowed to write settings. This also accounts that such an access
2448 * happened.
2449 *
2450 * @return {@code true} iff the package is allowed to write settings.
2451 */
2452 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2453 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2454 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2455 boolean throwException) {
2456 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2457 throwException);
2458 }
2459
2460 /**
2461 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2462 * situations where a Context pointer is unavailable.
2463 * @hide
2464 */
2465 @Deprecated
2466 static ConnectivityManager getInstanceOrNull() {
2467 return sInstance;
2468 }
2469
2470 /**
2471 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2472 * situations where a Context pointer is unavailable.
2473 * @hide
2474 */
2475 @Deprecated
2476 @UnsupportedAppUsage
2477 private static ConnectivityManager getInstance() {
2478 if (getInstanceOrNull() == null) {
2479 throw new IllegalStateException("No ConnectivityManager yet constructed");
2480 }
2481 return getInstanceOrNull();
2482 }
2483
2484 /**
2485 * Get the set of tetherable, available interfaces. This list is limited by
2486 * device configuration and current interface existence.
2487 *
2488 * @return an array of 0 or more Strings of tetherable interface names.
2489 *
2490 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2491 * {@hide}
2492 */
2493 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2494 @UnsupportedAppUsage
2495 @Deprecated
2496 public String[] getTetherableIfaces() {
2497 return mTetheringManager.getTetherableIfaces();
2498 }
2499
2500 /**
2501 * Get the set of tethered interfaces.
2502 *
2503 * @return an array of 0 or more String of currently tethered interface names.
2504 *
2505 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2506 * {@hide}
2507 */
2508 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2509 @UnsupportedAppUsage
2510 @Deprecated
2511 public String[] getTetheredIfaces() {
2512 return mTetheringManager.getTetheredIfaces();
2513 }
2514
2515 /**
2516 * Get the set of interface names which attempted to tether but
2517 * failed. Re-attempting to tether may cause them to reset to the Tethered
2518 * state. Alternatively, causing the interface to be destroyed and recreated
2519 * may cause them to reset to the available state.
2520 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2521 * information on the cause of the errors.
2522 *
2523 * @return an array of 0 or more String indicating the interface names
2524 * which failed to tether.
2525 *
2526 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2527 * {@hide}
2528 */
2529 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2530 @UnsupportedAppUsage
2531 @Deprecated
2532 public String[] getTetheringErroredIfaces() {
2533 return mTetheringManager.getTetheringErroredIfaces();
2534 }
2535
2536 /**
2537 * Get the set of tethered dhcp ranges.
2538 *
2539 * @deprecated This method is not supported.
2540 * TODO: remove this function when all of clients are removed.
2541 * {@hide}
2542 */
2543 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2544 @Deprecated
2545 public String[] getTetheredDhcpRanges() {
2546 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2547 }
2548
2549 /**
2550 * Attempt to tether the named interface. This will setup a dhcp server
2551 * on the interface, forward and NAT IP packets and forward DNS requests
2552 * to the best active upstream network interface. Note that if no upstream
2553 * IP network interface is available, dhcp will still run and traffic will be
2554 * allowed between the tethered devices and this device, though upstream net
2555 * access will of course fail until an upstream network interface becomes
2556 * active.
2557 *
2558 * <p>This method requires the caller to hold either the
2559 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2560 * or the ability to modify system settings as determined by
2561 * {@link android.provider.Settings.System#canWrite}.</p>
2562 *
2563 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2564 * and WifiStateMachine which need direct access. All other clients should use
2565 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2566 * logic.</p>
2567 *
2568 * @param iface the interface name to tether.
2569 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2570 * @deprecated Use {@link TetheringManager#startTethering} instead
2571 *
2572 * {@hide}
2573 */
2574 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2575 @Deprecated
2576 public int tether(String iface) {
2577 return mTetheringManager.tether(iface);
2578 }
2579
2580 /**
2581 * Stop tethering the named interface.
2582 *
2583 * <p>This method requires the caller to hold either the
2584 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2585 * or the ability to modify system settings as determined by
2586 * {@link android.provider.Settings.System#canWrite}.</p>
2587 *
2588 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2589 * and WifiStateMachine which need direct access. All other clients should use
2590 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2591 * logic.</p>
2592 *
2593 * @param iface the interface name to untether.
2594 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2595 *
2596 * {@hide}
2597 */
2598 @UnsupportedAppUsage
2599 @Deprecated
2600 public int untether(String iface) {
2601 return mTetheringManager.untether(iface);
2602 }
2603
2604 /**
2605 * Check if the device allows for tethering. It may be disabled via
2606 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2607 * due to device configuration.
2608 *
2609 * <p>If this app does not have permission to use this API, it will always
2610 * return false rather than throw an exception.</p>
2611 *
2612 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2613 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2614 *
2615 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2616 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2617 *
2618 * @return a boolean - {@code true} indicating Tethering is supported.
2619 *
2620 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2621 * {@hide}
2622 */
2623 @SystemApi
2624 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2625 android.Manifest.permission.WRITE_SETTINGS})
2626 public boolean isTetheringSupported() {
2627 return mTetheringManager.isTetheringSupported();
2628 }
2629
2630 /**
2631 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2632 *
2633 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
2634 * @hide
2635 */
2636 @SystemApi
2637 @Deprecated
2638 public static abstract class OnStartTetheringCallback {
2639 /**
2640 * Called when tethering has been successfully started.
2641 */
2642 public void onTetheringStarted() {}
2643
2644 /**
2645 * Called when starting tethering failed.
2646 */
2647 public void onTetheringFailed() {}
2648 }
2649
2650 /**
2651 * Convenient overload for
2652 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2653 * handler to run on the current thread's {@link Looper}.
2654 *
2655 * @deprecated Use {@link TetheringManager#startTethering} instead.
2656 * @hide
2657 */
2658 @SystemApi
2659 @Deprecated
2660 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2661 public void startTethering(int type, boolean showProvisioningUi,
2662 final OnStartTetheringCallback callback) {
2663 startTethering(type, showProvisioningUi, callback, null);
2664 }
2665
2666 /**
2667 * Runs tether provisioning for the given type if needed and then starts tethering if
2668 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2669 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2670 * schedules tether provisioning re-checks if appropriate.
2671 *
2672 * @param type The type of tethering to start. Must be one of
2673 * {@link ConnectivityManager.TETHERING_WIFI},
2674 * {@link ConnectivityManager.TETHERING_USB}, or
2675 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2676 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2677 * is one. This should be true the first time this function is called and also any time
2678 * the user can see this UI. It gives users information from their carrier about the
2679 * check failing and how they can sign up for tethering if possible.
2680 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2681 * of the result of trying to tether.
2682 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2683 *
2684 * @deprecated Use {@link TetheringManager#startTethering} instead.
2685 * @hide
2686 */
2687 @SystemApi
2688 @Deprecated
2689 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2690 public void startTethering(int type, boolean showProvisioningUi,
2691 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002692 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002693
2694 final Executor executor = new Executor() {
2695 @Override
2696 public void execute(Runnable command) {
2697 if (handler == null) {
2698 command.run();
2699 } else {
2700 handler.post(command);
2701 }
2702 }
2703 };
2704
2705 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2706 @Override
2707 public void onTetheringStarted() {
2708 callback.onTetheringStarted();
2709 }
2710
2711 @Override
2712 public void onTetheringFailed(final int error) {
2713 callback.onTetheringFailed();
2714 }
2715 };
2716
2717 final TetheringRequest request = new TetheringRequest.Builder(type)
2718 .setShouldShowEntitlementUi(showProvisioningUi).build();
2719
2720 mTetheringManager.startTethering(request, executor, tetheringCallback);
2721 }
2722
2723 /**
2724 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2725 * applicable.
2726 *
2727 * @param type The type of tethering to stop. Must be one of
2728 * {@link ConnectivityManager.TETHERING_WIFI},
2729 * {@link ConnectivityManager.TETHERING_USB}, or
2730 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2731 *
2732 * @deprecated Use {@link TetheringManager#stopTethering} instead.
2733 * @hide
2734 */
2735 @SystemApi
2736 @Deprecated
2737 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2738 public void stopTethering(int type) {
2739 mTetheringManager.stopTethering(type);
2740 }
2741
2742 /**
2743 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2744 * upstream status.
2745 *
2746 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
2747 * @hide
2748 */
2749 @SystemApi
2750 @Deprecated
2751 public abstract static class OnTetheringEventCallback {
2752
2753 /**
2754 * Called when tethering upstream changed. This can be called multiple times and can be
2755 * called any time.
2756 *
2757 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2758 * have any upstream.
2759 */
2760 public void onUpstreamChanged(@Nullable Network network) {}
2761 }
2762
2763 @GuardedBy("mTetheringEventCallbacks")
2764 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2765 mTetheringEventCallbacks = new ArrayMap<>();
2766
2767 /**
2768 * Start listening to tethering change events. Any new added callback will receive the last
2769 * tethering status right away. If callback is registered when tethering has no upstream or
2770 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2771 * with a null argument. The same callback object cannot be registered twice.
2772 *
2773 * @param executor the executor on which callback will be invoked.
2774 * @param callback the callback to be called when tethering has change events.
2775 *
2776 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
2777 * @hide
2778 */
2779 @SystemApi
2780 @Deprecated
2781 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2782 public void registerTetheringEventCallback(
2783 @NonNull @CallbackExecutor Executor executor,
2784 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00002785 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002786
2787 final TetheringEventCallback tetherCallback =
2788 new TetheringEventCallback() {
2789 @Override
2790 public void onUpstreamChanged(@Nullable Network network) {
2791 callback.onUpstreamChanged(network);
2792 }
2793 };
2794
2795 synchronized (mTetheringEventCallbacks) {
2796 mTetheringEventCallbacks.put(callback, tetherCallback);
2797 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
2798 }
2799 }
2800
2801 /**
2802 * Remove tethering event callback previously registered with
2803 * {@link #registerTetheringEventCallback}.
2804 *
2805 * @param callback previously registered callback.
2806 *
2807 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
2808 * @hide
2809 */
2810 @SystemApi
2811 @Deprecated
2812 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2813 public void unregisterTetheringEventCallback(
2814 @NonNull final OnTetheringEventCallback callback) {
2815 Objects.requireNonNull(callback, "The callback must be non-null");
2816 synchronized (mTetheringEventCallbacks) {
2817 final TetheringEventCallback tetherCallback =
2818 mTetheringEventCallbacks.remove(callback);
2819 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
2820 }
2821 }
2822
2823
2824 /**
2825 * Get the list of regular expressions that define any tetherable
2826 * USB network interfaces. If USB tethering is not supported by the
2827 * device, this list should be empty.
2828 *
2829 * @return an array of 0 or more regular expression Strings defining
2830 * what interfaces are considered tetherable usb interfaces.
2831 *
2832 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2833 * {@hide}
2834 */
2835 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2836 @UnsupportedAppUsage
2837 @Deprecated
2838 public String[] getTetherableUsbRegexs() {
2839 return mTetheringManager.getTetherableUsbRegexs();
2840 }
2841
2842 /**
2843 * Get the list of regular expressions that define any tetherable
2844 * Wifi network interfaces. If Wifi tethering is not supported by the
2845 * device, this list should be empty.
2846 *
2847 * @return an array of 0 or more regular expression Strings defining
2848 * what interfaces are considered tetherable wifi interfaces.
2849 *
2850 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
2851 * {@hide}
2852 */
2853 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2854 @UnsupportedAppUsage
2855 @Deprecated
2856 public String[] getTetherableWifiRegexs() {
2857 return mTetheringManager.getTetherableWifiRegexs();
2858 }
2859
2860 /**
2861 * Get the list of regular expressions that define any tetherable
2862 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2863 * device, this list should be empty.
2864 *
2865 * @return an array of 0 or more regular expression Strings defining
2866 * what interfaces are considered tetherable bluetooth interfaces.
2867 *
2868 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2869 *TetheringManager.TetheringInterfaceRegexps)} instead.
2870 * {@hide}
2871 */
2872 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2873 @UnsupportedAppUsage
2874 @Deprecated
2875 public String[] getTetherableBluetoothRegexs() {
2876 return mTetheringManager.getTetherableBluetoothRegexs();
2877 }
2878
2879 /**
2880 * Attempt to both alter the mode of USB and Tethering of USB. A
2881 * utility method to deal with some of the complexity of USB - will
2882 * attempt to switch to Rndis and subsequently tether the resulting
2883 * interface on {@code true} or turn off tethering and switch off
2884 * Rndis on {@code false}.
2885 *
2886 * <p>This method requires the caller to hold either the
2887 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2888 * or the ability to modify system settings as determined by
2889 * {@link android.provider.Settings.System#canWrite}.</p>
2890 *
2891 * @param enable a boolean - {@code true} to enable tethering
2892 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2893 * @deprecated Use {@link TetheringManager#startTethering} instead
2894 *
2895 * {@hide}
2896 */
2897 @UnsupportedAppUsage
2898 @Deprecated
2899 public int setUsbTethering(boolean enable) {
2900 return mTetheringManager.setUsbTethering(enable);
2901 }
2902
2903 /**
2904 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2905 * {@hide}
2906 */
2907 @SystemApi
2908 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002909 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002910 /**
2911 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2912 * {@hide}
2913 */
2914 @Deprecated
2915 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2916 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2917 /**
2918 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2919 * {@hide}
2920 */
2921 @Deprecated
2922 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2923 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2924 /**
2925 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2926 * {@hide}
2927 */
2928 @Deprecated
2929 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2930 /**
2931 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2932 * {@hide}
2933 */
2934 @Deprecated
2935 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2936 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2937 /**
2938 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
2939 * {@hide}
2940 */
2941 @Deprecated
2942 public static final int TETHER_ERROR_MASTER_ERROR =
2943 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
2944 /**
2945 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2946 * {@hide}
2947 */
2948 @Deprecated
2949 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2950 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2951 /**
2952 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2953 * {@hide}
2954 */
2955 @Deprecated
2956 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2957 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2958 /**
2959 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
2960 * {@hide}
2961 */
2962 @Deprecated
2963 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
2964 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
2965 /**
2966 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
2967 * {@hide}
2968 */
2969 @Deprecated
2970 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
2971 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
2972 /**
2973 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2974 * {@hide}
2975 */
2976 @Deprecated
2977 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2978 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2979 /**
2980 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
2981 * {@hide}
2982 */
2983 @SystemApi
2984 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002985 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002986 /**
2987 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2988 * {@hide}
2989 */
2990 @Deprecated
2991 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2992 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2993 /**
2994 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2995 * {@hide}
2996 */
2997 @SystemApi
2998 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09002999 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003000
3001 /**
3002 * Get a more detailed error code after a Tethering or Untethering
3003 * request asynchronously failed.
3004 *
3005 * @param iface The name of the interface of interest
3006 * @return error The error code of the last error tethering or untethering the named
3007 * interface
3008 *
3009 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3010 * {@hide}
3011 */
3012 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3013 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3014 @Deprecated
3015 public int getLastTetherError(String iface) {
3016 int error = mTetheringManager.getLastTetherError(iface);
3017 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3018 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3019 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3020 // instead.
3021 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3022 }
3023 return error;
3024 }
3025
3026 /** @hide */
3027 @Retention(RetentionPolicy.SOURCE)
3028 @IntDef(value = {
3029 TETHER_ERROR_NO_ERROR,
3030 TETHER_ERROR_PROVISION_FAILED,
3031 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3032 })
3033 public @interface EntitlementResultCode {
3034 }
3035
3036 /**
3037 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3038 * entitlement succeeded.
3039 *
3040 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3041 * @hide
3042 */
3043 @SystemApi
3044 @Deprecated
3045 public interface OnTetheringEntitlementResultListener {
3046 /**
3047 * Called to notify entitlement result.
3048 *
3049 * @param resultCode an int value of entitlement result. It may be one of
3050 * {@link #TETHER_ERROR_NO_ERROR},
3051 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3052 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3053 */
3054 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3055 }
3056
3057 /**
3058 * Get the last value of the entitlement check on this downstream. If the cached value is
3059 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
3060 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
3061 * guaranteed that the UI-based entitlement check will complete in any specific time period
3062 * and may in fact never complete. Any successful entitlement check the platform performs for
3063 * any reason will update the cached value.
3064 *
3065 * @param type the downstream type of tethering. Must be one of
3066 * {@link #TETHERING_WIFI},
3067 * {@link #TETHERING_USB}, or
3068 * {@link #TETHERING_BLUETOOTH}.
3069 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3070 * @param executor the executor on which callback will be invoked.
3071 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3072 * notify the caller of the result of entitlement check. The listener may be called zero
3073 * or one time.
3074 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3075 * {@hide}
3076 */
3077 @SystemApi
3078 @Deprecated
3079 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3080 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3081 @NonNull @CallbackExecutor Executor executor,
3082 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003083 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003084 ResultReceiver wrappedListener = new ResultReceiver(null) {
3085 @Override
3086 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003087 final long token = Binder.clearCallingIdentity();
3088 try {
3089 executor.execute(() -> {
3090 listener.onTetheringEntitlementResult(resultCode);
3091 });
3092 } finally {
3093 Binder.restoreCallingIdentity(token);
3094 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003095 }
3096 };
3097
3098 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
3099 showEntitlementUi);
3100 }
3101
3102 /**
3103 * Report network connectivity status. This is currently used only
3104 * to alter status bar UI.
3105 * <p>This method requires the caller to hold the permission
3106 * {@link android.Manifest.permission#STATUS_BAR}.
3107 *
3108 * @param networkType The type of network you want to report on
3109 * @param percentage The quality of the connection 0 is bad, 100 is good
3110 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3111 * {@hide}
3112 */
3113 public void reportInetCondition(int networkType, int percentage) {
3114 printStackTrace();
3115 try {
3116 mService.reportInetCondition(networkType, percentage);
3117 } catch (RemoteException e) {
3118 throw e.rethrowFromSystemServer();
3119 }
3120 }
3121
3122 /**
3123 * Report a problem network to the framework. This provides a hint to the system
3124 * that there might be connectivity problems on this network and may cause
3125 * the framework to re-evaluate network connectivity and/or switch to another
3126 * network.
3127 *
3128 * @param network The {@link Network} the application was attempting to use
3129 * or {@code null} to indicate the current default network.
3130 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3131 * working and non-working connectivity.
3132 */
3133 @Deprecated
3134 public void reportBadNetwork(@Nullable Network network) {
3135 printStackTrace();
3136 try {
3137 // One of these will be ignored because it matches system's current state.
3138 // The other will trigger the necessary reevaluation.
3139 mService.reportNetworkConnectivity(network, true);
3140 mService.reportNetworkConnectivity(network, false);
3141 } catch (RemoteException e) {
3142 throw e.rethrowFromSystemServer();
3143 }
3144 }
3145
3146 /**
3147 * Report to the framework whether a network has working connectivity.
3148 * This provides a hint to the system that a particular network is providing
3149 * working connectivity or not. In response the framework may re-evaluate
3150 * the network's connectivity and might take further action thereafter.
3151 *
3152 * @param network The {@link Network} the application was attempting to use
3153 * or {@code null} to indicate the current default network.
3154 * @param hasConnectivity {@code true} if the application was able to successfully access the
3155 * Internet using {@code network} or {@code false} if not.
3156 */
3157 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3158 printStackTrace();
3159 try {
3160 mService.reportNetworkConnectivity(network, hasConnectivity);
3161 } catch (RemoteException e) {
3162 throw e.rethrowFromSystemServer();
3163 }
3164 }
3165
3166 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003167 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003168 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003169 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3170 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3171 * accessing any network, regardless of what the settings for that network are.
3172 *
3173 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3174 * proxy is likely to break networking on multiple networks. This method is only meant
3175 * for device policy clients looking to do general internal filtering or similar use cases.
3176 *
3177 * {@see #getGlobalProxy}
3178 * {@see LinkProperties#getHttpProxy}
3179 *
3180 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3181 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003182 * @hide
3183 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003184 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003185 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003186 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003187 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003188 try {
3189 mService.setGlobalProxy(p);
3190 } catch (RemoteException e) {
3191 throw e.rethrowFromSystemServer();
3192 }
3193 }
3194
3195 /**
3196 * Retrieve any network-independent global HTTP proxy.
3197 *
3198 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3199 * if no global HTTP proxy is set.
3200 * @hide
3201 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003202 @SystemApi(client = MODULE_LIBRARIES)
3203 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003204 public ProxyInfo getGlobalProxy() {
3205 try {
3206 return mService.getGlobalProxy();
3207 } catch (RemoteException e) {
3208 throw e.rethrowFromSystemServer();
3209 }
3210 }
3211
3212 /**
3213 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3214 * network-specific HTTP proxy. If {@code network} is null, the
3215 * network-specific proxy returned is the proxy of the default active
3216 * network.
3217 *
3218 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3219 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3220 * or when {@code network} is {@code null},
3221 * the {@code ProxyInfo} for the default active network. Returns
3222 * {@code null} when no proxy applies or the caller doesn't have
3223 * permission to use {@code network}.
3224 * @hide
3225 */
3226 public ProxyInfo getProxyForNetwork(Network network) {
3227 try {
3228 return mService.getProxyForNetwork(network);
3229 } catch (RemoteException e) {
3230 throw e.rethrowFromSystemServer();
3231 }
3232 }
3233
3234 /**
3235 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3236 * otherwise if this process is bound to a {@link Network} using
3237 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3238 * the default network's proxy is returned.
3239 *
3240 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3241 * HTTP proxy is active.
3242 */
3243 @Nullable
3244 public ProxyInfo getDefaultProxy() {
3245 return getProxyForNetwork(getBoundNetworkForProcess());
3246 }
3247
3248 /**
3249 * Returns true if the hardware supports the given network type
3250 * else it returns false. This doesn't indicate we have coverage
3251 * or are authorized onto a network, just whether or not the
3252 * hardware supports it. For example a GSM phone without a SIM
3253 * should still return {@code true} for mobile data, but a wifi only
3254 * tablet would return {@code false}.
3255 *
3256 * @param networkType The network type we'd like to check
3257 * @return {@code true} if supported, else {@code false}
3258 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3259 * @hide
3260 */
3261 @Deprecated
3262 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3263 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3264 public boolean isNetworkSupported(int networkType) {
3265 try {
3266 return mService.isNetworkSupported(networkType);
3267 } catch (RemoteException e) {
3268 throw e.rethrowFromSystemServer();
3269 }
3270 }
3271
3272 /**
3273 * Returns if the currently active data network is metered. A network is
3274 * classified as metered when the user is sensitive to heavy data usage on
3275 * that connection due to monetary costs, data limitations or
3276 * battery/performance issues. You should check this before doing large
3277 * data transfers, and warn the user or delay the operation until another
3278 * network is available.
3279 *
3280 * @return {@code true} if large transfers should be avoided, otherwise
3281 * {@code false}.
3282 */
3283 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3284 public boolean isActiveNetworkMetered() {
3285 try {
3286 return mService.isActiveNetworkMetered();
3287 } catch (RemoteException e) {
3288 throw e.rethrowFromSystemServer();
3289 }
3290 }
3291
3292 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003293 * Set sign in error notification to visible or invisible
3294 *
3295 * @hide
3296 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3297 */
3298 @Deprecated
3299 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3300 String action) {
3301 try {
3302 mService.setProvisioningNotificationVisible(visible, networkType, action);
3303 } catch (RemoteException e) {
3304 throw e.rethrowFromSystemServer();
3305 }
3306 }
3307
3308 /**
3309 * Set the value for enabling/disabling airplane mode
3310 *
3311 * @param enable whether to enable airplane mode or not
3312 *
3313 * @hide
3314 */
3315 @RequiresPermission(anyOf = {
3316 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3317 android.Manifest.permission.NETWORK_SETTINGS,
3318 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3319 android.Manifest.permission.NETWORK_STACK})
3320 @SystemApi
3321 public void setAirplaneMode(boolean enable) {
3322 try {
3323 mService.setAirplaneMode(enable);
3324 } catch (RemoteException e) {
3325 throw e.rethrowFromSystemServer();
3326 }
3327 }
3328
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003329 /**
3330 * Registers the specified {@link NetworkProvider}.
3331 * Each listener must only be registered once. The listener can be unregistered with
3332 * {@link #unregisterNetworkProvider}.
3333 *
3334 * @param provider the provider to register
3335 * @return the ID of the provider. This ID must be used by the provider when registering
3336 * {@link android.net.NetworkAgent}s.
3337 * @hide
3338 */
3339 @SystemApi
3340 @RequiresPermission(anyOf = {
3341 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3342 android.Manifest.permission.NETWORK_FACTORY})
3343 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3344 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3345 throw new IllegalStateException("NetworkProviders can only be registered once");
3346 }
3347
3348 try {
3349 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3350 provider.getName());
3351 provider.setProviderId(providerId);
3352 } catch (RemoteException e) {
3353 throw e.rethrowFromSystemServer();
3354 }
3355 return provider.getProviderId();
3356 }
3357
3358 /**
3359 * Unregisters the specified NetworkProvider.
3360 *
3361 * @param provider the provider to unregister
3362 * @hide
3363 */
3364 @SystemApi
3365 @RequiresPermission(anyOf = {
3366 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3367 android.Manifest.permission.NETWORK_FACTORY})
3368 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3369 try {
3370 mService.unregisterNetworkProvider(provider.getMessenger());
3371 } catch (RemoteException e) {
3372 throw e.rethrowFromSystemServer();
3373 }
3374 provider.setProviderId(NetworkProvider.ID_NONE);
3375 }
3376
3377
3378 /** @hide exposed via the NetworkProvider class. */
3379 @RequiresPermission(anyOf = {
3380 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3381 android.Manifest.permission.NETWORK_FACTORY})
3382 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3383 try {
3384 mService.declareNetworkRequestUnfulfillable(request);
3385 } catch (RemoteException e) {
3386 throw e.rethrowFromSystemServer();
3387 }
3388 }
3389
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003390 /**
3391 * @hide
3392 * Register a NetworkAgent with ConnectivityService.
3393 * @return Network corresponding to NetworkAgent.
3394 */
3395 @RequiresPermission(anyOf = {
3396 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3397 android.Manifest.permission.NETWORK_FACTORY})
3398 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jeand6372722020-12-21 18:36:52 +09003399 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3400 int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003401 try {
3402 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
3403 } catch (RemoteException e) {
3404 throw e.rethrowFromSystemServer();
3405 }
3406 }
3407
3408 /**
3409 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3410 * changes. Should be extended by applications wanting notifications.
3411 *
3412 * A {@code NetworkCallback} is registered by calling
3413 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3414 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3415 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3416 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3417 * A {@code NetworkCallback} should be registered at most once at any time.
3418 * A {@code NetworkCallback} that has been unregistered can be registered again.
3419 */
3420 public static class NetworkCallback {
3421 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003422 * No flags associated with this callback.
3423 * @hide
3424 */
3425 public static final int FLAG_NONE = 0;
3426 /**
3427 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3428 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3429 * <p>
3430 * These include:
3431 * <li> Some transport info instances (retrieved via
3432 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3433 * contain location sensitive information.
3434 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
3435 * sensitive for wifi suggestor apps (i.e using {@link WifiNetworkSuggestion}).</li>
3436 * </p>
3437 * <p>
3438 * Note:
3439 * <li> Retrieving this location sensitive information (subject to app's location
3440 * permissions) will be noted by system. </li>
3441 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
3442 * not include location sensitive info.
3443 * </p>
3444 */
Roshan Pius189d0092021-03-11 21:16:44 -08003445 // Note: Some existing fields which are location sensitive may still be included without
3446 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003447 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3448
3449 /** @hide */
3450 @Retention(RetentionPolicy.SOURCE)
3451 @IntDef(flag = true, prefix = "FLAG_", value = {
3452 FLAG_NONE,
3453 FLAG_INCLUDE_LOCATION_INFO
3454 })
3455 public @interface Flag { }
3456
3457 /**
3458 * All the valid flags for error checking.
3459 */
3460 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3461
3462 public NetworkCallback() {
3463 this(FLAG_NONE);
3464 }
3465
3466 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003467 if ((flags & VALID_FLAGS) != flags) {
3468 throw new IllegalArgumentException("Invalid flags");
3469 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003470 mFlags = flags;
3471 }
3472
3473 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003474 * Called when the framework connects to a new network to evaluate whether it satisfies this
3475 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3476 * callback. There is no guarantee that this new network will satisfy any requests, or that
3477 * the network will stay connected for longer than the time necessary to evaluate it.
3478 * <p>
3479 * Most applications <b>should not</b> act on this callback, and should instead use
3480 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3481 * the framework in properly evaluating the network &mdash; for example, an application that
3482 * can automatically log in to a captive portal without user intervention.
3483 *
3484 * @param network The {@link Network} of the network that is being evaluated.
3485 *
3486 * @hide
3487 */
3488 public void onPreCheck(@NonNull Network network) {}
3489
3490 /**
3491 * Called when the framework connects and has declared a new network ready for use.
3492 * This callback may be called more than once if the {@link Network} that is
3493 * satisfying the request changes.
3494 *
3495 * @param network The {@link Network} of the satisfying network.
3496 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3497 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3498 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3499 * @hide
3500 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003501 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003502 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003503 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003504 // Internally only this method is called when a new network is available, and
3505 // it calls the callback in the same way and order that older versions used
3506 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003507 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3508 onBlockedStatusChanged(network, blocked);
3509 }
3510
3511 /**
3512 * Legacy variant of onAvailable that takes a boolean blocked reason.
3513 *
3514 * This method has never been public API, but it's not final, so there may be apps that
3515 * implemented it and rely on it being called. Do our best not to break them.
3516 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3517 * this method is called. There does not seem to be a way to avoid this.
3518 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3519 *
3520 * @hide
3521 */
3522 public void onAvailable(@NonNull Network network,
3523 @NonNull NetworkCapabilities networkCapabilities,
3524 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003525 onAvailable(network);
3526 if (!networkCapabilities.hasCapability(
3527 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3528 onNetworkSuspended(network);
3529 }
3530 onCapabilitiesChanged(network, networkCapabilities);
3531 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003532 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003533 }
3534
3535 /**
3536 * Called when the framework connects and has declared a new network ready for use.
3537 *
3538 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3539 * be available at the same time, and onAvailable will be called for each of these as they
3540 * appear.
3541 *
3542 * <p>For callbacks registered with {@link #requestNetwork} and
3543 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3544 * is the new best network for this request and is now tracked by this callback ; this
3545 * callback will no longer receive method calls about other networks that may have been
3546 * passed to this method previously. The previously-best network may have disconnected, or
3547 * it may still be around and the newly-best network may simply be better.
3548 *
3549 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3550 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3551 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3552 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3553 *
3554 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3555 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3556 * this callback as this is prone to race conditions (there is no guarantee the objects
3557 * returned by these methods will be current). Instead, wait for a call to
3558 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3559 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3560 * to be well-ordered with respect to other callbacks.
3561 *
3562 * @param network The {@link Network} of the satisfying network.
3563 */
3564 public void onAvailable(@NonNull Network network) {}
3565
3566 /**
3567 * Called when the network is about to be lost, typically because there are no outstanding
3568 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3569 * with the new replacement network for graceful handover. This method is not guaranteed
3570 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3571 * network is suddenly disconnected.
3572 *
3573 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3574 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3575 * this callback as this is prone to race conditions ; calling these methods while in a
3576 * callback may return an outdated or even a null object.
3577 *
3578 * @param network The {@link Network} that is about to be lost.
3579 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3580 * connected for graceful handover; note that the network may still
3581 * suffer a hard loss at any time.
3582 */
3583 public void onLosing(@NonNull Network network, int maxMsToLive) {}
3584
3585 /**
3586 * Called when a network disconnects or otherwise no longer satisfies this request or
3587 * callback.
3588 *
3589 * <p>If the callback was registered with requestNetwork() or
3590 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3591 * returned by onAvailable() when that network is lost and no other network satisfies
3592 * the criteria of the request.
3593 *
3594 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3595 * each network which no longer satisfies the criteria of the callback.
3596 *
3597 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3598 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3599 * this callback as this is prone to race conditions ; calling these methods while in a
3600 * callback may return an outdated or even a null object.
3601 *
3602 * @param network The {@link Network} lost.
3603 */
3604 public void onLost(@NonNull Network network) {}
3605
3606 /**
3607 * Called if no network is found within the timeout time specified in
3608 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3609 * requested network request cannot be fulfilled (whether or not a timeout was
3610 * specified). When this callback is invoked the associated
3611 * {@link NetworkRequest} will have already been removed and released, as if
3612 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
3613 */
3614 public void onUnavailable() {}
3615
3616 /**
3617 * Called when the network corresponding to this request changes capabilities but still
3618 * satisfies the requested criteria.
3619 *
3620 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3621 * to be called immediately after {@link #onAvailable}.
3622 *
3623 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3624 * ConnectivityManager methods in this callback as this is prone to race conditions :
3625 * calling these methods while in a callback may return an outdated or even a null object.
3626 *
3627 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08003628 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003629 * network.
3630 */
3631 public void onCapabilitiesChanged(@NonNull Network network,
3632 @NonNull NetworkCapabilities networkCapabilities) {}
3633
3634 /**
3635 * Called when the network corresponding to this request changes {@link LinkProperties}.
3636 *
3637 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3638 * to be called immediately after {@link #onAvailable}.
3639 *
3640 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3641 * ConnectivityManager methods in this callback as this is prone to race conditions :
3642 * calling these methods while in a callback may return an outdated or even a null object.
3643 *
3644 * @param network The {@link Network} whose link properties have changed.
3645 * @param linkProperties The new {@link LinkProperties} for this network.
3646 */
3647 public void onLinkPropertiesChanged(@NonNull Network network,
3648 @NonNull LinkProperties linkProperties) {}
3649
3650 /**
3651 * Called when the network the framework connected to for this request suspends data
3652 * transmission temporarily.
3653 *
3654 * <p>This generally means that while the TCP connections are still live temporarily
3655 * network data fails to transfer. To give a specific example, this is used on cellular
3656 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3657 * means read operations on sockets on this network will block once the buffers are
3658 * drained, and write operations will block once the buffers are full.
3659 *
3660 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3661 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3662 * this callback as this is prone to race conditions (there is no guarantee the objects
3663 * returned by these methods will be current).
3664 *
3665 * @hide
3666 */
3667 public void onNetworkSuspended(@NonNull Network network) {}
3668
3669 /**
3670 * Called when the network the framework connected to for this request
3671 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3672 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
3673
3674 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3675 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3676 * this callback as this is prone to race conditions : calling these methods while in a
3677 * callback may return an outdated or even a null object.
3678 *
3679 * @hide
3680 */
3681 public void onNetworkResumed(@NonNull Network network) {}
3682
3683 /**
3684 * Called when access to the specified network is blocked or unblocked.
3685 *
3686 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3687 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3688 * this callback as this is prone to race conditions : calling these methods while in a
3689 * callback may return an outdated or even a null object.
3690 *
3691 * @param network The {@link Network} whose blocked status has changed.
3692 * @param blocked The blocked status of this {@link Network}.
3693 */
3694 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
3695
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003696 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09003697 * Called when access to the specified network is blocked or unblocked, or the reason for
3698 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003699 *
3700 * If a NetworkCallback object implements this method,
3701 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
3702 *
3703 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3704 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3705 * this callback as this is prone to race conditions : calling these methods while in a
3706 * callback may return an outdated or even a null object.
3707 *
3708 * @param network The {@link Network} whose blocked status has changed.
3709 * @param blocked The blocked status of this {@link Network}.
3710 * @hide
3711 */
3712 @SystemApi(client = MODULE_LIBRARIES)
3713 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
3714 onBlockedStatusChanged(network, blocked != 0);
3715 }
3716
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003717 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08003718 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003719 }
3720
3721 /**
3722 * Constant error codes used by ConnectivityService to communicate about failures and errors
3723 * across a Binder boundary.
3724 * @hide
3725 */
3726 public interface Errors {
3727 int TOO_MANY_REQUESTS = 1;
3728 }
3729
3730 /** @hide */
3731 public static class TooManyRequestsException extends RuntimeException {}
3732
3733 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3734 switch (e.errorCode) {
3735 case Errors.TOO_MANY_REQUESTS:
3736 return new TooManyRequestsException();
3737 default:
3738 Log.w(TAG, "Unknown service error code " + e.errorCode);
3739 return new RuntimeException(e);
3740 }
3741 }
3742
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003743 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003744 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003745 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003746 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003747 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003748 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003749 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003750 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003751 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003752 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003753 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003754 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003755 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003756 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003757 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003758 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003759 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003760 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003761 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003762 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003763 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09003764 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003765
3766 /** @hide */
3767 public static String getCallbackName(int whichCallback) {
3768 switch (whichCallback) {
3769 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3770 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3771 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3772 case CALLBACK_LOST: return "CALLBACK_LOST";
3773 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3774 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3775 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
3776 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3777 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3778 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
3779 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
3780 default:
3781 return Integer.toString(whichCallback);
3782 }
3783 }
3784
3785 private class CallbackHandler extends Handler {
3786 private static final String TAG = "ConnectivityManager.CallbackHandler";
3787 private static final boolean DBG = false;
3788
3789 CallbackHandler(Looper looper) {
3790 super(looper);
3791 }
3792
3793 CallbackHandler(Handler handler) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003794 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003795 }
3796
3797 @Override
3798 public void handleMessage(Message message) {
3799 if (message.what == EXPIRE_LEGACY_REQUEST) {
3800 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3801 return;
3802 }
3803
3804 final NetworkRequest request = getObject(message, NetworkRequest.class);
3805 final Network network = getObject(message, Network.class);
3806 final NetworkCallback callback;
3807 synchronized (sCallbacks) {
3808 callback = sCallbacks.get(request);
3809 if (callback == null) {
3810 Log.w(TAG,
3811 "callback not found for " + getCallbackName(message.what) + " message");
3812 return;
3813 }
3814 if (message.what == CALLBACK_UNAVAIL) {
3815 sCallbacks.remove(request);
3816 callback.networkRequest = ALREADY_UNREGISTERED;
3817 }
3818 }
3819 if (DBG) {
3820 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
3821 }
3822
3823 switch (message.what) {
3824 case CALLBACK_PRECHECK: {
3825 callback.onPreCheck(network);
3826 break;
3827 }
3828 case CALLBACK_AVAILABLE: {
3829 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3830 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003831 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003832 break;
3833 }
3834 case CALLBACK_LOSING: {
3835 callback.onLosing(network, message.arg1);
3836 break;
3837 }
3838 case CALLBACK_LOST: {
3839 callback.onLost(network);
3840 break;
3841 }
3842 case CALLBACK_UNAVAIL: {
3843 callback.onUnavailable();
3844 break;
3845 }
3846 case CALLBACK_CAP_CHANGED: {
3847 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3848 callback.onCapabilitiesChanged(network, cap);
3849 break;
3850 }
3851 case CALLBACK_IP_CHANGED: {
3852 LinkProperties lp = getObject(message, LinkProperties.class);
3853 callback.onLinkPropertiesChanged(network, lp);
3854 break;
3855 }
3856 case CALLBACK_SUSPENDED: {
3857 callback.onNetworkSuspended(network);
3858 break;
3859 }
3860 case CALLBACK_RESUMED: {
3861 callback.onNetworkResumed(network);
3862 break;
3863 }
3864 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003865 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003866 }
3867 }
3868 }
3869
3870 private <T> T getObject(Message msg, Class<T> c) {
3871 return (T) msg.getData().getParcelable(c.getSimpleName());
3872 }
3873 }
3874
3875 private CallbackHandler getDefaultHandler() {
3876 synchronized (sCallbacks) {
3877 if (sCallbackHandler == null) {
3878 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
3879 }
3880 return sCallbackHandler;
3881 }
3882 }
3883
3884 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3885 private static CallbackHandler sCallbackHandler;
3886
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003887 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
3888 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
3889 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003890 printStackTrace();
3891 checkCallbackNotNull(callback);
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00003892 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3893 throw new IllegalArgumentException("null NetworkCapabilities");
3894 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003895 final NetworkRequest request;
3896 final String callingPackageName = mContext.getOpPackageName();
3897 try {
3898 synchronized(sCallbacks) {
3899 if (callback.networkRequest != null
3900 && callback.networkRequest != ALREADY_UNREGISTERED) {
3901 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3902 // and requests (http://b/20701525).
3903 Log.e(TAG, "NetworkCallback was already registered");
3904 }
3905 Messenger messenger = new Messenger(handler);
3906 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08003907 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003908 if (reqType == LISTEN) {
3909 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08003910 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08003911 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003912 } else {
3913 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003914 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3915 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003916 }
3917 if (request != null) {
3918 sCallbacks.put(request, callback);
3919 }
3920 callback.networkRequest = request;
3921 }
3922 } catch (RemoteException e) {
3923 throw e.rethrowFromSystemServer();
3924 } catch (ServiceSpecificException e) {
3925 throw convertServiceException(e);
3926 }
3927 return request;
3928 }
3929
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09003930 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3931 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
3932 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
3933 legacyType, handler);
3934 }
3935
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003936 /**
3937 * Helper function to request a network with a particular legacy type.
3938 *
3939 * This API is only for use in internal system code that requests networks with legacy type and
3940 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
3941 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
3942 *
3943 * @param request {@link NetworkRequest} describing this request.
3944 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3945 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3946 * be a positive value (i.e. >0).
3947 * @param legacyType to specify the network type(#TYPE_*).
3948 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3949 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3950 * the callback must not be shared - it uniquely specifies this request.
3951 *
3952 * @hide
3953 */
3954 @SystemApi
3955 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
3956 public void requestNetwork(@NonNull NetworkRequest request,
3957 int timeoutMs, int legacyType, @NonNull Handler handler,
3958 @NonNull NetworkCallback networkCallback) {
3959 if (legacyType == TYPE_NONE) {
3960 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3961 }
3962 CallbackHandler cbHandler = new CallbackHandler(handler);
3963 NetworkCapabilities nc = request.networkCapabilities;
3964 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
3965 }
3966
3967 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003968 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003969 *
3970 * <p>This method will attempt to find the best network that matches the passed
3971 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3972 * criteria. The platform will evaluate which network is the best at its own discretion.
3973 * Throughput, latency, cost per byte, policy, user preference and other considerations
3974 * may be factored in the decision of what is considered the best network.
3975 *
3976 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3977 * matching this request, while always attempting to match the request to a better network if
3978 * possible. If a better match is found, the platform will switch this request to the now-best
3979 * network and inform the app of the newly best network by invoking
3980 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3981 * will not try to maintain any other network than the best one currently matching the request:
3982 * a network not matching any network request may be disconnected at any time.
3983 *
3984 * <p>For example, an application could use this method to obtain a connected cellular network
3985 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3986 * radio to consume additional power. Or, an application could inform the system that it wants
3987 * a network supporting sending MMSes and have the system let it know about the currently best
3988 * MMS-supporting network through the provided {@link NetworkCallback}.
3989 *
3990 * <p>The status of the request can be followed by listening to the various callbacks described
3991 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3992 * used to direct traffic to the network (although accessing some networks may be subject to
3993 * holding specific permissions). Callers will learn about the specific characteristics of the
3994 * network through
3995 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3996 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3997 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3998 * matching the request at any given time; therefore when a better network matching the request
3999 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4000 * with the new network after which no further updates are given about the previously-best
4001 * network, unless it becomes the best again at some later time. All callbacks are invoked
4002 * in order on the same thread, which by default is a thread created by the framework running
4003 * in the app.
4004 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4005 * callbacks are invoked.
4006 *
4007 * <p>This{@link NetworkRequest} will live until released via
4008 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4009 * which point the system may let go of the network at any time.
4010 *
4011 * <p>A version of this method which takes a timeout is
4012 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4013 * wait for a limited amount of time for the network to become unavailable.
4014 *
4015 * <p>It is presently unsupported to request a network with mutable
4016 * {@link NetworkCapabilities} such as
4017 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4018 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4019 * as these {@code NetworkCapabilities} represent states that a particular
4020 * network may never attain, and whether a network will attain these states
4021 * is unknown prior to bringing up the network so the framework does not
4022 * know how to go about satisfying a request with these capabilities.
4023 *
4024 * <p>This method requires the caller to hold either the
4025 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4026 * or the ability to modify system settings as determined by
4027 * {@link android.provider.Settings.System#canWrite}.</p>
4028 *
4029 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4030 * number of outstanding requests to 100 per app (identified by their UID), shared with
4031 * all variants of this method, of {@link #registerNetworkCallback} as well as
4032 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4033 * Requesting a network with this method will count toward this limit. If this limit is
4034 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4035 * make sure to unregister the callbacks with
4036 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4037 *
4038 * @param request {@link NetworkRequest} describing this request.
4039 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4040 * the callback must not be shared - it uniquely specifies this request.
4041 * The callback is invoked on the default internal Handler.
4042 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4043 * @throws SecurityException if missing the appropriate permissions.
4044 * @throws RuntimeException if the app already has too many callbacks registered.
4045 */
4046 public void requestNetwork(@NonNull NetworkRequest request,
4047 @NonNull NetworkCallback networkCallback) {
4048 requestNetwork(request, networkCallback, getDefaultHandler());
4049 }
4050
4051 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004052 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004053 *
4054 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4055 * but runs all the callbacks on the passed Handler.
4056 *
4057 * <p>This method has the same permission requirements as
4058 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4059 * and throws the same exceptions in the same conditions.
4060 *
4061 * @param request {@link NetworkRequest} describing this request.
4062 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4063 * the callback must not be shared - it uniquely specifies this request.
4064 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4065 */
4066 public void requestNetwork(@NonNull NetworkRequest request,
4067 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4068 CallbackHandler cbHandler = new CallbackHandler(handler);
4069 NetworkCapabilities nc = request.networkCapabilities;
4070 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4071 }
4072
4073 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004074 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004075 * by a timeout.
4076 *
4077 * This function behaves identically to the non-timed-out version
4078 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4079 * is not found within the given time (in milliseconds) the
4080 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4081 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4082 * not have to be released if timed-out (it is automatically released). Unregistering a
4083 * request that timed out is not an error.
4084 *
4085 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4086 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4087 * for that purpose. Calling this method will attempt to bring up the requested network.
4088 *
4089 * <p>This method has the same permission requirements as
4090 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4091 * and throws the same exceptions in the same conditions.
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 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4097 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4098 * be a positive value (i.e. >0).
4099 */
4100 public void requestNetwork(@NonNull NetworkRequest request,
4101 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4102 checkTimeout(timeoutMs);
4103 NetworkCapabilities nc = request.networkCapabilities;
4104 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4105 getDefaultHandler());
4106 }
4107
4108 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004109 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004110 * by a timeout.
4111 *
4112 * This method behaves identically to
4113 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4114 * on the passed Handler.
4115 *
4116 * <p>This method has the same permission requirements as
4117 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4118 * and throws the same exceptions in the same conditions.
4119 *
4120 * @param request {@link NetworkRequest} describing this request.
4121 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4122 * the callback must not be shared - it uniquely specifies this request.
4123 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4124 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4125 * before {@link NetworkCallback#onUnavailable} is called.
4126 */
4127 public void requestNetwork(@NonNull NetworkRequest request,
4128 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4129 checkTimeout(timeoutMs);
4130 CallbackHandler cbHandler = new CallbackHandler(handler);
4131 NetworkCapabilities nc = request.networkCapabilities;
4132 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4133 }
4134
4135 /**
4136 * The lookup key for a {@link Network} object included with the intent after
4137 * successfully finding a network for the applications request. Retrieve it with
4138 * {@link android.content.Intent#getParcelableExtra(String)}.
4139 * <p>
4140 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4141 * then you must get a ConnectivityManager instance before doing so.
4142 */
4143 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4144
4145 /**
4146 * The lookup key for a {@link NetworkRequest} object included with the intent after
4147 * successfully finding a network for the applications request. Retrieve it with
4148 * {@link android.content.Intent#getParcelableExtra(String)}.
4149 */
4150 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4151
4152
4153 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004154 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004155 *
4156 * This function behaves identically to the version that takes a NetworkCallback, but instead
4157 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4158 * the request may outlive the calling application and get called back when a suitable
4159 * network is found.
4160 * <p>
4161 * The operation is an Intent broadcast that goes to a broadcast receiver that
4162 * you registered with {@link Context#registerReceiver} or through the
4163 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4164 * <p>
4165 * The operation Intent is delivered with two extras, a {@link Network} typed
4166 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4167 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4168 * the original requests parameters. It is important to create a new,
4169 * {@link NetworkCallback} based request before completing the processing of the
4170 * Intent to reserve the network or it will be released shortly after the Intent
4171 * is processed.
4172 * <p>
4173 * If there is already a request for this Intent registered (with the equality of
4174 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4175 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4176 * <p>
4177 * The request may be released normally by calling
4178 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4179 * <p>It is presently unsupported to request a network with either
4180 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4181 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4182 * as these {@code NetworkCapabilities} represent states that a particular
4183 * network may never attain, and whether a network will attain these states
4184 * is unknown prior to bringing up the network so the framework does not
4185 * know how to go about satisfying a request with these capabilities.
4186 *
4187 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4188 * number of outstanding requests to 100 per app (identified by their UID), shared with
4189 * all variants of this method, of {@link #registerNetworkCallback} as well as
4190 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4191 * Requesting a network with this method will count toward this limit. If this limit is
4192 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4193 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4194 * or {@link #releaseNetworkRequest(PendingIntent)}.
4195 *
4196 * <p>This method requires the caller to hold either the
4197 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4198 * or the ability to modify system settings as determined by
4199 * {@link android.provider.Settings.System#canWrite}.</p>
4200 *
4201 * @param request {@link NetworkRequest} describing this request.
4202 * @param operation Action to perform when the network is available (corresponds
4203 * to the {@link NetworkCallback#onAvailable} call. Typically
4204 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4205 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4206 * @throws SecurityException if missing the appropriate permissions.
4207 * @throws RuntimeException if the app already has too many callbacks registered.
4208 */
4209 public void requestNetwork(@NonNull NetworkRequest request,
4210 @NonNull PendingIntent operation) {
4211 printStackTrace();
4212 checkPendingIntentNotNull(operation);
4213 try {
4214 mService.pendingRequestForNetwork(
4215 request.networkCapabilities, operation, mContext.getOpPackageName(),
4216 getAttributionTag());
4217 } catch (RemoteException e) {
4218 throw e.rethrowFromSystemServer();
4219 } catch (ServiceSpecificException e) {
4220 throw convertServiceException(e);
4221 }
4222 }
4223
4224 /**
4225 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4226 * <p>
4227 * This method has the same behavior as
4228 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4229 * releasing network resources and disconnecting.
4230 *
4231 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4232 * PendingIntent passed to
4233 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4234 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4235 */
4236 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4237 printStackTrace();
4238 checkPendingIntentNotNull(operation);
4239 try {
4240 mService.releasePendingNetworkRequest(operation);
4241 } catch (RemoteException e) {
4242 throw e.rethrowFromSystemServer();
4243 }
4244 }
4245
4246 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004247 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004248 }
4249
4250 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004251 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004252 }
4253
4254 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004255 if (timeoutMs <= 0) {
4256 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4257 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004258 }
4259
4260 /**
4261 * Registers to receive notifications about all networks which satisfy the given
4262 * {@link NetworkRequest}. The callbacks will continue to be called until
4263 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4264 * called.
4265 *
4266 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4267 * number of outstanding requests to 100 per app (identified by their UID), shared with
4268 * all variants of this method, of {@link #requestNetwork} as well as
4269 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4270 * Requesting a network with this method will count toward this limit. If this limit is
4271 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4272 * make sure to unregister the callbacks with
4273 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4274 *
4275 * @param request {@link NetworkRequest} describing this request.
4276 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4277 * networks change state.
4278 * The callback is invoked on the default internal Handler.
4279 * @throws RuntimeException if the app already has too many callbacks registered.
4280 */
4281 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4282 public void registerNetworkCallback(@NonNull NetworkRequest request,
4283 @NonNull NetworkCallback networkCallback) {
4284 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4285 }
4286
4287 /**
4288 * Registers to receive notifications about all networks which satisfy the given
4289 * {@link NetworkRequest}. The callbacks will continue to be called until
4290 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4291 * called.
4292 *
4293 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4294 * number of outstanding requests to 100 per app (identified by their UID), shared with
4295 * all variants of this method, of {@link #requestNetwork} as well as
4296 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4297 * Requesting a network with this method will count toward this limit. If this limit is
4298 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4299 * make sure to unregister the callbacks with
4300 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4301 *
4302 *
4303 * @param request {@link NetworkRequest} describing this request.
4304 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4305 * networks change state.
4306 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4307 * @throws RuntimeException if the app already has too many callbacks registered.
4308 */
4309 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4310 public void registerNetworkCallback(@NonNull NetworkRequest request,
4311 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4312 CallbackHandler cbHandler = new CallbackHandler(handler);
4313 NetworkCapabilities nc = request.networkCapabilities;
4314 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4315 }
4316
4317 /**
4318 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4319 * {@link NetworkRequest}.
4320 *
4321 * This function behaves identically to the version that takes a NetworkCallback, but instead
4322 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4323 * the request may outlive the calling application and get called back when a suitable
4324 * network is found.
4325 * <p>
4326 * The operation is an Intent broadcast that goes to a broadcast receiver that
4327 * you registered with {@link Context#registerReceiver} or through the
4328 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4329 * <p>
4330 * The operation Intent is delivered with two extras, a {@link Network} typed
4331 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4332 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4333 * the original requests parameters.
4334 * <p>
4335 * If there is already a request for this Intent registered (with the equality of
4336 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4337 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4338 * <p>
4339 * The request may be released normally by calling
4340 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4341 *
4342 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4343 * number of outstanding requests to 100 per app (identified by their UID), shared with
4344 * all variants of this method, of {@link #requestNetwork} as well as
4345 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4346 * Requesting a network with this method will count toward this limit. If this limit is
4347 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4348 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4349 * or {@link #releaseNetworkRequest(PendingIntent)}.
4350 *
4351 * @param request {@link NetworkRequest} describing this request.
4352 * @param operation Action to perform when the network is available (corresponds
4353 * to the {@link NetworkCallback#onAvailable} call. Typically
4354 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4355 * @throws RuntimeException if the app already has too many callbacks registered.
4356 */
4357 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4358 public void registerNetworkCallback(@NonNull NetworkRequest request,
4359 @NonNull PendingIntent operation) {
4360 printStackTrace();
4361 checkPendingIntentNotNull(operation);
4362 try {
4363 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004364 request.networkCapabilities, operation, mContext.getOpPackageName(),
4365 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004366 } catch (RemoteException e) {
4367 throw e.rethrowFromSystemServer();
4368 } catch (ServiceSpecificException e) {
4369 throw convertServiceException(e);
4370 }
4371 }
4372
4373 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004374 * Registers to receive notifications about changes in the application's default network. This
4375 * may be a physical network or a virtual network, such as a VPN that applies to the
4376 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004377 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4378 *
4379 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4380 * number of outstanding requests to 100 per app (identified by their UID), shared with
4381 * all variants of this method, of {@link #requestNetwork} as well as
4382 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4383 * Requesting a network with this method will count toward this limit. If this limit is
4384 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4385 * make sure to unregister the callbacks with
4386 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4387 *
4388 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004389 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004390 * The callback is invoked on the default internal Handler.
4391 * @throws RuntimeException if the app already has too many callbacks registered.
4392 */
4393 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4394 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4395 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4396 }
4397
4398 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004399 * Registers to receive notifications about changes in the application's default network. This
4400 * may be a physical network or a virtual network, such as a VPN that applies to the
4401 * application. The callbacks will continue to be called until either the application exits or
4402 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4403 *
4404 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4405 * number of outstanding requests to 100 per app (identified by their UID), shared with
4406 * all variants of this method, of {@link #requestNetwork} as well as
4407 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4408 * Requesting a network with this method will count toward this limit. If this limit is
4409 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4410 * make sure to unregister the callbacks with
4411 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4412 *
4413 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4414 * application's default network changes.
4415 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4416 * @throws RuntimeException if the app already has too many callbacks registered.
4417 */
4418 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4419 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4420 @NonNull Handler handler) {
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004421 registerDefaultNetworkCallbackAsUid(Process.INVALID_UID, networkCallback, handler);
4422 }
4423
4424 /**
4425 * Registers to receive notifications about changes in the default network for the specified
4426 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4427 * UID. The callbacks will continue to be called until either the application exits or
4428 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4429 *
4430 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4431 * number of outstanding requests to 100 per app (identified by their UID), shared with
4432 * all variants of this method, of {@link #requestNetwork} as well as
4433 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4434 * Requesting a network with this method will count toward this limit. If this limit is
4435 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4436 * make sure to unregister the callbacks with
4437 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4438 *
4439 * @param uid the UID for which to track default network changes.
4440 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4441 * UID's default network changes.
4442 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4443 * @throws RuntimeException if the app already has too many callbacks registered.
4444 * @hide
4445 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004446 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004447 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4448 @RequiresPermission(anyOf = {
4449 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4450 android.Manifest.permission.NETWORK_SETTINGS})
4451 public void registerDefaultNetworkCallbackAsUid(int uid,
4452 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004453 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004454 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004455 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4456 }
4457
4458 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004459 * Registers to receive notifications about changes in the system default network. The callbacks
4460 * will continue to be called until either the application exits or
4461 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4462 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004463 * This method should not be used to determine networking state seen by applications, because in
4464 * many cases, most or even all application traffic may not use the default network directly,
4465 * and traffic from different applications may go on different networks by default. As an
4466 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4467 * and not onto the system default network. Applications or system components desiring to do
4468 * determine network state as seen by applications should use other methods such as
4469 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4470 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004471 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4472 * number of outstanding requests to 100 per app (identified by their UID), shared with
4473 * all variants of this method, of {@link #requestNetwork} as well as
4474 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4475 * Requesting a network with this method will count toward this limit. If this limit is
4476 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4477 * make sure to unregister the callbacks with
4478 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4479 *
4480 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4481 * system default network changes.
4482 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4483 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004484 *
4485 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004486 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004487 @SystemApi(client = MODULE_LIBRARIES)
4488 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4489 @RequiresPermission(anyOf = {
4490 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4491 android.Manifest.permission.NETWORK_SETTINGS})
4492 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004493 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004494 CallbackHandler cbHandler = new CallbackHandler(handler);
4495 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004496 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004497 }
4498
4499 /**
junyulaibd123062021-03-15 11:48:48 +08004500 * Registers to receive notifications about the best matching network which satisfy the given
4501 * {@link NetworkRequest}. The callbacks will continue to be called until
4502 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4503 * called.
4504 *
4505 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4506 * number of outstanding requests to 100 per app (identified by their UID), shared with
4507 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4508 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4509 * Requesting a network with this method will count toward this limit. If this limit is
4510 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4511 * make sure to unregister the callbacks with
4512 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4513 *
4514 *
4515 * @param request {@link NetworkRequest} describing this request.
4516 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4517 * networks change state.
4518 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4519 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004520 */
junyulai5a5c99b2021-03-05 15:51:17 +08004521 @SuppressLint("ExecutorRegistration")
4522 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4523 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4524 final NetworkCapabilities nc = request.networkCapabilities;
4525 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004526 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004527 }
4528
4529 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004530 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4531 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4532 * network connection for updated bandwidth information. The caller will be notified via
4533 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4534 * method assumes that the caller has previously called
4535 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4536 * changes.
4537 *
4538 * @param network {@link Network} specifying which network you're interested.
4539 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4540 */
4541 public boolean requestBandwidthUpdate(@NonNull Network network) {
4542 try {
4543 return mService.requestBandwidthUpdate(network);
4544 } catch (RemoteException e) {
4545 throw e.rethrowFromSystemServer();
4546 }
4547 }
4548
4549 /**
4550 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
4551 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4552 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4553 * If the given {@code NetworkCallback} had previously been used with
4554 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4555 * will be disconnected.
4556 *
4557 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4558 * triggering it as soon as this call returns.
4559 *
4560 * @param networkCallback The {@link NetworkCallback} used when making the request.
4561 */
4562 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
4563 printStackTrace();
4564 checkCallbackNotNull(networkCallback);
4565 final List<NetworkRequest> reqs = new ArrayList<>();
4566 // Find all requests associated to this callback and stop callback triggers immediately.
4567 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4568 synchronized (sCallbacks) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +00004569 if (networkCallback.networkRequest == null) {
4570 throw new IllegalArgumentException("NetworkCallback was not registered");
4571 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004572 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4573 Log.d(TAG, "NetworkCallback was already unregistered");
4574 return;
4575 }
4576 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4577 if (e.getValue() == networkCallback) {
4578 reqs.add(e.getKey());
4579 }
4580 }
4581 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4582 for (NetworkRequest r : reqs) {
4583 try {
4584 mService.releaseNetworkRequest(r);
4585 } catch (RemoteException e) {
4586 throw e.rethrowFromSystemServer();
4587 }
4588 // Only remove mapping if rpc was successful.
4589 sCallbacks.remove(r);
4590 }
4591 networkCallback.networkRequest = ALREADY_UNREGISTERED;
4592 }
4593 }
4594
4595 /**
4596 * Unregisters a callback previously registered via
4597 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4598 *
4599 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4600 * PendingIntent passed to
4601 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4602 * Cannot be null.
4603 */
4604 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
4605 releaseNetworkRequest(operation);
4606 }
4607
4608 /**
4609 * Informs the system whether it should switch to {@code network} regardless of whether it is
4610 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4611 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4612 * the system default network regardless of any other network that's currently connected. If
4613 * {@code always} is true, then the choice is remembered, so that the next time the user
4614 * connects to this network, the system will switch to it.
4615 *
4616 * @param network The network to accept.
4617 * @param accept Whether to accept the network even if unvalidated.
4618 * @param always Whether to remember this choice in the future.
4619 *
4620 * @hide
4621 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004622 @SystemApi(client = MODULE_LIBRARIES)
4623 @RequiresPermission(anyOf = {
4624 android.Manifest.permission.NETWORK_SETTINGS,
4625 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4626 android.Manifest.permission.NETWORK_STACK,
4627 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4628 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004629 try {
4630 mService.setAcceptUnvalidated(network, accept, always);
4631 } catch (RemoteException e) {
4632 throw e.rethrowFromSystemServer();
4633 }
4634 }
4635
4636 /**
4637 * Informs the system whether it should consider the network as validated even if it only has
4638 * partial connectivity. If {@code accept} is true, then the network will be considered as
4639 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4640 * is remembered, so that the next time the user connects to this network, the system will
4641 * switch to it.
4642 *
4643 * @param network The network to accept.
4644 * @param accept Whether to consider the network as validated even if it has partial
4645 * connectivity.
4646 * @param always Whether to remember this choice in the future.
4647 *
4648 * @hide
4649 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004650 @SystemApi(client = MODULE_LIBRARIES)
4651 @RequiresPermission(anyOf = {
4652 android.Manifest.permission.NETWORK_SETTINGS,
4653 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4654 android.Manifest.permission.NETWORK_STACK,
4655 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4656 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
4657 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004658 try {
4659 mService.setAcceptPartialConnectivity(network, accept, always);
4660 } catch (RemoteException e) {
4661 throw e.rethrowFromSystemServer();
4662 }
4663 }
4664
4665 /**
4666 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4667 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4668 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4669 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4670 *
4671 * @param network The network to accept.
4672 *
4673 * @hide
4674 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004675 @SystemApi(client = MODULE_LIBRARIES)
4676 @RequiresPermission(anyOf = {
4677 android.Manifest.permission.NETWORK_SETTINGS,
4678 android.Manifest.permission.NETWORK_SETUP_WIZARD,
4679 android.Manifest.permission.NETWORK_STACK,
4680 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
4681 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004682 try {
4683 mService.setAvoidUnvalidated(network);
4684 } catch (RemoteException e) {
4685 throw e.rethrowFromSystemServer();
4686 }
4687 }
4688
4689 /**
4690 * Requests that the system open the captive portal app on the specified network.
4691 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004692 * <p>This is to be used on networks where a captive portal was detected, as per
4693 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
4694 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004695 * @param network The network to log into.
4696 *
4697 * @hide
4698 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09004699 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4700 @RequiresPermission(anyOf = {
4701 android.Manifest.permission.NETWORK_SETTINGS,
4702 android.Manifest.permission.NETWORK_STACK,
4703 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4704 })
4705 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004706 try {
4707 mService.startCaptivePortalApp(network);
4708 } catch (RemoteException e) {
4709 throw e.rethrowFromSystemServer();
4710 }
4711 }
4712
4713 /**
4714 * Requests that the system open the captive portal app with the specified extras.
4715 *
4716 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4717 * corresponding permission.
4718 * @param network Network on which the captive portal was detected.
4719 * @param appExtras Extras to include in the app start intent.
4720 * @hide
4721 */
4722 @SystemApi
4723 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4724 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
4725 try {
4726 mService.startCaptivePortalAppInternal(network, appExtras);
4727 } catch (RemoteException e) {
4728 throw e.rethrowFromSystemServer();
4729 }
4730 }
4731
4732 /**
4733 * Determine whether the device is configured to avoid bad wifi.
4734 * @hide
4735 */
4736 @SystemApi
4737 @RequiresPermission(anyOf = {
4738 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4739 android.Manifest.permission.NETWORK_STACK})
4740 public boolean shouldAvoidBadWifi() {
4741 try {
4742 return mService.shouldAvoidBadWifi();
4743 } catch (RemoteException e) {
4744 throw e.rethrowFromSystemServer();
4745 }
4746 }
4747
4748 /**
4749 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4750 * time-sensitive user-facing operations when the system default network is temporarily
4751 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4752 * this method), and the operation should be infrequent to ensure that data usage is limited.
4753 *
4754 * An example of such an operation might be a time-sensitive foreground activity, such as a
4755 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4756 */
4757 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4758
4759 /**
4760 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4761 * a backup channel for traffic that is primarily going over another network.
4762 *
4763 * An example might be maintaining backup connections to peers or servers for the purpose of
4764 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4765 * on backup paths should be negligible compared to the traffic on the main path.
4766 */
4767 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4768
4769 /**
4770 * It is acceptable to use metered data to improve network latency and performance.
4771 */
4772 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4773
4774 /**
4775 * Return value to use for unmetered networks. On such networks we currently set all the flags
4776 * to true.
4777 * @hide
4778 */
4779 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4780 MULTIPATH_PREFERENCE_HANDOVER |
4781 MULTIPATH_PREFERENCE_RELIABILITY |
4782 MULTIPATH_PREFERENCE_PERFORMANCE;
4783
4784 /** @hide */
4785 @Retention(RetentionPolicy.SOURCE)
4786 @IntDef(flag = true, value = {
4787 MULTIPATH_PREFERENCE_HANDOVER,
4788 MULTIPATH_PREFERENCE_RELIABILITY,
4789 MULTIPATH_PREFERENCE_PERFORMANCE,
4790 })
4791 public @interface MultipathPreference {
4792 }
4793
4794 /**
4795 * Provides a hint to the calling application on whether it is desirable to use the
4796 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4797 * for multipath data transfer on this network when it is not the system default network.
4798 * Applications desiring to use multipath network protocols should call this method before
4799 * each such operation.
4800 *
4801 * @param network The network on which the application desires to use multipath data.
4802 * If {@code null}, this method will return the a preference that will generally
4803 * apply to metered networks.
4804 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4805 */
4806 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4807 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
4808 try {
4809 return mService.getMultipathPreference(network);
4810 } catch (RemoteException e) {
4811 throw e.rethrowFromSystemServer();
4812 }
4813 }
4814
4815 /**
4816 * Resets all connectivity manager settings back to factory defaults.
4817 * @hide
4818 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08004819 @SystemApi(client = MODULE_LIBRARIES)
4820 @RequiresPermission(anyOf = {
4821 android.Manifest.permission.NETWORK_SETTINGS,
4822 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004823 public void factoryReset() {
4824 try {
4825 mService.factoryReset();
4826 mTetheringManager.stopAllTethering();
4827 } catch (RemoteException e) {
4828 throw e.rethrowFromSystemServer();
4829 }
4830 }
4831
4832 /**
4833 * Binds the current process to {@code network}. All Sockets created in the future
4834 * (and not explicitly bound via a bound SocketFactory from
4835 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4836 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4837 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4838 * work and all host name resolutions will fail. This is by design so an application doesn't
4839 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4840 * To clear binding pass {@code null} for {@code network}. Using individually bound
4841 * Sockets created by Network.getSocketFactory().createSocket() and
4842 * performing network-specific host name resolutions via
4843 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4844 * {@code bindProcessToNetwork}.
4845 *
4846 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4847 * the current binding.
4848 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4849 */
4850 public boolean bindProcessToNetwork(@Nullable Network network) {
4851 // Forcing callers to call through non-static function ensures ConnectivityManager
4852 // instantiated.
4853 return setProcessDefaultNetwork(network);
4854 }
4855
4856 /**
4857 * Binds the current process to {@code network}. All Sockets created in the future
4858 * (and not explicitly bound via a bound SocketFactory from
4859 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4860 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4861 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4862 * work and all host name resolutions will fail. This is by design so an application doesn't
4863 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4864 * To clear binding pass {@code null} for {@code network}. Using individually bound
4865 * Sockets created by Network.getSocketFactory().createSocket() and
4866 * performing network-specific host name resolutions via
4867 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4868 * {@code setProcessDefaultNetwork}.
4869 *
4870 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4871 * the current binding.
4872 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4873 * @deprecated This function can throw {@link IllegalStateException}. Use
4874 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4875 * is a direct replacement.
4876 */
4877 @Deprecated
4878 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
4879 int netId = (network == null) ? NETID_UNSET : network.netId;
4880 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4881
4882 if (netId != NETID_UNSET) {
4883 netId = network.getNetIdForResolv();
4884 }
4885
4886 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4887 return false;
4888 }
4889
4890 if (!isSameNetId) {
4891 // Set HTTP proxy system properties to match network.
4892 // TODO: Deprecate this static method and replace it with a non-static version.
4893 try {
Remi NGUYEN VAN345c2df2021-02-03 10:18:20 +09004894 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004895 } catch (SecurityException e) {
4896 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4897 Log.e(TAG, "Can't set proxy properties", e);
4898 }
4899 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VAN342dddd2021-03-18 23:27:19 +09004900 InetAddressCompat.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004901 // Must flush socket pool as idle sockets will be bound to previous network and may
4902 // cause subsequent fetches to be performed on old network.
4903 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
4904 }
4905
4906 return true;
4907 }
4908
4909 /**
4910 * Returns the {@link Network} currently bound to this process via
4911 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4912 *
4913 * @return {@code Network} to which this process is bound, or {@code null}.
4914 */
4915 @Nullable
4916 public Network getBoundNetworkForProcess() {
4917 // Forcing callers to call thru non-static function ensures ConnectivityManager
4918 // instantiated.
4919 return getProcessDefaultNetwork();
4920 }
4921
4922 /**
4923 * Returns the {@link Network} currently bound to this process via
4924 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4925 *
4926 * @return {@code Network} to which this process is bound, or {@code null}.
4927 * @deprecated Using this function can lead to other functions throwing
4928 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4929 * {@code getBoundNetworkForProcess} is a direct replacement.
4930 */
4931 @Deprecated
4932 @Nullable
4933 public static Network getProcessDefaultNetwork() {
4934 int netId = NetworkUtils.getBoundNetworkForProcess();
4935 if (netId == NETID_UNSET) return null;
4936 return new Network(netId);
4937 }
4938
4939 private void unsupportedStartingFrom(int version) {
4940 if (Process.myUid() == Process.SYSTEM_UID) {
4941 // The getApplicationInfo() call we make below is not supported in system context. Let
4942 // the call through here, and rely on the fact that ConnectivityService will refuse to
4943 // allow the system to use these APIs anyway.
4944 return;
4945 }
4946
4947 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4948 throw new UnsupportedOperationException(
4949 "This method is not supported in target SDK version " + version + " and above");
4950 }
4951 }
4952
4953 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4954 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
4955 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
4956 // remove these exemptions. Note that this check is not secure, and apps can still access these
4957 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4958 // so is unsupported and may break in the future. http://b/22728205
4959 private void checkLegacyRoutingApiAccess() {
4960 unsupportedStartingFrom(VERSION_CODES.M);
4961 }
4962
4963 /**
4964 * Binds host resolutions performed by this process to {@code network}.
4965 * {@link #bindProcessToNetwork} takes precedence over this setting.
4966 *
4967 * @param network The {@link Network} to bind host resolutions from the current process to, or
4968 * {@code null} to clear the current binding.
4969 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4970 * @hide
4971 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4972 */
4973 @Deprecated
4974 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4975 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
4976 return NetworkUtils.bindProcessToNetworkForHostResolution(
4977 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
4978 }
4979
4980 /**
4981 * Device is not restricting metered network activity while application is running on
4982 * background.
4983 */
4984 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4985
4986 /**
4987 * Device is restricting metered network activity while application is running on background,
4988 * but application is allowed to bypass it.
4989 * <p>
4990 * In this state, application should take action to mitigate metered network access.
4991 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4992 */
4993 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4994
4995 /**
4996 * Device is restricting metered network activity while application is running on background.
4997 * <p>
4998 * In this state, application should not try to use the network while running on background,
4999 * because it would be denied.
5000 */
5001 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5002
5003 /**
5004 * A change in the background metered network activity restriction has occurred.
5005 * <p>
5006 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5007 * applies to them.
5008 * <p>
5009 * This is only sent to registered receivers, not manifest receivers.
5010 */
5011 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5012 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5013 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5014
5015 /** @hide */
5016 @Retention(RetentionPolicy.SOURCE)
5017 @IntDef(flag = false, value = {
5018 RESTRICT_BACKGROUND_STATUS_DISABLED,
5019 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5020 RESTRICT_BACKGROUND_STATUS_ENABLED,
5021 })
5022 public @interface RestrictBackgroundStatus {
5023 }
5024
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005025 /**
5026 * Determines if the calling application is subject to metered network restrictions while
5027 * running on background.
5028 *
5029 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5030 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5031 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5032 */
5033 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5034 try {
Remi NGUYEN VANe62e7ff2021-03-18 14:23:12 +09005035 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005036 } catch (RemoteException e) {
5037 throw e.rethrowFromSystemServer();
5038 }
5039 }
5040
5041 /**
5042 * The network watchlist is a list of domains and IP addresses that are associated with
5043 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5044 * currently used by the system for validation purposes.
5045 *
5046 * @return Hash of network watchlist config file. Null if config does not exist.
5047 */
5048 @Nullable
5049 public byte[] getNetworkWatchlistConfigHash() {
5050 try {
5051 return mService.getNetworkWatchlistConfigHash();
5052 } catch (RemoteException e) {
5053 Log.e(TAG, "Unable to get watchlist config hash");
5054 throw e.rethrowFromSystemServer();
5055 }
5056 }
5057
5058 /**
5059 * Returns the {@code uid} of the owner of a network connection.
5060 *
5061 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5062 * IPPROTO_UDP} currently supported.
5063 * @param local The local {@link InetSocketAddress} of a connection.
5064 * @param remote The remote {@link InetSocketAddress} of a connection.
5065 * @return {@code uid} if the connection is found and the app has permission to observe it
5066 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5067 * android.os.Process#INVALID_UID} if the connection is not found.
5068 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
5069 * user.
5070 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
5071 */
5072 public int getConnectionOwnerUid(
5073 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5074 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5075 try {
5076 return mService.getConnectionOwnerUid(connectionInfo);
5077 } catch (RemoteException e) {
5078 throw e.rethrowFromSystemServer();
5079 }
5080 }
5081
5082 private void printStackTrace() {
5083 if (DEBUG) {
5084 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5085 final StringBuffer sb = new StringBuffer();
5086 for (int i = 3; i < callStack.length; i++) {
5087 final String stackTrace = callStack[i].toString();
5088 if (stackTrace == null || stackTrace.contains("android.os")) {
5089 break;
5090 }
5091 sb.append(" [").append(stackTrace).append("]");
5092 }
5093 Log.d(TAG, "StackLog:" + sb.toString());
5094 }
5095 }
5096
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005097 /** @hide */
5098 public TestNetworkManager startOrGetTestNetworkManager() {
5099 final IBinder tnBinder;
5100 try {
5101 tnBinder = mService.startOrGetTestNetworkService();
5102 } catch (RemoteException e) {
5103 throw e.rethrowFromSystemServer();
5104 }
5105
5106 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5107 }
5108
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005109 /** @hide */
5110 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5111 return new ConnectivityDiagnosticsManager(mContext, mService);
5112 }
5113
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005114 /**
5115 * Simulates a Data Stall for the specified Network.
5116 *
5117 * <p>This method should only be used for tests.
5118 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005119 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5120 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005121 *
5122 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005123 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5124 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5125 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005126 * @param network The Network for which a Data Stall is being simluated.
5127 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5128 * @throws SecurityException if the caller is not the owner of the given network.
5129 * @hide
5130 */
5131 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5132 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5133 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005134 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005135 @NonNull Network network, @NonNull PersistableBundle extras) {
5136 try {
5137 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5138 } catch (RemoteException e) {
5139 e.rethrowFromSystemServer();
5140 }
5141 }
5142
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005143 @NonNull
5144 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5145
5146 /**
5147 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5148 * receive available QoS events related to the {@link Network} and local ip + port
5149 * specified within socketInfo.
5150 * <p/>
5151 * The same {@link QosCallback} must be unregistered before being registered a second time,
5152 * otherwise {@link QosCallbackRegistrationException} is thrown.
5153 * <p/>
5154 * This API does not, in itself, require any permission if called with a network that is not
5155 * restricted. However, the underlying implementation currently only supports the IMS network,
5156 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5157 * useful, because they'd never be called back on networks that they would have access to.
5158 *
5159 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5160 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5161 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5162 * @throws RuntimeException if the app already has too many callbacks registered.
5163 *
5164 * Exceptions after the time of registration is passed through
5165 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5166 *
5167 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005168 * @param executor The executor on which the callback will be invoked. The provided
5169 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005170 * callbacks cannot be guaranteed.onQosCallbackRegistered
5171 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005172 *
5173 * @hide
5174 */
5175 @SystemApi
5176 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005177 @CallbackExecutor @NonNull final Executor executor,
5178 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005179 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005180 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005181 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005182
5183 try {
5184 synchronized (mQosCallbackConnections) {
5185 if (getQosCallbackConnection(callback) == null) {
5186 final QosCallbackConnection connection =
5187 new QosCallbackConnection(this, callback, executor);
5188 mQosCallbackConnections.add(connection);
5189 mService.registerQosSocketCallback(socketInfo, connection);
5190 } else {
5191 Log.e(TAG, "registerQosCallback: Callback already registered");
5192 throw new QosCallbackRegistrationException();
5193 }
5194 }
5195 } catch (final RemoteException e) {
5196 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5197
5198 // The same unregister method method is called for consistency even though nothing
5199 // will be sent to the ConnectivityService since the callback was never successfully
5200 // registered.
5201 unregisterQosCallback(callback);
5202 e.rethrowFromSystemServer();
5203 } catch (final ServiceSpecificException e) {
5204 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5205 unregisterQosCallback(callback);
5206 throw convertServiceException(e);
5207 }
5208 }
5209
5210 /**
5211 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5212 * events once unregistered and can be registered a second time.
5213 * <p/>
5214 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5215 *
5216 * @param callback the callback being unregistered
5217 *
5218 * @hide
5219 */
5220 @SystemApi
5221 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5222 Objects.requireNonNull(callback, "The callback must be non-null");
5223 try {
5224 synchronized (mQosCallbackConnections) {
5225 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5226 if (connection != null) {
5227 connection.stopReceivingMessages();
5228 mService.unregisterQosCallback(connection);
5229 mQosCallbackConnections.remove(connection);
5230 } else {
5231 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5232 }
5233 }
5234 } catch (final RemoteException e) {
5235 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5236 e.rethrowFromSystemServer();
5237 }
5238 }
5239
5240 /**
5241 * Gets the connection related to the callback.
5242 *
5243 * @param callback the callback to look up
5244 * @return the related connection
5245 */
5246 @Nullable
5247 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5248 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5249 // Checking by reference here is intentional
5250 if (connection.getCallback() == callback) {
5251 return connection;
5252 }
5253 }
5254 return null;
5255 }
5256
5257 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005258 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005259 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5260 * be used to request that the system provide a network without causing the network to be
5261 * in the foreground.
5262 *
5263 * <p>This method will attempt to find the best network that matches the passed
5264 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5265 * criteria. The platform will evaluate which network is the best at its own discretion.
5266 * Throughput, latency, cost per byte, policy, user preference and other considerations
5267 * may be factored in the decision of what is considered the best network.
5268 *
5269 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5270 * matching this request, while always attempting to match the request to a better network if
5271 * possible. If a better match is found, the platform will switch this request to the now-best
5272 * network and inform the app of the newly best network by invoking
5273 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5274 * will not try to maintain any other network than the best one currently matching the request:
5275 * a network not matching any network request may be disconnected at any time.
5276 *
5277 * <p>For example, an application could use this method to obtain a connected cellular network
5278 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5279 * radio to consume additional power. Or, an application could inform the system that it wants
5280 * a network supporting sending MMSes and have the system let it know about the currently best
5281 * MMS-supporting network through the provided {@link NetworkCallback}.
5282 *
5283 * <p>The status of the request can be followed by listening to the various callbacks described
5284 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5285 * used to direct traffic to the network (although accessing some networks may be subject to
5286 * holding specific permissions). Callers will learn about the specific characteristics of the
5287 * network through
5288 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5289 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5290 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5291 * matching the request at any given time; therefore when a better network matching the request
5292 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5293 * with the new network after which no further updates are given about the previously-best
5294 * network, unless it becomes the best again at some later time. All callbacks are invoked
5295 * in order on the same thread, which by default is a thread created by the framework running
5296 * in the app.
5297 *
5298 * <p>This{@link NetworkRequest} will live until released via
5299 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5300 * which point the system may let go of the network at any time.
5301 *
5302 * <p>It is presently unsupported to request a network with mutable
5303 * {@link NetworkCapabilities} such as
5304 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5305 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5306 * as these {@code NetworkCapabilities} represent states that a particular
5307 * network may never attain, and whether a network will attain these states
5308 * is unknown prior to bringing up the network so the framework does not
5309 * know how to go about satisfying a request with these capabilities.
5310 *
5311 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5312 * number of outstanding requests to 100 per app (identified by their UID), shared with
5313 * all variants of this method, of {@link #registerNetworkCallback} as well as
5314 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5315 * Requesting a network with this method will count toward this limit. If this limit is
5316 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5317 * make sure to unregister the callbacks with
5318 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5319 *
5320 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005321 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5322 * the callback must not be shared - it uniquely specifies this request.
junyulai8c8ac362021-04-15 00:39:49 +08005323 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5324 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005325 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5326 * @throws SecurityException if missing the appropriate permissions.
5327 * @throws RuntimeException if the app already has too many callbacks registered.
5328 *
5329 * @hide
5330 */
5331 @SystemApi(client = MODULE_LIBRARIES)
5332 @SuppressLint("ExecutorRegistration")
5333 @RequiresPermission(anyOf = {
5334 android.Manifest.permission.NETWORK_SETTINGS,
5335 android.Manifest.permission.NETWORK_STACK,
5336 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5337 })
5338 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulai8c8ac362021-04-15 00:39:49 +08005339 @NonNull NetworkCallback networkCallback,
5340 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005341 final NetworkCapabilities nc = request.networkCapabilities;
5342 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005343 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005344 }
James Mattis12aeab82021-01-10 14:24:24 -08005345
5346 /**
James Mattis12aeab82021-01-10 14:24:24 -08005347 * Used by automotive devices to set the network preferences used to direct traffic at an
5348 * application level as per the given OemNetworkPreferences. An example use-case would be an
5349 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5350 * vehicle via a particular network.
5351 *
5352 * Calling this will overwrite the existing preference.
5353 *
5354 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5355 * @param executor the executor on which listener will be invoked.
5356 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5357 * communicate completion of setOemNetworkPreference(). This will only be
5358 * called once upon successful completion of setOemNetworkPreference().
5359 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5360 * @throws SecurityException if missing the appropriate permissions.
5361 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005362 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005363 */
James Mattis6e2d7022021-01-26 16:23:52 -08005364 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005365 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005366 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005367 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005368 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005369 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5370 if (null != listener) {
5371 Objects.requireNonNull(executor, "Executor must be non-null");
5372 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005373 final IOnCompleteListener listenerInternal = listener == null ? null :
5374 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005375 @Override
5376 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005377 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005378 }
5379 };
5380
5381 try {
5382 mService.setOemNetworkPreference(preference, listenerInternal);
5383 } catch (RemoteException e) {
5384 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5385 throw e.rethrowFromSystemServer();
5386 }
5387 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005388
Chalard Jeanad565e22021-02-25 17:23:40 +09005389 /**
5390 * Request that a user profile is put by default on a network matching a given preference.
5391 *
5392 * See the documentation for the individual preferences for a description of the supported
5393 * behaviors.
5394 *
5395 * @param profile the profile concerned.
5396 * @param preference the preference for this profile.
5397 * @param executor an executor to execute the listener on. Optional if listener is null.
5398 * @param listener an optional listener to listen for completion of the operation.
5399 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5400 * @throws SecurityException if missing the appropriate permissions.
5401 * @hide
5402 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005403 // This function is for establishing per-profile default networking and can only be called by
5404 // the device policy manager, running as the system server. It would make no sense to call it
5405 // on a context for a user because it does not establish a setting on behalf of a user, rather
5406 // it establishes a setting for a user on behalf of the DPM.
5407 @SuppressLint({"UserHandle"})
5408 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005409 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5410 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5411 @ProfileNetworkPreference final int preference,
5412 @Nullable @CallbackExecutor final Executor executor,
5413 @Nullable final Runnable listener) {
5414 if (null != listener) {
5415 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5416 }
5417 final IOnCompleteListener proxy;
5418 if (null == listener) {
5419 proxy = null;
5420 } else {
5421 proxy = new IOnCompleteListener.Stub() {
5422 @Override
5423 public void onComplete() {
5424 executor.execute(listener::run);
5425 }
5426 };
5427 }
5428 try {
5429 mService.setProfileNetworkPreference(profile, preference, proxy);
5430 } catch (RemoteException e) {
5431 throw e.rethrowFromSystemServer();
5432 }
5433 }
5434
lucaslin5cdbcfb2021-03-12 00:46:33 +08005435 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005436 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005437 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005438 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005439
5440 /**
5441 * Get the network ID range reserved for IPSec tunnel interfaces.
5442 *
5443 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5444 * @hide
5445 */
5446 @SystemApi(client = MODULE_LIBRARIES)
5447 @NonNull
5448 public static Range<Integer> getIpSecNetIdRange() {
5449 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5450 }
lucaslin889dcda2021-03-12 17:56:09 +08005451
5452 /**
5453 * Get private DNS mode from settings.
5454 *
lucaslindebfe602021-03-17 14:53:35 +08005455 * @param context The Context to query the private DNS mode from settings.
lucaslin889dcda2021-03-12 17:56:09 +08005456 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5457 *
5458 * @hide
5459 */
5460 @SystemApi(client = MODULE_LIBRARIES)
5461 @NonNull
5462 @PrivateDnsMode
lucasline2cd02d2021-03-16 17:11:14 +08005463 public static String getPrivateDnsMode(@NonNull Context context) {
5464 final ContentResolver cr = context.getContentResolver();
lucaslin889dcda2021-03-12 17:56:09 +08005465 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5466 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5467 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5468 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5469 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5470 return mode;
5471 }
paulhu6865eb62021-03-25 12:36:56 +08005472
5473 /**
5474 * Set private DNS mode to settings.
5475 *
5476 * @param context The {@link Context} to set the private DNS mode.
5477 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5478 *
5479 * @hide
5480 */
5481 @SystemApi(client = MODULE_LIBRARIES)
5482 public static void setPrivateDnsMode(@NonNull Context context,
5483 @NonNull @PrivateDnsMode String mode) {
5484 if (!(mode == PRIVATE_DNS_MODE_OFF
5485 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5486 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5487 throw new IllegalArgumentException("Invalid private dns mode");
5488 }
5489 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5490 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005491}