blob: 35a3a40c27b61632b5121937de218993ab0cf405 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
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 */
The Android Open Source Project28527d22009-03-03 19:31:44 -080016package android.net;
17
Junyu Laia62493f2021-01-19 11:10:56 +000018import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
paulhu56e09df2021-03-17 20:30:33 +080019import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_DEFAULT_MODE;
20import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE;
Junyu Laia62493f2021-01-19 11:10:56 +000021import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaiad010792021-01-11 16:53:38 +080022import static android.net.NetworkRequest.Type.LISTEN;
junyulai1b1c8742021-03-12 20:05:08 +080023import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
junyulaiad010792021-01-11 16:53:38 +080024import static android.net.NetworkRequest.Type.REQUEST;
25import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +090026import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Brightf9e945b2020-06-15 16:10:01 -070027import static android.net.QosCallback.QosCallbackRegistrationException;
junyulaid05a1922019-01-15 11:32:44 +080028
junyulai4c95b082018-12-27 17:25:29 +080029import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080030import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090031import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000032import android.annotation.Nullable;
Jeff Sharkey656584a2017-04-24 11:18:03 -060033import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080034import android.annotation.SdkConstant;
35import android.annotation.SdkConstant.SdkConstantType;
lucaslin705c3332021-03-12 17:56:09 +080036import android.annotation.StringDef;
Junyu Laia62493f2021-01-19 11:10:56 +000037import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080038import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060039import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070040import android.app.PendingIntent;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090041import android.app.admin.DevicePolicyManager;
Artur Satayev9c2add62019-12-10 17:47:52 +000042import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090043import android.content.ComponentName;
lucaslin705c3332021-03-12 17:56:09 +080044import android.content.ContentResolver;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070045import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070046import android.content.Intent;
Remi NGUYEN VANd2d60c62021-04-08 16:26:20 +090047import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
junyulai4c95b082018-12-27 17:25:29 +080048import android.net.IpSecManager.UdpEncapsulationSocket;
49import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080050import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080051import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080052import android.net.TetheringManager.TetheringRequest;
Roshan Pius951c0032020-12-22 15:10:42 -080053import android.net.wifi.WifiNetworkSuggestion;
Robert Greenwalt2034b912009-08-12 16:08:25 -070054import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000055import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070056import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080057import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070058import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080059import android.os.IBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070060import android.os.Looper;
61import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070062import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080063import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070064import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090065import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080066import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080067import android.os.ResultReceiver;
Hugo Benichia590ab82017-05-11 13:16:17 +090068import android.os.ServiceSpecificException;
Chalard Jeanfa45a682021-02-25 17:23:40 +090069import android.os.UserHandle;
Jeff Sharkey971cd162011-08-29 16:02:57 -070070import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080071import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080072import android.telephony.TelephonyManager;
lucaslin705c3332021-03-12 17:56:09 +080073import android.text.TextUtils;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080074import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070075import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090076import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090077import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080078
markchien6ae63e52020-01-21 13:11:06 +080079import com.android.internal.annotations.GuardedBy;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070080
Paul Jensen3e2917c2014-08-27 12:38:45 -040081import libcore.net.event.NetworkEventDispatcher;
82
junyulai7e06ad42019-03-04 22:45:36 +080083import java.io.IOException;
84import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080085import java.lang.annotation.Retention;
86import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090087import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080088import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070089import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080090import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090091import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090092import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080093import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090094import java.util.List;
95import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080096import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080097import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080098import java.util.concurrent.ExecutorService;
99import java.util.concurrent.Executors;
100import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -0800101
The Android Open Source Project28527d22009-03-03 19:31:44 -0800102/**
103 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600104 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800105 * <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>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700114 * <li>Provide an API that allows applications to request and select networks for their data
115 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800116 * </ol>
117 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600118@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700119public class ConnectivityManager {
120 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900121 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700122
The Android Open Source Project28527d22009-03-03 19:31:44 -0800123 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700124 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800125 * 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/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800129 * 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/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800136 * 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
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800145 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800146 * 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.
Chalard Jean52e23962018-02-10 05:33:50 +0900152 *
153 * @deprecated apps should use the more versatile {@link #requestNetwork},
154 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
155 * functions instead for faster and more detailed updates about the network
156 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800158 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900159 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800160 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700161
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500163 * 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
Paul Jensen75e0adb2015-05-22 10:50:39 -0400167 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500168 * 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/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400173 * 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
Chalard Jean9dd11612018-06-04 16:52:49 +0900182 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400183 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500184 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400185 * {@link CaptivePortal#ignoreNetwork}. </li>
186 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500187 */
188 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
189 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
190
191 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800192 * The lookup key for a {@link NetworkInfo} object. Retrieve with
193 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700194 *
Chalard Jean97021a12019-01-11 16:47:53 +0900195 * @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.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800199 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700200 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800201 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700202
The Android Open Source Project28527d22009-03-03 19:31:44 -0800203 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700204 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700205 *
206 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900207 * @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.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700210 */
Chalard Jean97021a12019-01-11 16:47:53 +0900211 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700212 public static final String EXTRA_NETWORK_TYPE = "networkType";
213
214 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800215 * 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)}.
junyulai9826e7f2018-12-13 12:47:51 +0800219 *
220 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800221 */
junyulai9826e7f2018-12-13 12:47:51 +0800222 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800223 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)}.
junyulai9826e7f2018-12-13 12:47:51 +0800228 *
229 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230 */
junyulai9826e7f2018-12-13 12:47:51 +0800231 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232 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)}.
junyulai9826e7f2018-12-13 12:47:51 +0800252 *
253 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800254 */
junyulai9826e7f2018-12-13 12:47:51 +0800255 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800256 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700257 /**
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
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700261 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700262 * {@hide}
263 */
264 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800265 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400266 * 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)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500272 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400273 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700274
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
Paul Jensen60df4aa2015-02-27 22:55:47 -0500280 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900281 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
282 * portal login activity.
283 * {@hide}
284 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900285 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900286 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
287 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
288
289 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900290 * Key for passing a user agent string to the captive portal login activity.
291 * {@hide}
292 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900293 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900294 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
295 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
296
297 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700298 * Broadcast action to indicate the change of data activity status
299 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800300 * The network becomes active when data transmission is started, or
301 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700302 * {@hide}
303 */
304 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900305 public static final String ACTION_DATA_ACTIVITY_CHANGE =
306 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700307 /**
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";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700319 /**
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";
Haoyu Baib5da5752012-06-20 14:29:57 -0700324
325 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800326 * 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
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700331 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800332 * <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.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800342 */
343 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800344 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800345 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
346 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
347
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700348 /**
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 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800355 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100356 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700357 public static final String INET_CONDITION_ACTION =
358 "android.net.conn.INET_CONDITION_ACTION";
359
Robert Greenwalt2034b912009-08-12 16:08:25 -0700360 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800361 * Broadcast Action: A tetherable connection has come or gone.
362 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900363 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
364 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800365 * {@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).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800368 * @hide
369 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800370 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000371 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800372 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800373 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800374
375 /**
376 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800377 * gives a String[] listing all the interfaces configured for
378 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800379 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000380 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800381 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800382
383 /**
384 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900385 * gives a String[] listing all the interfaces currently in local-only
386 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800387 */
markchiena0f8fd92019-12-25 19:40:32 +0800388 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900389
390 /**
391 * @hide
392 * gives a String[] listing all the interfaces currently tethered
393 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
394 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000395 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800396 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800397
398 /**
399 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800400 * 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.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800403 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800405 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800406
407 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800408 * 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 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800413 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800414 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 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900424 * 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 *
lucaslin311b6902021-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 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900430 * @hide
431 */
lucasline8b3f9c2021-03-04 17:09:51 +0800432 @SystemApi(client = MODULE_LIBRARIES)
433 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900434
435 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900436 * 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 *
lucaslin311b6902021-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 *
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900443 * @hide
444 */
lucasline8b3f9c2021-03-04 17:09:51 +0800445 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900446 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucasline8b3f9c2021-03-04 17:09:51 +0800447 "android.net.action.PROMPT_LOST_VALIDATION";
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900448
449 /**
lucaslin2240ef62019-03-12 13:08:03 +0800450 * 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 *
lucaslin311b6902021-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 *
lucaslin2240ef62019-03-12 13:08:03 +0800458 * @hide
459 */
lucasline8b3f9c2021-03-04 17:09:51 +0800460 @SystemApi(client = MODULE_LIBRARIES)
lucaslin2240ef62019-03-12 13:08:03 +0800461 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucasline8b3f9c2021-03-04 17:09:51 +0800462 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
lucaslin2240ef62019-03-12 13:08:03 +0800463
464 /**
paulhue3fe4d02021-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 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800474 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900475 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800476 * @hide
477 */
markchiena0f8fd92019-12-25 19:40:32 +0800478 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800479
480 /**
481 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900482 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800483 * @hide
484 */
485 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900486 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800487
488 /**
489 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900490 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800491 * @hide
492 */
493 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900494 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800495
496 /**
497 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900498 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800499 * @hide
500 */
501 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900502 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800503
504 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800505 * 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 */
markchiena0f8fd92019-12-25 19:40:32 +0800510 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800511
512 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800513 * Extra used for communicating with the TetherService. Includes the type of tethering to
514 * enable if any.
515 * @hide
516 */
markchien6ae63e52020-01-21 13:11:06 +0800517 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800518
519 /**
520 * Extra used for communicating with the TetherService. Includes the type of tethering for
521 * which to cancel provisioning.
522 * @hide
523 */
markchien6ae63e52020-01-21 13:11:06 +0800524 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800525
526 /**
527 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
528 * provisioning.
529 * @hide
530 */
markchien6ae63e52020-01-21 13:11:06 +0800531 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800532
533 /**
534 * Tells the TetherService to run a provision check now.
535 * @hide
536 */
markchien6ae63e52020-01-21 13:11:06 +0800537 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800538
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 */
markchien6ae63e52020-01-21 13:11:06 +0800544 public static final String EXTRA_PROVISION_CALLBACK =
545 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800546
547 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800548 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700549 * @hide
550 */
paulhu74357e72020-01-13 16:46:45 +0800551 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700552 public static final int TYPE_NONE = -1;
553
554 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900555 * 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.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700560 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900561 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900563
Robert Greenwalt2034b912009-08-12 16:08:25 -0700564 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900565 * 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.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700570 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900571 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700572 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900573
Robert Greenwalt2034b912009-08-12 16:08:25 -0700574 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800575 * 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.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900579 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900580 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900581 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900582 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700583 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700584 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700585 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900586
Robert Greenwalt2034b912009-08-12 16:08:25 -0700587 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800588 * 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.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900592 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900593 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900594 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900595 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700596 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700597 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700598 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900599
Robert Greenwalt2034b912009-08-12 16:08:25 -0700600 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800601 * 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.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900605 *
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.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700609 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900610 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700611 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900612
Robert Greenwalt2034b912009-08-12 16:08:25 -0700613 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800614 * A High Priority Mobile data connection. This network type uses the
615 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900616 * is different.
617 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900618 * @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.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700621 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700622 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700623 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900624
jshbfa81722010-03-11 15:04:43 -0800625 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900626 * 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.
jshbfa81722010-03-11 15:04:43 -0800631 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900632 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800633 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800634
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800635 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900636 * 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.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800641 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900642 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800643 public static final int TYPE_BLUETOOTH = 7;
644
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700645 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800646 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900647 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700648 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900649 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800650 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800651
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700652 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900653 * 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.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700658 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900659 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800660 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700661
Wink Savilleb7c92c72011-03-12 14:52:01 -0800662 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800663 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900664 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800665 * {@hide}
666 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900667 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900668 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800669 public static final int TYPE_MOBILE_FOTA = 10;
670
671 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800672 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900673 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800674 * {@hide}
675 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900676 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100677 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800678 public static final int TYPE_MOBILE_IMS = 11;
679
680 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800681 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900682 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800683 * {@hide}
684 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900685 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900686 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800687 public static final int TYPE_MOBILE_CBS = 12;
688
repo syncf5de5572011-07-29 23:55:49 -0700689 /**
690 * A Wi-Fi p2p connection. Only requesting processes will have access to
691 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900692 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700693 * {@hide}
694 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900695 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800696 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700697 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800698
Wink Saville512c2202013-07-29 15:00:57 -0700699 /**
700 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900701 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700702 * {@hide}
703 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900704 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100705 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700706 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700707
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900708 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700709 * Emergency PDN connection for emergency services. This
710 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900711 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700712 * {@hide}
713 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900714 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900715 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700716 public static final int TYPE_MOBILE_EMERGENCY = 15;
717
Hui Lu865b70d2014-01-15 11:05:36 -0500718 /**
719 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900720 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500721 * {@hide}
722 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900723 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900724 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500725 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700726
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700727 /**
728 * A virtual network using one or more native bearers.
729 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900730 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700731 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900732 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700733 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500734
Benedict Wongbdfaa482018-11-14 17:40:55 -0800735 /**
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.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700743
Chalard Jeanaea539a2020-03-25 01:24:04 +0900744 /**
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
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900774 // 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
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700780 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800781 public static final int MAX_RADIO_TYPE = TYPE_TEST;
782
783 /** {@hide} */
784 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800785
Hugo Benichiad353f42017-06-20 14:07:59 +0900786 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
787
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800788 /**
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
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800794 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800795 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800796 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800797 * from an App.
798 */
799 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800800 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
801
Jeff Sharkey8c870452012-09-26 22:03:49 -0700802 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700803 * @hide
804 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900805 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700806
Paul Jensen5dea4352014-07-11 12:28:19 -0400807 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900808 * 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
Chalard Jean9dd11612018-06-04 16:52:49 +0900810 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900811 * @hide
812 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900813 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900814 new NetworkRequest.Builder().clearCapabilities().build();
815
816 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400817 * 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
Erik Klineb0be3e62017-10-30 15:29:44 +0900823 /**
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 */
lucaslin705c3332021-03-12 17:56:09 +0800833 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900834 public static final String PRIVATE_DNS_MODE_OFF = "off";
835 /**
836 * @hide
837 */
lucaslin705c3332021-03-12 17:56:09 +0800838 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900839 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
840 /**
841 * @hide
842 */
lucaslin705c3332021-03-12 17:56:09 +0800843 @SystemApi(client = MODULE_LIBRARIES)
Erik Klineb0be3e62017-10-30 15:29:44 +0900844 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
lucaslin705c3332021-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 {}
Erik Klineb0be3e62017-10-30 15:29:44 +0900854
Sudheer Shanka98215562021-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 Colitti79c6f222021-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 Shanka98215562021-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 Colitti42fe2232021-03-25 23:17:36 +0900948 BLOCKED_REASON_LOCKDOWN_VPN,
Sudheer Shanka98215562021-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 Colitti79c6f222021-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
Chalard Jeana3b77512019-04-09 15:46:21 +0900963 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700964 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900965
Paul Jensenc0618a62014-12-10 15:12:18 -0500966 /**
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;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800973
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900974 private final Context mContext;
975
Amos Bianchia9b415a2020-03-04 11:07:38 -0800976 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800977
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800978 /**
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}
Paul Jensenbbb61092015-05-06 10:42:25 -0400982 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
983 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800984 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700985 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700986 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900987 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800988 }
989
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800990 /**
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.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900996 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800997 * {@hide}
998 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900999 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001000 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001001 public static String getNetworkTypeName(int type) {
1002 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +09001003 case TYPE_NONE:
1004 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -07001005 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";
repo syncf5de5572011-07-29 23:55:49 -07001031 case TYPE_WIFI_P2P:
1032 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -07001033 case TYPE_MOBILE_IA:
1034 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -07001035 case TYPE_MOBILE_EMERGENCY:
1036 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -05001037 case TYPE_PROXY:
1038 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +09001039 case TYPE_VPN:
1040 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -07001041 default:
1042 return Integer.toString(type);
1043 }
1044 }
1045
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001046 /**
Aaron Huang96011892020-06-27 07:18:23 +08001047 * @hide
Aaron Huang96011892020-06-27 07:18:23 +08001048 */
lucaslin7fc930b2021-03-17 14:16:01 +08001049 @SystemApi(client = MODULE_LIBRARIES)
Aaron Huang96011892020-06-27 07:18:23 +08001050 public void systemReady() {
1051 try {
1052 mService.systemReady();
1053 } catch (RemoteException e) {
1054 throw e.rethrowFromSystemServer();
1055 }
1056 }
1057
1058 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001059 * 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}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001063 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001064 * {@hide}
1065 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001066 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +09001067 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -07001068 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:
Wink Saville512c2202013-07-29 15:00:57 -07001078 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -07001079 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -07001080 return true;
1081 default:
1082 return false;
1083 }
1084 }
1085
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001086 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001087 * Checks if the given network type is backed by a Wi-Fi radio.
1088 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001089 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001090 * @hide
1091 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001092 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -07001093 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 Jeanfa45a682021-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 Jeanb43f3962021-03-17 14:33:24 +09001108 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-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 Jeanb43f3962021-03-17 14:33:24 +09001118 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-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 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001131 * Specifies the preferred network type. When the device has more
1132 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001133 *
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.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001137 * @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.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001141 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001142 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001143 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001144 }
1145
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001146 /**
1147 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001148 *
1149 * @return an integer representing the preferred network type
1150 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001151 * @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.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001155 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001156 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001157 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001158 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001159 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001160 }
1161
Scott Mainf58b7d82011-10-06 19:02:28 -07001162 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001163 * 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.
Chalard Jean96d10a72018-03-29 17:45:24 +09001168 * 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.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001172 *
1173 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001174 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001175 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001176 */
junyulai9826e7f2018-12-13 12:47:51 +08001177 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001178 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001179 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001180 public NetworkInfo getActiveNetworkInfo() {
1181 try {
1182 return mService.getActiveNetworkInfo();
1183 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001184 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001185 }
1186 }
1187
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001188 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001189 * 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
Paul Jensen1f567382015-02-13 14:18:39 -05001197 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001198 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001199 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001200 public Network getActiveNetwork() {
1201 try {
1202 return mService.getActiveNetwork();
1203 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001204 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001205 }
1206 }
1207
1208 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001209 * 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.
Robin Lee5b52bef2016-03-24 12:07:00 +00001214 *
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
lifr42a60c22021-03-11 20:11:09 +08001217 * TODO: b/183465229 Cleanup getActiveNetworkForUid once b/165835257 is fixed
Robin Lee5b52bef2016-03-24 12:07:00 +00001218 */
paulhu8e96a752019-08-12 16:25:11 +08001219 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001220 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001221 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001222 return getActiveNetworkForUid(uid, false);
1223 }
1224
1225 /** {@hide} */
1226 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001227 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001228 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001229 } catch (RemoteException e) {
1230 throw e.rethrowFromSystemServer();
1231 }
1232 }
1233
1234 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +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 *
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001258 * @hide
1259 */
1260 @RequiresPermission(anyOf = {
1261 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucasline257bce2021-03-22 11:51:27 +08001262 android.Manifest.permission.NETWORK_STACK,
1263 android.Manifest.permission.NETWORK_SETTINGS})
1264 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +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 Colittibcd692f2021-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 Colittibcd692f2021-01-15 01:29:01 +09001308 * @hide
1309 */
1310 @RequiresPermission(anyOf = {
1311 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucasline257bce2021-03-22 11:51:27 +08001312 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001313 android.Manifest.permission.NETWORK_SETTINGS})
lucasline257bce2021-03-22 11:51:27 +08001314 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittibcd692f2021-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 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001324 * 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 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001332 * {@hide}
1333 */
paulhu8e96a752019-08-12 16:25:11 +08001334 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001335 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001336 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001337 return getActiveNetworkInfoForUid(uid, false);
1338 }
1339
1340 /** {@hide} */
1341 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001342 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001343 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001344 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001345 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001346 }
1347 }
1348
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001349 /**
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
Chalard Jean96d10a72018-03-29 17:45:24 +09001357 * 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.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001362 *
Paul Jensendda8e592015-03-18 12:23:02 -04001363 * @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.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001366 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001367 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001368 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001369 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001370 public NetworkInfo getNetworkInfo(int networkType) {
1371 try {
1372 return mService.getNetworkInfo(networkType);
1373 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001374 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001375 }
1376 }
1377
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001378 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001379 * 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.
junyulai9826e7f2018-12-13 12:47:51 +08001387 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001388 */
junyulai9826e7f2018-12-13 12:47:51 +08001389 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001390 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001391 @Nullable
1392 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001393 return getNetworkInfoForUid(network, Process.myUid(), false);
1394 }
1395
1396 /** {@hide} */
1397 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001398 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001399 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001400 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001401 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001402 }
1403 }
1404
1405 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001406 * 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 *
Paul Jensendda8e592015-03-18 12:23:02 -04001412 * @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.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001415 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001416 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001417 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001418 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001419 public NetworkInfo[] getAllNetworkInfo() {
1420 try {
1421 return mService.getAllNetworkInfo();
1422 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001423 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001424 }
1425 }
1426
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001427 /**
junyulaiebd15162021-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
1438 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1439 try {
1440 return mService.getAllNetworkStateSnapshot();
1441 } catch (RemoteException e) {
1442 throw e.rethrowFromSystemServer();
1443 }
1444 }
1445
1446 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001447 * Returns the {@link Network} object currently serving a given type, or
1448 * null if the given type is not connected.
1449 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001450 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001451 * @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.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001454 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001455 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001456 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001457 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001458 public Network getNetworkForType(int networkType) {
1459 try {
1460 return mService.getNetworkForType(networkType);
1461 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001462 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001463 }
1464 }
1465
1466 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001467 * Returns an array of all {@link Network} currently tracked by the
1468 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001469 *
1470 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001471 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001472 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001473 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001474 public Network[] getAllNetworks() {
1475 try {
1476 return mService.getAllNetworks();
1477 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001478 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001479 }
1480 }
1481
1482 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001483 * Returns an array of {@link NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001484 * the Networks that applications run by the given user will use by default.
1485 * @hide
1486 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001487 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001488 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1489 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001490 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001491 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001492 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001493 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001494 }
1495 }
1496
1497 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001498 * 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 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001504 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001505 * @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.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001509 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001510 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001511 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001512 public LinkProperties getActiveLinkProperties() {
1513 try {
1514 return mService.getActiveLinkProperties();
1515 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001516 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001517 }
1518 }
1519
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001520 /**
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 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001528 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001529 * @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.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001533 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001534 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001535 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001536 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001537 public LinkProperties getLinkProperties(int networkType) {
1538 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001539 return mService.getLinkPropertiesForType(networkType);
1540 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001541 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001542 }
1543 }
1544
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001545 /**
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}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001551 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001552 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001553 @Nullable
1554 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001555 try {
1556 return mService.getLinkProperties(network);
1557 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001558 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001559 }
1560 }
1561
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001562 /**
Roshan Pius951c0032020-12-22 15:10:42 -08001563 * Get the {@link NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001564 * will return {@code null} if the network is unknown.
1565 *
Roshan Pius951c0032020-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 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001574 * @param network The {@link Network} object identifying the network in question.
Roshan Pius951c0032020-12-22 15:10:42 -08001575 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001576 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001577 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001578 @Nullable
1579 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001580 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001581 return mService.getNetworkCapabilities(
1582 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001583 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001584 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001585 }
1586 }
1587
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001588 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001589 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001590 * 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 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001595 * 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.
paulhu8e96a752019-08-12 16:25:11 +08001598 *
Udam Sainicd645462016-01-04 12:16:14 -08001599 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001600 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1601 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001602 */
paulhu8e96a752019-08-12 16:25:11 +08001603 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001604 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001605 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001606 public String getCaptivePortalServerUrl() {
1607 try {
1608 return mService.getCaptivePortalServerUrl();
1609 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001610 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001611 }
1612 }
1613
1614 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001615 * 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.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001618 *
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 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001624 * @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.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001630 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001631 * @deprecated Deprecated in favor of the cleaner
1632 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001633 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001634 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001635 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001636 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001637 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001638 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001639 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001640 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1641 if (netCap == null) {
1642 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1643 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001644 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001645 }
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) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001654 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001655 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001656 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001657 }
1658 }
1659
1660 request = requestNetworkForFeatureLocked(netCap);
1661 }
1662 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001663 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001664 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001665 } else {
1666 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001667 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001668 }
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.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001675 *
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 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001681 * @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.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001687 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001688 * @deprecated Deprecated in favor of the cleaner
1689 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001690 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001691 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001692 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001693 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001694 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001695 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001696 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001697 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1698 if (netCap == null) {
1699 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1700 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001701 return -1;
1702 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001703
Paul Jensen49f74a32014-12-17 10:39:34 -05001704 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001705 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001706 }
1707 return 1;
1708 }
1709
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001710 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001711 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1712 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001713 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;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001731 }
Erik Klinece55eb12017-01-26 18:08:28 +09001732 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1733 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001734 }
1735 return null;
1736 }
1737
Robert Greenwalt802c1102014-06-02 15:32:02 -07001738 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001739 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 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001761 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1762 return TYPE_WIFI_P2P;
1763 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001764 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;
Paul Jensen49f74a32014-12-17 10:39:34 -05001773
1774 private void clearDnsBinding() {
1775 if (currentNetwork != null) {
1776 currentNetwork = null;
1777 setProcessDefaultNetworkForHostResolution(null);
1778 }
1779 }
1780
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001781 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001782 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001783 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001784 currentNetwork = network;
1785 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001786 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001787 }
1788 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001789 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001790 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001791 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1792 }
1793 };
1794 }
1795
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001796 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001797 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1798 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001799
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;
Paul Jensen49f74a32014-12-17 10:39:34 -05001820 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001821 }
1822 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1823 }
1824
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001825 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001826 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1827 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001828 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001829 try {
1830 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001831 } catch (RemoteException e) {
1832 throw e.rethrowFromSystemServer();
1833 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001834 LegacyRequest l = new LegacyRequest();
1835 l.networkCapabilities = netCap;
1836 l.delay = delay;
1837 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001838 l.networkRequest = sendRequestForNetwork(
1839 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001840 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);
Hugo Benichifd44e912017-02-02 17:02:36 +09001849 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001850 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1851 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001852 }
1853 }
1854
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001855 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001856 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1857 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001858 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001859 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001860 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001861 if (l == null) return false;
1862 unregisterNetworkCallback(l.networkCallback);
1863 l.clearDnsBinding();
1864 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001865 }
1866
Erik Klinece55eb12017-01-26 18:08:28 +09001867 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 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001900 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1901 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001902 * @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 VAN81f68422021-03-15 07:31:54 +00001910 if (transport == NOT_FOUND) {
1911 throw new IllegalArgumentException("unknown legacy type: " + type);
1912 }
Erik Klinece55eb12017-01-26 18:08:28 +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
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001922 /** @hide */
1923 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001924 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001925 public PacketKeepaliveCallback() {
1926 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001927 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001928 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001929 public void onStarted() {}
1930 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001931 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001932 public void onStopped() {}
1933 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001934 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001935 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 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001948 * 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.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001951 *
junyulai4c95b082018-12-27 17:25:29 +08001952 * @deprecated Use {@link SocketKeepalive} instead.
1953 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001954 * @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;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001983 /** The hardware returned an error. */
1984 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001985
Nathan Harold0990bc82018-02-14 13:09:45 -08001986 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001987 public static final int NATT_PORT = 4500;
1988
Nathan Harold0990bc82018-02-14 13:09:45 -08001989 /** The minimum interval in seconds between keepalive packet transmissions */
1990 public static final int MIN_INTERVAL = 10;
1991
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001992 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001993 private final ISocketKeepaliveCallback mCallback;
1994 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001995
1996 private volatile Integer mSlot;
1997
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001998 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001999 public void stop() {
2000 try {
junyulai070f9ff2019-01-16 20:23:34 +08002001 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.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002013 }
2014 }
2015
2016 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002017 Objects.requireNonNull(network, "network cannot be null");
2018 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002019 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08002020 mExecutor = Executors.newSingleThreadExecutor();
2021 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002022 @Override
junyulai070f9ff2019-01-16 20:23:34 +08002023 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08002024 final long token = Binder.clearCallingIdentity();
2025 try {
2026 mExecutor.execute(() -> {
2027 mSlot = slot;
2028 callback.onStarted();
2029 });
2030 } finally {
2031 Binder.restoreCallingIdentity(token);
2032 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002033 }
junyulai070f9ff2019-01-16 20:23:34 +08002034
2035 @Override
2036 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08002037 final long token = Binder.clearCallingIdentity();
2038 try {
2039 mExecutor.execute(() -> {
2040 mSlot = null;
2041 callback.onStopped();
2042 });
2043 } finally {
2044 Binder.restoreCallingIdentity(token);
2045 }
junyulai070f9ff2019-01-16 20:23:34 +08002046 mExecutor.shutdown();
2047 }
2048
2049 @Override
2050 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08002051 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 }
junyulai070f9ff2019-01-16 20:23:34 +08002060 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 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002069 }
2070 }
2071
2072 /**
2073 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2074 *
junyulai4c95b082018-12-27 17:25:29 +08002075 * @deprecated Use {@link #createSocketKeepalive} instead.
2076 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002077 * @hide
2078 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002079 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002080 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 {
junyulai070f9ff2019-01-16 20:23:34 +08002085 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002086 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2087 } catch (RemoteException e) {
2088 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08002089 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002090 }
2091 return k;
2092 }
2093
Chiachang Wang619319a2021-01-15 11:06:21 +08002094 // Construct an invalid fd.
2095 private ParcelFileDescriptor createInvalidFd() {
2096 final int invalidFd = -1;
2097 return ParcelFileDescriptor.adoptFd(invalidFd);
2098 }
2099
The Android Open Source Project28527d22009-03-03 19:31:44 -08002100 /**
junyulai4c95b082018-12-27 17:25:29 +08002101 * 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 *
junyulai0835a1e2019-01-08 20:04:33 +08002113 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2114 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08002115 **/
junyulai7e06ad42019-03-04 22:45:36 +08002116 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08002117 @NonNull UdpEncapsulationSocket socket,
2118 @NonNull InetAddress source,
2119 @NonNull InetAddress destination,
2120 @NonNull @CallbackExecutor Executor executor,
2121 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002122 ParcelFileDescriptor dup;
2123 try {
junyulai828dad12019-03-27 11:00:37 +08002124 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2125 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08002126 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.
Chiachang Wang619319a2021-01-15 11:06:21 +08002130 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002131 }
2132 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2133 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002134 }
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.
junyulai7e06ad42019-03-04 22:45:36 +08002141 * @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.
junyulaid05a1922019-01-15 11:32:44 +08002144 * @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 *
junyulai0835a1e2019-01-08 20:04:33 +08002153 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2154 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002155 * @hide
2156 */
2157 @SystemApi
2158 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002159 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2160 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002161 @NonNull InetAddress source,
2162 @NonNull InetAddress destination,
2163 @NonNull @CallbackExecutor Executor executor,
2164 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002165 ParcelFileDescriptor dup;
2166 try {
junyulai828dad12019-03-27 11:00:37 +08002167 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002168 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.
Chiachang Wang619319a2021-01-15 11:06:21 +08002172 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002173 }
2174 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANce355502021-03-11 10:56:49 +00002175 -1 /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002176 }
2177
2178 /**
junyulai0835a1e2019-01-08 20:04:33 +08002179 * 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)
junyulai7e06ad42019-03-04 22:45:36 +08002199 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002200 @NonNull Socket socket,
2201 @NonNull Executor executor,
2202 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002203 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.
Chiachang Wang619319a2021-01-15 11:06:21 +08002209 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002210 }
2211 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002212 }
2213
2214 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002215 * 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.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002218 *
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 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002224 * @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
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002228 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002229 * @deprecated Deprecated in favor of the
2230 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2231 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002232 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002233 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002234 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002235 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002236 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002237 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002238 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002239 }
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.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002245 *
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 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002251 * @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
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002256 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002257 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002258 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002259 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002260 @UnsupportedAppUsage
lucasline257bce2021-03-22 11:51:27 +08002261 @SystemApi(client = MODULE_LIBRARIES)
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002262 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002263 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002264 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002265 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2266 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002267 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002268 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002269 }
2270 }
2271
2272 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002273 * @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 Piusaa24fde2020-12-17 14:53:09 -08002277 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002278 }
2279
2280 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002281 * 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}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002288 * <p>
Scott Main50589142011-10-06 18:32:43 -07002289 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002290 * 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.
Danica Chang96567052010-08-11 14:54:43 -07002293 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002294 * @return Whether background data usage is allowed.
2295 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002296 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002297 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002298 // assume that background data is allowed; final authority is
2299 // NetworkInfo which may be blocked.
2300 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002301 }
2302
2303 /**
2304 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002305 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002306 * @param allowBackgroundData Whether an application should use data while
2307 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002308 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002309 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2310 * @see #getBackgroundDataSetting()
2311 * @hide
2312 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002313 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002314 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002315 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002316 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002317 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002318
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002319 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002320 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002321 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002322 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002323 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002324 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002325 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002326 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;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002334 }
Wink Saville689f7042014-12-05 11:10:30 -08002335 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002336 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002337 }
2338
The Android Open Source Project28527d22009-03-03 19:31:44 -08002339 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002340 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002341 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002342 */
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
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002350 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002351 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002352 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002353 }
2354
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002355 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002356 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002357
2358 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002359 * 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
Paul Jensenee2f45d2015-03-10 10:54:12 -04002365 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002366 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002367 *
2368 * @param l The listener to be told when the network is active.
2369 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002370 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002371 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2372 @Override
2373 public void onNetworkActive() throws RemoteException {
2374 l.onNetworkActive();
2375 }
2376 };
2377
2378 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002379 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002380 mNetworkActivityListeners.put(l, rl);
2381 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002382 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002383 }
2384 }
2385
2386 /**
2387 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002388 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002389 *
2390 * @param l Previously registered listener.
2391 */
Chalard Jean158702d2019-01-07 19:26:34 +09002392 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002393 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002394 if (rl == null) {
2395 throw new IllegalArgumentException("Listener was not registered.");
2396 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002397 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002398 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002399 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002400 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002401 }
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 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002412 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002413 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002414 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002415 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002416 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002417 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002418 }
2419
2420 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002421 * {@hide}
2422 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002423 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002424 mContext = Objects.requireNonNull(context, "missing context");
2425 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002426 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002427 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002428 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002429
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002430 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002431 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002432 public static ConnectivityManager from(Context context) {
2433 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2434 }
2435
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002436 /** @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
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002446 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002447 * 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 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002461 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2462 * situations where a Context pointer is unavailable.
2463 * @hide
2464 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002465 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002466 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 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002475 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002476 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002477 private static ConnectivityManager getInstance() {
2478 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002479 throw new IllegalStateException("No ConnectivityManager yet constructed");
2480 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002481 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002482 }
2483
2484 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002485 * 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 *
markchien6ae63e52020-01-21 13:11:06 +08002490 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002491 * {@hide}
2492 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002493 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002494 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002495 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002496 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002497 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002498 }
2499
2500 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002501 * Get the set of tethered interfaces.
2502 *
2503 * @return an array of 0 or more String of currently tethered interface names.
2504 *
markchien6ae63e52020-01-21 13:11:06 +08002505 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002506 * {@hide}
2507 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002508 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002509 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002510 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002511 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002512 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002513 }
2514
2515 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002516 * 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 *
markchien6ae63e52020-01-21 13:11:06 +08002526 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002527 * {@hide}
2528 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002529 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002530 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002531 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002532 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002533 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002534 }
2535
2536 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002537 * Get the set of tethered dhcp ranges.
2538 *
markchien2e6ba522020-02-14 11:55:48 +08002539 * @deprecated This method is not supported.
2540 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002541 * {@hide}
2542 */
paulhu8e96a752019-08-12 16:25:11 +08002543 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002544 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002545 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002546 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002547 }
2548
2549 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002550 * 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.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002557 *
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>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002562 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002563 * <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 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002568 * @param iface the interface name to tether.
2569 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002570 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002571 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002572 * {@hide}
2573 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002574 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002575 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002576 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002577 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002578 }
2579
2580 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002581 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002582 *
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>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002587 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002588 * <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 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002593 * @param iface the interface name to untether.
2594 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2595 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002596 * {@hide}
2597 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002598 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002599 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002600 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002601 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002602 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002603
2604 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002605 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002606 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002607 * due to device configuration.
2608 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002609 * <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 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002618 * @return a boolean - {@code true} indicating Tethering is supported.
2619 *
markchien6ae63e52020-01-21 13:11:06 +08002620 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002621 * {@hide}
2622 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002623 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002624 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2625 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002626 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002627 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002628 }
2629
2630 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002631 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002632 *
2633 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002634 * @hide
2635 */
2636 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002637 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002638 public static abstract class OnStartTetheringCallback {
2639 /**
2640 * Called when tethering has been successfully started.
2641 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002642 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002643
2644 /**
2645 * Called when starting tethering failed.
2646 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002647 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002648 }
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}.
markchien91c78e52020-01-20 19:31:56 +08002654 *
2655 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002656 * @hide
2657 */
2658 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002659 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002660 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002661 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.
markchien91c78e52020-01-20 19:31:56 +08002683 *
2684 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002685 * @hide
2686 */
2687 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002688 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002689 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002690 public void startTethering(int type, boolean showProvisioningUi,
2691 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002692 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002693
markchien91c78e52020-01-20 19:31:56 +08002694 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002695 @Override
markchien91c78e52020-01-20 19:31:56 +08002696 public void execute(Runnable command) {
2697 if (handler == null) {
2698 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002699 } else {
markchien91c78e52020-01-20 19:31:56 +08002700 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002701 }
2702 }
2703 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002704
markchien91c78e52020-01-20 19:31:56 +08002705 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2706 @Override
2707 public void onTetheringStarted() {
2708 callback.onTetheringStarted();
2709 }
2710
2711 @Override
markchienf47d8342020-03-19 13:37:43 +08002712 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002713 callback.onTetheringFailed();
2714 }
2715 };
2716
2717 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002718 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002719
Amos Bianchia9b415a2020-03-04 11:07:38 -08002720 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002721 }
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}.
markchien6ae63e52020-01-21 13:11:06 +08002731 *
2732 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002733 * @hide
2734 */
2735 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002736 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002737 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002738 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002739 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002740 }
2741
2742 /**
markchien4ef53e82019-02-27 14:56:11 +08002743 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2744 * upstream status.
2745 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002746 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002747 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002748 */
2749 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002750 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002751 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
markchien6ae63e52020-01-21 13:11:06 +08002763 @GuardedBy("mTetheringEventCallbacks")
2764 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2765 mTetheringEventCallbacks = new ArrayMap<>();
2766
markchien4ef53e82019-02-27 14:56:11 +08002767 /**
2768 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002769 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002770 * 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.
markchien6ae63e52020-01-21 13:11:06 +08002775 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002776 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002777 * @hide
2778 */
2779 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002780 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002781 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2782 public void registerTetheringEventCallback(
2783 @NonNull @CallbackExecutor Executor executor,
2784 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00002785 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchien4ef53e82019-02-27 14:56:11 +08002786
markchien6ae63e52020-01-21 13:11:06 +08002787 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);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002797 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002798 }
markchien4ef53e82019-02-27 14:56:11 +08002799 }
2800
2801 /**
2802 * Remove tethering event callback previously registered with
2803 * {@link #registerTetheringEventCallback}.
2804 *
2805 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002806 *
2807 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002808 * @hide
2809 */
2810 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002811 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002812 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2813 public void unregisterTetheringEventCallback(
2814 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002815 Objects.requireNonNull(callback, "The callback must be non-null");
2816 synchronized (mTetheringEventCallbacks) {
2817 final TetheringEventCallback tetherCallback =
2818 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002819 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002820 }
markchien4ef53e82019-02-27 14:56:11 +08002821 }
2822
2823
2824 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002825 * 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 *
markchien6ae63e52020-01-21 13:11:06 +08002832 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002833 * {@hide}
2834 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002835 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002836 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002837 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002838 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002839 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002840 }
2841
2842 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002843 * 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 *
markchien6ae63e52020-01-21 13:11:06 +08002850 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002851 * {@hide}
2852 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002853 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002854 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002855 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002856 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002857 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002858 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002859
Danica Chang96567052010-08-11 14:54:43 -07002860 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002861 * 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 *
markchien6ae63e52020-01-21 13:11:06 +08002868 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2869 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002870 * {@hide}
2871 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002872 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002873 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002874 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002875 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002876 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002877 }
2878
Mike Lockwooded4a1742011-07-19 13:04:47 -07002879 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002880 * 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}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002885 *
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>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002890 *
2891 * @param enable a boolean - {@code true} to enable tethering
2892 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002893 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002894 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002895 * {@hide}
2896 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002897 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002898 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002899 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002900 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002901 }
2902
markchien6ae63e52020-01-21 13:11:06 +08002903 /**
2904 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2905 * {@hide}
2906 */
markchien0f45bb92019-01-16 17:44:13 +08002907 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002908 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002909 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002910 /**
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 /**
markchienf47d8342020-03-19 13:37:43 +08002938 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002939 * {@hide}
2940 */
2941 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002942 public static final int TETHER_ERROR_MASTER_ERROR =
2943 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002944 /**
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 /**
markchienf47d8342020-03-19 13:37:43 +08002959 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002960 * {@hide}
2961 */
2962 @Deprecated
2963 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002964 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002965 /**
markchienf47d8342020-03-19 13:37:43 +08002966 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002967 * {@hide}
2968 */
2969 @Deprecated
2970 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002971 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002972 /**
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 /**
markchienf47d8342020-03-19 13:37:43 +08002980 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002981 * {@hide}
2982 */
markchien0f45bb92019-01-16 17:44:13 +08002983 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002984 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002985 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002986 /**
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 */
markchien0f45bb92019-01-16 17:44:13 +08002997 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002998 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002999 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003000
3001 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003002 * 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
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003006 * @return error The error code of the last error tethering or untethering the named
3007 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003008 *
markchien6ae63e52020-01-21 13:11:06 +08003009 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003010 * {@hide}
3011 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003012 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00003013 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08003014 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003015 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08003016 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;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003024 }
3025
markchienbf5ab012019-03-06 16:25:00 +08003026 /** @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
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003036 /**
markchienbf5ab012019-03-06 16:25:00 +08003037 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08003038 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08003039 *
3040 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08003041 * @hide
3042 */
3043 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08003044 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08003045 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 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07003054 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08003055 }
3056
3057 /**
markchien0f45bb92019-01-16 17:44:13 +08003058 * 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.
markchienbf5ab012019-03-06 16:25:00 +08003070 * @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.
markchien6ae63e52020-01-21 13:11:06 +08003074 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08003075 * {@hide}
3076 */
3077 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08003078 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08003079 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08003080 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3081 @NonNull @CallbackExecutor Executor executor,
3082 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003083 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchienbf5ab012019-03-06 16:25:00 +08003084 ResultReceiver wrappedListener = new ResultReceiver(null) {
3085 @Override
3086 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-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 }
markchienbf5ab012019-03-06 16:25:00 +08003095 }
3096 };
3097
Amos Bianchia9b415a2020-03-04 11:07:38 -08003098 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08003099 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08003100 }
3101
3102 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003103 * Report network connectivity status. This is currently used only
3104 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003105 * <p>This method requires the caller to hold the permission
3106 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003107 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003108 * @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
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003110 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003111 * {@hide}
3112 */
3113 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003114 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003115 try {
3116 mService.reportInetCondition(networkType, percentage);
3117 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003118 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003119 }
3120 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003121
3122 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003123 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003124 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003125 * the framework to re-evaluate network connectivity and/or switch to another
3126 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003127 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003128 * @param network The {@link Network} the application was attempting to use
3129 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003130 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3131 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003132 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003133 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003134 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003135 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003136 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003137 // 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) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003142 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003143 }
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 */
Chalard Jean158702d2019-01-07 19:26:34 +09003157 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003158 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003159 try {
3160 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003161 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003162 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003163 }
3164 }
3165
3166 /**
Chalard Jean48d60ea2021-03-17 17:03:34 +09003167 * Set a network-independent global HTTP proxy.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003168 *
Chalard Jean48d60ea2021-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.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003182 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003183 */
Chalard Jean48d60ea2021-03-17 17:03:34 +09003184 // Used by Device Policy Manager to set the global proxy.
Chiachang Wang4d513572021-03-18 09:44:34 +08003185 @SystemApi(client = MODULE_LIBRARIES)
paulhu8e96a752019-08-12 16:25:11 +08003186 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean48d60ea2021-03-17 17:03:34 +09003187 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003188 try {
3189 mService.setGlobalProxy(p);
3190 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003191 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003192 }
3193 }
3194
3195 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003196 * Retrieve any network-independent global HTTP proxy.
3197 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003198 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003199 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003200 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003201 */
Chiachang Wang4d513572021-03-18 09:44:34 +08003202 @SystemApi(client = MODULE_LIBRARIES)
3203 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04003204 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003205 try {
3206 return mService.getGlobalProxy();
3207 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003208 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003209 }
3210 }
3211
3212 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003213 * 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) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003230 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003231 }
3232 }
3233
3234 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003235 * 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
Paul Jensenee2f45d2015-03-10 10:54:12 -04003237 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003238 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003239 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003240 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003241 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003242 */
Chalard Jean158702d2019-01-07 19:26:34 +09003243 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003244 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003245 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003246 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003247
3248 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003249 * 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
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003252 * 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}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003258 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003259 * @hide
3260 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003261 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003262 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003263 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003264 public boolean isNetworkSupported(int networkType) {
3265 try {
3266 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003267 } catch (RemoteException e) {
3268 throw e.rethrowFromSystemServer();
3269 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003270 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003271
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
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003275 * 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}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003282 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003283 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003284 public boolean isActiveNetworkMetered() {
3285 try {
3286 return mService.isActiveNetworkMetered();
3287 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003288 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003289 }
3290 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003291
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003292 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003293 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003294 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003295 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003296 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003297 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003298 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003299 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003300 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003301 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003302 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003303 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003304 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003305 }
3306 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003307
3308 /**
3309 * Set the value for enabling/disabling airplane mode
3310 *
3311 * @param enable whether to enable airplane mode or not
3312 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003313 * @hide
3314 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003315 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003316 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003317 android.Manifest.permission.NETWORK_SETTINGS,
3318 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3319 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003320 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003321 public void setAirplaneMode(boolean enable) {
3322 try {
3323 mService.setAirplaneMode(enable);
3324 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003325 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003326 }
3327 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003328
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +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
paulhub6ba8e82020-03-04 09:43:41 +08003340 @RequiresPermission(anyOf = {
3341 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3342 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003343 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3344 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003345 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
paulhub6ba8e82020-03-04 09:43:41 +08003365 @RequiresPermission(anyOf = {
3366 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3367 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003368 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. */
paulhub6ba8e82020-03-04 09:43:41 +08003379 @RequiresPermission(anyOf = {
3380 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3381 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003382 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3383 try {
3384 mService.declareNetworkRequestUnfulfillable(request);
3385 } catch (RemoteException e) {
3386 throw e.rethrowFromSystemServer();
3387 }
3388 }
3389
Paul Jensen1f567382015-02-13 14:18:39 -05003390 /**
3391 * @hide
3392 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003393 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003394 */
paulhub6ba8e82020-03-04 09:43:41 +08003395 @RequiresPermission(anyOf = {
3396 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3397 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003398 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Chalard Jean28018572020-12-21 18:36:52 +09003399 NetworkCapabilities nc, @NonNull NetworkScore score, NetworkAgentConfig config,
3400 int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003401 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003402 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003403 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003404 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003405 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003406 }
3407
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003408 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003409 * 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)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003415 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003416 * 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.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003419 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003420 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003421 /**
Roshan Pius951c0032020-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 Piuse1220262021-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 Pius951c0032020-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 VAN81f68422021-03-15 07:31:54 +00003467 if ((flags & VALID_FLAGS) != flags) {
3468 throw new IllegalArgumentException("Invalid flags");
3469 }
Roshan Pius951c0032020-12-22 15:10:42 -08003470 mFlags = flags;
3471 }
3472
3473 /**
Lorenzo Colitti14574592015-04-24 12:23: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.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003485 *
3486 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003487 */
paulhu1a407652019-03-22 16:35:06 +08003488 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003489
3490 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003491 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003492 * This callback may be called more than once if the {@link Network} that is
3493 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003494 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003495 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003496 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3497 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003498 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003499 * @hide
3500 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003501 public final void onAvailable(@NonNull Network network,
paulhu1a407652019-03-22 16:35:06 +08003502 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003503 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +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 Colitti79c6f222021-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) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +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 Colitti79c6f222021-03-18 00:54:57 +09003532 // No call to onBlockedStatusChanged here. That is done by the caller.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003533 }
3534
3535 /**
3536 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003537 *
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.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003561 *
3562 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003563 */
paulhu1a407652019-03-22 16:35:06 +08003564 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003565
3566 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003567 * 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.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003572 *
Chalard Jean01378b62019-08-30 16:27:28 +09003573 * <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.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003582 */
paulhu1a407652019-03-22 16:35:06 +08003583 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003584
3585 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003586 * 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.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003601 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003602 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003603 */
paulhu1a407652019-03-22 16:35:06 +08003604 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003605
3606 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003607 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003608 * {@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
Etan Cohenf67bde92017-03-01 12:47:28 -08003611 * {@link NetworkRequest} will have already been removed and released, as if
3612 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003613 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003614 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003615
3616 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003617 * 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.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003626 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003627 * @param network The {@link Network} whose capabilities have changed.
Roshan Pius951c0032020-12-22 15:10:42 -08003628 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003629 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003630 */
paulhu1a407652019-03-22 16:35:06 +08003631 public void onCapabilitiesChanged(@NonNull Network network,
3632 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003633
3634 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003635 * 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.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003643 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003644 * @param network The {@link Network} whose link properties have changed.
3645 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003646 */
paulhu1a407652019-03-22 16:35:06 +08003647 public void onLinkPropertiesChanged(@NonNull Network network,
3648 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003649
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003650 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003651 * 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 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003665 * @hide
3666 */
paulhu1a407652019-03-22 16:35:06 +08003667 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003668
3669 /**
3670 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003671 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3672 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003673
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 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003679 * @hide
3680 */
paulhu1a407652019-03-22 16:35:06 +08003681 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003682
junyulaif2c67e42018-08-07 19:50:45 +08003683 /**
3684 * Called when access to the specified network is blocked or unblocked.
3685 *
Chalard Jean01378b62019-08-30 16:27:28 +09003686 * <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 *
junyulaif2c67e42018-08-07 19:50:45 +08003691 * @param network The {@link Network} whose blocked status has changed.
3692 * @param blocked The blocked status of this {@link Network}.
3693 */
junyulai7e06ad42019-03-04 22:45:36 +08003694 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003695
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003696 /**
Lorenzo Colitti42fe2232021-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 Colitti79c6f222021-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
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003717 private NetworkRequest networkRequest;
Roshan Pius951c0032020-12-22 15:10:42 -08003718 private final int mFlags;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003719 }
3720
Hugo Benichia590ab82017-05-11 13:16:17 +09003721 /**
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 {
Chalard Jean9dd11612018-06-04 16:52:49 +09003727 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003728 }
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
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003743 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003744 public static final int CALLBACK_PRECHECK = 1;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003745 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003746 public static final int CALLBACK_AVAILABLE = 2;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003747 /** @hide arg1 = TTL */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003748 public static final int CALLBACK_LOSING = 3;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003749 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003750 public static final int CALLBACK_LOST = 4;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003751 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003752 public static final int CALLBACK_UNAVAIL = 5;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003753 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003754 public static final int CALLBACK_CAP_CHANGED = 6;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003755 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003756 public static final int CALLBACK_IP_CHANGED = 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003757 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003758 private static final int EXPIRE_LEGACY_REQUEST = 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003759 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003760 public static final int CALLBACK_SUSPENDED = 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003761 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003762 public static final int CALLBACK_RESUMED = 10;
junyulaif2c67e42018-08-07 19:50:45 +08003763 /** @hide */
Remi NGUYEN VAN1fb66ad2021-03-12 15:24:06 +09003764 public static final int CALLBACK_BLK_CHANGED = 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003765
Erik Kline155a59a2015-11-25 12:49:38 +09003766 /** @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";
Erik Kline155a59a2015-11-25 12:49:38 +09003776 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3777 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3778 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003779 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003780 default:
3781 return Integer.toString(whichCallback);
3782 }
3783 }
3784
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003785 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003786 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003787 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003788
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003789 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003790 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003791 }
3792
Hugo Benichifd44e912017-02-02 17:02:36 +09003793 CallbackHandler(Handler handler) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003794 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003795 }
3796
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003797 @Override
3798 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003799 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);
Etan Cohenb58e3662019-05-21 12:06:04 -07003809 if (callback == null) {
3810 Log.w(TAG,
3811 "callback not found for " + getCallbackName(message.what) + " message");
3812 return;
3813 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003814 if (message.what == CALLBACK_UNAVAIL) {
3815 sCallbacks.remove(request);
3816 callback.networkRequest = ALREADY_UNREGISTERED;
3817 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003818 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003819 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003820 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003821 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003822
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003823 switch (message.what) {
3824 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003825 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003826 break;
3827 }
3828 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003829 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3830 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003831 callback.onAvailable(network, cap, lp, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003832 break;
3833 }
3834 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003835 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003836 break;
3837 }
3838 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003839 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003840 break;
3841 }
3842 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003843 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003844 break;
3845 }
3846 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003847 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3848 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003849 break;
3850 }
3851 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003852 LinkProperties lp = getObject(message, LinkProperties.class);
3853 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003854 break;
3855 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003856 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003857 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003858 break;
3859 }
3860 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003861 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003862 break;
3863 }
junyulaif2c67e42018-08-07 19:50:45 +08003864 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003865 callback.onBlockedStatusChanged(network, message.arg1);
junyulaif2c67e42018-08-07 19:50:45 +08003866 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003867 }
3868 }
3869
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003870 private <T> T getObject(Message msg, Class<T> c) {
3871 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003872 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003873 }
3874
Hugo Benichifd44e912017-02-02 17:02:36 +09003875 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003876 synchronized (sCallbacks) {
3877 if (sCallbackHandler == null) {
3878 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003879 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003880 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003881 }
3882 }
3883
Hugo Benichibc4ac972017-02-03 14:18:44 +09003884 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3885 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003886
Lorenzo Colitti2a49c5d2021-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) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003890 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003891 checkCallbackNotNull(callback);
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00003892 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3893 throw new IllegalArgumentException("null NetworkCapabilities");
3894 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003895 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003896 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003897 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003898 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003899 if (callback.networkRequest != null
3900 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003901 // 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 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003905 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003906 Binder binder = new Binder();
Roshan Pius951c0032020-12-22 15:10:42 -08003907 final int callbackFlags = callback.mFlags;
junyulaiad010792021-01-11 16:53:38 +08003908 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003909 request = mService.listenForNetwork(
Roshan Pius951c0032020-12-22 15:10:42 -08003910 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003911 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003912 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003913 request = mService.requestNetwork(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09003914 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
3915 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003916 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003917 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003918 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003919 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003920 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003921 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003922 } catch (RemoteException e) {
3923 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003924 } catch (ServiceSpecificException e) {
3925 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003926 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003927 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003928 }
3929
Lorenzo Colitti2a49c5d2021-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
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003936 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003937 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003938 *
markchienfac84a22020-03-18 21:16:15 +08003939 * 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
markchiend6eeffd2020-01-14 00:55:21 +08003941 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003942 *
markchiend6eeffd2020-01-14 00:55:21 +08003943 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003944 * @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.
markchienfac84a22020-03-18 21:16:15 +08003949 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3950 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003951 *
3952 * @hide
3953 */
markchiend6eeffd2020-01-14 00:55:21 +08003954 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003955 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003956 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003957 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 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003962 CallbackHandler cbHandler = new CallbackHandler(handler);
3963 NetworkCapabilities nc = request.networkCapabilities;
3964 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003965 }
3966
3967 /**
Roshan Pius951c0032020-12-22 15:10:42 -08003968 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003969 *
Chalard Jean01378b62019-08-30 16:27:28 +09003970 * <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 *
Paul Jensenee52d232015-06-16 15:11:58 -04004015 * <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
Chalard Jean01378b62019-08-30 16:27:28 +09004022 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004023 *
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>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004028 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004029 * <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 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004038 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09004039 * @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.
Chalard Jean31740e42019-05-13 15:13:58 +09004042 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4043 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004044 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004045 */
Chalard Jean158702d2019-01-07 19:26:34 +09004046 public void requestNetwork(@NonNull NetworkRequest request,
4047 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004048 requestNetwork(request, networkCallback, getDefaultHandler());
4049 }
4050
4051 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004052 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Hugo Benichifd44e912017-02-02 17:02:36 +09004053 *
Chalard Jean01378b62019-08-30 16:27:28 +09004054 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4055 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09004056 *
Chalard Jean01378b62019-08-30 16:27:28 +09004057 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004058 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4059 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09004060 *
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.
Hugo Benichifd44e912017-02-02 17:02:36 +09004065 */
Chalard Jean158702d2019-01-07 19:26:34 +09004066 public void requestNetwork(@NonNull NetworkRequest request,
4067 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004068 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08004069 NetworkCapabilities nc = request.networkCapabilities;
4070 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004071 }
4072
4073 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004074 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Etan Cohenf67bde92017-03-01 12:47:28 -08004075 * 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 *
Chalard Jean01378b62019-08-30 16:27:28 +09004089 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004090 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4091 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08004092 *
4093 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004094 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4095 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08004096 * @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).
Etan Cohenf67bde92017-03-01 12:47:28 -08004099 */
Chalard Jean158702d2019-01-07 19:26:34 +09004100 public void requestNetwork(@NonNull NetworkRequest request,
4101 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09004102 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08004103 NetworkCapabilities nc = request.networkCapabilities;
4104 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4105 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09004106 }
4107
Hugo Benichifd44e912017-02-02 17:02:36 +09004108 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004109 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Hugo Benichifd44e912017-02-02 17:02:36 +09004110 * by a timeout.
4111 *
Chalard Jean01378b62019-08-30 16:27:28 +09004112 * This method behaves identically to
4113 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4114 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08004115 *
Chalard Jean01378b62019-08-30 16:27:28 +09004116 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09004117 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4118 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09004119 *
4120 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08004121 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4122 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09004123 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004124 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4125 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004126 */
Chalard Jean158702d2019-01-07 19:26:34 +09004127 public void requestNetwork(@NonNull NetworkRequest request,
4128 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09004129 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09004130 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08004131 NetworkCapabilities nc = request.networkCapabilities;
4132 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004133 }
4134
4135 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004136 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004137 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004138 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08004139 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04004140 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4141 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004142 */
Erik Kline8a826212014-11-19 12:12:24 +09004143 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004144
4145 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004146 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004147 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004148 * {@link android.content.Intent#getParcelableExtra(String)}.
4149 */
Erik Kline8a826212014-11-19 12:12:24 +09004150 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004151
4152
4153 /**
Roshan Pius951c0032020-12-22 15:10:42 -08004154 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004155 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004156 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004157 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004158 * the request may outlive the calling application and get called back when a suitable
4159 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004160 * <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
Erik Kline8a826212014-11-19 12:12:24 +09004166 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4167 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004168 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004169 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004170 * Intent to reserve the network or it will be released shortly after the Intent
4171 * is processed.
4172 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04004173 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004174 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07004175 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004176 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004177 * The request may be released normally by calling
4178 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04004179 * <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
Chalard Jean9dd11612018-06-04 16:52:49 +09004185 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004186 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004187 * <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 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004196 * <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 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004201 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004202 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004203 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004204 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004205 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4206 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004207 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004208 */
Chalard Jean158702d2019-01-07 19:26:34 +09004209 public void requestNetwork(@NonNull NetworkRequest request,
4210 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004211 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004212 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004213 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004214 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004215 request.networkCapabilities, operation, mContext.getOpPackageName(),
4216 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004217 } catch (RemoteException e) {
4218 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004219 } catch (ServiceSpecificException e) {
4220 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004221 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004222 }
4223
4224 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004225 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4226 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004227 * This method has the same behavior as
4228 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004229 * 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 */
Chalard Jean158702d2019-01-07 19:26:34 +09004236 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004237 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004238 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004239 try {
4240 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004241 } catch (RemoteException e) {
4242 throw e.rethrowFromSystemServer();
4243 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004244 }
4245
Hugo Benichibc1104b2017-05-09 15:19:01 +09004246 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004247 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004248 }
4249
4250 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004251 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichibc1104b2017-05-09 15:19:01 +09004252 }
4253
4254 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN81f68422021-03-15 07:31:54 +00004255 if (timeoutMs <= 0) {
4256 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4257 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004258 }
4259
4260 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004261 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004262 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004263 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4264 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004265 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004266 * <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 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004275 * @param request {@link NetworkRequest} describing this request.
4276 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4277 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004278 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004279 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004280 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004281 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004282 public void registerNetworkCallback(@NonNull NetworkRequest request,
4283 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004284 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
Chiachang Wang3b723c22019-02-27 17:14:50 +08004290 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4291 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004292 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004293 * <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 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004303 * @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.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004307 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004308 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004309 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004310 public void registerNetworkCallback(@NonNull NetworkRequest request,
4311 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004312 CallbackHandler cbHandler = new CallbackHandler(handler);
4313 NetworkCapabilities nc = request.networkCapabilities;
4314 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004315 }
4316
4317 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004318 * 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
Paul Jensen169f6622015-06-30 14:29:18 -04004340 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004341 *
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 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004351 * @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.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004355 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004356 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004357 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004358 public void registerNetworkCallback(@NonNull NetworkRequest request,
4359 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004360 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004361 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004362 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004363 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004364 request.networkCapabilities, operation, mContext.getOpPackageName(),
4365 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004366 } catch (RemoteException e) {
4367 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004368 } catch (ServiceSpecificException e) {
4369 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004370 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004371 }
4372
4373 /**
Lorenzo Colitti76b639e2021-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
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004377 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004378 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004379 * <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 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004388 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004389 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004390 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004391 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004392 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004393 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004394 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004395 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4396 }
4397
4398 /**
Lorenzo Colitti76b639e2021-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 Colitti2a49c5d2021-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 Colitti92ed8b92021-03-22 18:23:21 +09004446 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti2a49c5d2021-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 Colitti76b639e2021-01-29 20:14:04 +09004453 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09004454 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004455 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4456 }
4457
4458 /**
Hugo Benichifd44e912017-02-02 17:02:36 +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.
Hugo Benichifd44e912017-02-02 17:02:36 +09004462 *
Lorenzo Colitti76b639e2021-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 *
Chalard Jeana5ff1132020-05-20 16:11:50 +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 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004480 * @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.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004483 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004484 *
4485 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004486 */
Lorenzo Colitti76b639e2021-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,
Chalard Jean158702d2019-01-07 19:26:34 +09004493 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004494 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004495 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004496 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004497 }
4498
4499 /**
junyulai8eb13a22021-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.
junyulai7514e312021-03-05 15:51:17 +08004520 */
junyulai7514e312021-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);
junyulai1b1c8742021-03-12 20:05:08 +08004526 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai7514e312021-03-05 15:51:17 +08004527 }
4528
4529 /**
fenglub00f4882015-04-21 17:12:05 -07004530 * 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
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004534 * method assumes that the caller has previously called
4535 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4536 * changes.
fenglu3f357402015-03-20 11:29:56 -07004537 *
fengluea2d9282015-04-27 14:28:04 -07004538 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004539 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004540 */
Chalard Jean158702d2019-01-07 19:26:34 +09004541 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004542 try {
fenglub00f4882015-04-21 17:12:05 -07004543 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004544 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004545 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004546 }
4547 }
4548
4549 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004550 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004551 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4552 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4553 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004554 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4555 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004556 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004557 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4558 * triggering it as soon as this call returns.
4559 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004560 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004561 */
Chalard Jean158702d2019-01-07 19:26:34 +09004562 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004563 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004564 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004565 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 VAN81f68422021-03-15 07:31:54 +00004569 if (networkCallback.networkRequest == null) {
4570 throw new IllegalArgumentException("NetworkCallback was not registered");
4571 }
Etan Cohen6cb65992019-04-16 15:07:55 -07004572 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4573 Log.d(TAG, "NetworkCallback was already unregistered");
4574 return;
4575 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004576 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 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004591 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004592 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004593 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004594
4595 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004596 * 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 */
Chalard Jean158702d2019-01-07 19:26:34 +09004604 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004605 releaseNetworkRequest(operation);
4606 }
4607
4608 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004609 * 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 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004616 * @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 Wang4d513572021-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) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004629 try {
4630 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004631 } catch (RemoteException e) {
4632 throw e.rethrowFromSystemServer();
4633 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004634 }
4635
4636 /**
lucaslin2240ef62019-03-12 13:08:03 +08004637 * 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 Wang4d513572021-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) {
lucaslin2240ef62019-03-12 13:08:03 +08004658 try {
4659 mService.setAcceptPartialConnectivity(network, accept, always);
4660 } catch (RemoteException e) {
4661 throw e.rethrowFromSystemServer();
4662 }
4663 }
4664
4665 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004666 * 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 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004671 * @param network The network to accept.
4672 *
4673 * @hide
4674 */
Chiachang Wang4d513572021-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) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004682 try {
4683 mService.setAvoidUnvalidated(network);
4684 } catch (RemoteException e) {
4685 throw e.rethrowFromSystemServer();
4686 }
4687 }
4688
4689 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004690 * Requests that the system open the captive portal app on the specified network.
4691 *
Remi NGUYEN VAN4cf96ab2021-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 *
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004695 * @param network The network to log into.
4696 *
4697 * @hide
4698 */
Remi NGUYEN VAN4cf96ab2021-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) {
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004706 try {
4707 mService.startCaptivePortalApp(network);
4708 } catch (RemoteException e) {
4709 throw e.rethrowFromSystemServer();
4710 }
4711 }
4712
4713 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004714 * 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.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004718 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004719 * @param appExtras Extras to include in the app start intent.
4720 * @hide
4721 */
4722 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004723 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004724 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004725 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004726 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004727 } catch (RemoteException e) {
4728 throw e.rethrowFromSystemServer();
4729 }
4730 }
4731
4732 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004733 * Determine whether the device is configured to avoid bad wifi.
4734 * @hide
4735 */
4736 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004737 @RequiresPermission(anyOf = {
4738 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4739 android.Manifest.permission.NETWORK_STACK})
4740 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004741 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004742 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004743 } catch (RemoteException e) {
4744 throw e.rethrowFromSystemServer();
4745 }
4746 }
4747
4748 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004749 * 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
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004751 * 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.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004753 *
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.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004800 *
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 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004806 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004807 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004808 try {
4809 return mService.getMultipathPreference(network);
4810 } catch (RemoteException e) {
4811 throw e.rethrowFromSystemServer();
4812 }
4813 }
4814
4815 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004816 * Resets all connectivity manager settings back to factory defaults.
4817 * @hide
4818 */
Chiachang Wang4d513572021-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})
Stuart Scott0f835ac2015-03-30 13:17:11 -07004823 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004824 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004825 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004826 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004827 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004828 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004829 }
4830 }
4831
4832 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004833 * 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
Paul Jensenee2f45d2015-03-10 10:54:12 -04004844 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004845 *
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 */
Chalard Jean158702d2019-01-07 19:26:34 +09004850 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004851 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004852 // 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 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004877 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004878 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004879 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004880 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4881
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004882 if (netId != NETID_UNSET) {
4883 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004884 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004885
4886 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4887 return false;
4888 }
4889
4890 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004891 // Set HTTP proxy system properties to match network.
4892 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004893 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004894 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +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 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004899 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANe1b04f62021-03-18 23:27:19 +09004900 InetAddressCompat.clearDnsCache();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004901 // 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();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004904 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004905
4906 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004907 }
4908
4909 /**
4910 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004911 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004912 *
4913 * @return {@code Network} to which this process is bound, or {@code null}.
4914 */
Chalard Jean158702d2019-01-07 19:26:34 +09004915 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004916 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 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004931 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004932 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004933 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004934 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004935 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004936 return new Network(netId);
4937 }
4938
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004939 private void unsupportedStartingFrom(int version) {
4940 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004941 // 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.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004944 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.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004955 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004956 // 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() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004960 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004961 }
4962
Paul Jensen8cdda642014-05-29 10:12:39 -04004963 /**
4964 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004965 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004966 *
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 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004973 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004974 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004975 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004976 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004977 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004978 }
Felipe Leme30511352016-01-22 09:44:57 -08004979
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.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004997 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004998 * 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
Felipe Lemed34c9af2016-01-27 14:46:39 -08005003 /**
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
Felipe Leme7e4c1852016-01-25 11:48:04 -08005015 /** @hide */
5016 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08005017 @IntDef(flag = false, value = {
5018 RESTRICT_BACKGROUND_STATUS_DISABLED,
5019 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5020 RESTRICT_BACKGROUND_STATUS_ENABLED,
5021 })
Felipe Leme30511352016-01-22 09:44:57 -08005022 public @interface RestrictBackgroundStatus {
5023 }
5024
Felipe Leme30511352016-01-22 09:44:57 -08005025 /**
5026 * Determines if the calling application is subject to metered network restrictions while
5027 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07005028 *
5029 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5030 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5031 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08005032 */
5033 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5034 try {
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005035 return mService.getRestrictBackgroundStatusByCaller();
Felipe Leme30511352016-01-22 09:44:57 -08005036 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07005037 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08005038 }
5039 }
Ricky Wai7097cc92018-01-23 04:09:45 +00005040
5041 /**
5042 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00005043 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5044 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00005045 *
5046 * @return Hash of network watchlist config file. Null if config does not exist.
5047 */
Chalard Jean158702d2019-01-07 19:26:34 +09005048 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00005049 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 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005057
5058 /**
5059 * Returns the {@code uid} of the owner of a network connection.
5060 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08005061 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5062 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005063 * @param local The local {@link InetSocketAddress} of a connection.
5064 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005065 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08005066 * (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.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005071 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08005072 public int getConnectionOwnerUid(
5073 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07005074 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5075 try {
5076 return mService.getConnectionOwnerUid(connectionInfo);
5077 } catch (RemoteException e) {
5078 throw e.rethrowFromSystemServer();
5079 }
5080 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09005081
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 }
Cody Kestingf53a0752020-04-15 12:33:28 -07005096
Remi NGUYEN VAN5f406422021-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 VAN5f406422021-01-15 23:02:47 +09005109 /** @hide */
5110 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5111 return new ConnectivityDiagnosticsManager(mContext, mService);
5112 }
5113
Cody Kestingf53a0752020-04-15 12:33:28 -07005114 /**
5115 * Simulates a Data Stall for the specified Network.
5116 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09005117 * <p>This method should only be used for tests.
5118 *
Remi NGUYEN VANd2d60c62021-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.
Cody Kestingf53a0752020-04-15 12:33:28 -07005121 *
5122 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VANd2d60c62021-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.
Cody Kestingf53a0752020-04-15 12:33:28 -07005126 * @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 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09005131 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07005132 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5133 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VANd2d60c62021-04-08 16:26:20 +09005134 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Cody Kestingf53a0752020-04-15 12:33:28 -07005135 @NonNull Network network, @NonNull PersistableBundle extras) {
5136 try {
5137 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5138 } catch (RemoteException e) {
5139 e.rethrowFromSystemServer();
5140 }
5141 }
James Mattis356a8792020-10-28 21:48:54 -07005142
Daniel Brightf9e945b2020-06-15 16:10:01 -07005143 @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
Daniel Brightf9e945b2020-06-15 16:10:01 -07005168 * @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 Bright7ee5f522021-03-10 11:51:50 -08005170 * callbacks cannot be guaranteed.onQosCallbackRegistered
5171 * @param callback receives qos events that satisfy socketInfo
Daniel Brightf9e945b2020-06-15 16:10:01 -07005172 *
5173 * @hide
5174 */
5175 @SystemApi
5176 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright7ee5f522021-03-10 11:51:50 -08005177 @CallbackExecutor @NonNull final Executor executor,
5178 @NonNull final QosCallback callback) {
Daniel Brightf9e945b2020-06-15 16:10:01 -07005179 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07005180 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright7ee5f522021-03-10 11:51:50 -08005181 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07005182
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 }
Junyu Laia62493f2021-01-19 11:10:56 +00005256
5257 /**
Roshan Pius951c0032020-12-22 15:10:42 -08005258 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Junyu Laia62493f2021-01-19 11:10:56 +00005259 * 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.
5321 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5322 * If null, the callback is invoked on the default internal Handler.
5323 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5324 * the callback must not be shared - it uniquely specifies this request.
5325 * @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,
junyulai962bdb82021-03-09 20:49:48 +08005339 @NonNull Handler handler, @NonNull NetworkCallback networkCallback) {
Junyu Laia62493f2021-01-19 11:10:56 +00005340 final NetworkCapabilities nc = request.networkCapabilities;
5341 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulai962bdb82021-03-09 20:49:48 +08005342 TYPE_NONE, new CallbackHandler(handler));
Junyu Laia62493f2021-01-19 11:10:56 +00005343 }
James Mattis45d81842021-01-10 14:24:24 -08005344
5345 /**
James Mattis45d81842021-01-10 14:24:24 -08005346 * Used by automotive devices to set the network preferences used to direct traffic at an
5347 * application level as per the given OemNetworkPreferences. An example use-case would be an
5348 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5349 * vehicle via a particular network.
5350 *
5351 * Calling this will overwrite the existing preference.
5352 *
5353 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5354 * @param executor the executor on which listener will be invoked.
5355 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5356 * communicate completion of setOemNetworkPreference(). This will only be
5357 * called once upon successful completion of setOemNetworkPreference().
5358 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5359 * @throws SecurityException if missing the appropriate permissions.
5360 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005361 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005362 */
James Mattisda32cfe2021-01-26 16:23:52 -08005363 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005364 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005365 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005366 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean6010c002021-03-03 16:37:13 +09005367 @Nullable final Runnable listener) {
James Mattis45d81842021-01-10 14:24:24 -08005368 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5369 if (null != listener) {
5370 Objects.requireNonNull(executor, "Executor must be non-null");
5371 }
Chalard Jean6010c002021-03-03 16:37:13 +09005372 final IOnCompleteListener listenerInternal = listener == null ? null :
5373 new IOnCompleteListener.Stub() {
James Mattis45d81842021-01-10 14:24:24 -08005374 @Override
5375 public void onComplete() {
Chalard Jean6010c002021-03-03 16:37:13 +09005376 executor.execute(listener::run);
James Mattis45d81842021-01-10 14:24:24 -08005377 }
5378 };
5379
5380 try {
5381 mService.setOemNetworkPreference(preference, listenerInternal);
5382 } catch (RemoteException e) {
5383 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5384 throw e.rethrowFromSystemServer();
5385 }
5386 }
lucaslin30e70a82021-03-12 00:46:33 +08005387
Chalard Jeanfa45a682021-02-25 17:23:40 +09005388 /**
5389 * Request that a user profile is put by default on a network matching a given preference.
5390 *
5391 * See the documentation for the individual preferences for a description of the supported
5392 * behaviors.
5393 *
5394 * @param profile the profile concerned.
5395 * @param preference the preference for this profile.
5396 * @param executor an executor to execute the listener on. Optional if listener is null.
5397 * @param listener an optional listener to listen for completion of the operation.
5398 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5399 * @throws SecurityException if missing the appropriate permissions.
5400 * @hide
5401 */
Chalard Jean6010c002021-03-03 16:37:13 +09005402 // This function is for establishing per-profile default networking and can only be called by
5403 // the device policy manager, running as the system server. It would make no sense to call it
5404 // on a context for a user because it does not establish a setting on behalf of a user, rather
5405 // it establishes a setting for a user on behalf of the DPM.
5406 @SuppressLint({"UserHandle"})
5407 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanfa45a682021-02-25 17:23:40 +09005408 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5409 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
5410 @ProfileNetworkPreference final int preference,
5411 @Nullable @CallbackExecutor final Executor executor,
5412 @Nullable final Runnable listener) {
5413 if (null != listener) {
5414 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5415 }
5416 final IOnCompleteListener proxy;
5417 if (null == listener) {
5418 proxy = null;
5419 } else {
5420 proxy = new IOnCompleteListener.Stub() {
5421 @Override
5422 public void onComplete() {
5423 executor.execute(listener::run);
5424 }
5425 };
5426 }
5427 try {
5428 mService.setProfileNetworkPreference(profile, preference, proxy);
5429 } catch (RemoteException e) {
5430 throw e.rethrowFromSystemServer();
5431 }
5432 }
5433
lucaslin30e70a82021-03-12 00:46:33 +08005434 // The first network ID of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005435 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin30e70a82021-03-12 00:46:33 +08005436 // The network ID range of IPSec tunnel interface.
lucaslin0cdcea12021-03-15 17:24:12 +08005437 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin30e70a82021-03-12 00:46:33 +08005438
5439 /**
5440 * Get the network ID range reserved for IPSec tunnel interfaces.
5441 *
5442 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5443 * @hide
5444 */
5445 @SystemApi(client = MODULE_LIBRARIES)
5446 @NonNull
5447 public static Range<Integer> getIpSecNetIdRange() {
5448 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5449 }
lucaslin705c3332021-03-12 17:56:09 +08005450
5451 /**
5452 * Get private DNS mode from settings.
5453 *
lucaslin7abe7e02021-03-17 14:53:35 +08005454 * @param context The Context to query the private DNS mode from settings.
lucaslin705c3332021-03-12 17:56:09 +08005455 * @return A string of private DNS mode as one of the PRIVATE_DNS_MODE_* constants.
5456 *
5457 * @hide
5458 */
5459 @SystemApi(client = MODULE_LIBRARIES)
5460 @NonNull
5461 @PrivateDnsMode
lucaslin20f04882021-03-16 17:11:14 +08005462 public static String getPrivateDnsMode(@NonNull Context context) {
5463 final ContentResolver cr = context.getContentResolver();
lucaslin705c3332021-03-12 17:56:09 +08005464 String mode = Settings.Global.getString(cr, PRIVATE_DNS_MODE);
5465 if (TextUtils.isEmpty(mode)) mode = Settings.Global.getString(cr, PRIVATE_DNS_DEFAULT_MODE);
5466 // If both PRIVATE_DNS_MODE and PRIVATE_DNS_DEFAULT_MODE are not set, choose
5467 // PRIVATE_DNS_MODE_OPPORTUNISTIC as default mode.
5468 if (TextUtils.isEmpty(mode)) mode = PRIVATE_DNS_MODE_OPPORTUNISTIC;
5469 return mode;
5470 }
paulhu89a762a2021-03-25 12:36:56 +08005471
5472 /**
5473 * Set private DNS mode to settings.
5474 *
5475 * @param context The {@link Context} to set the private DNS mode.
5476 * @param mode The private dns mode. This should be one of the PRIVATE_DNS_MODE_* constants.
5477 *
5478 * @hide
5479 */
5480 @SystemApi(client = MODULE_LIBRARIES)
5481 public static void setPrivateDnsMode(@NonNull Context context,
5482 @NonNull @PrivateDnsMode String mode) {
5483 if (!(mode == PRIVATE_DNS_MODE_OFF
5484 || mode == PRIVATE_DNS_MODE_OPPORTUNISTIC
5485 || mode == PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
5486 throw new IllegalArgumentException("Invalid private dns mode");
5487 }
5488 Settings.Global.putString(context.getContentResolver(), PRIVATE_DNS_MODE, mode);
5489 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005490}