blob: e463a7cd319a677ec1e778919708c86aaeba1eac [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;
junyulaid05a1922019-01-15 11:32:44 +080019import static android.net.IpSecManager.INVALID_RESOURCE_ID;
Junyu Laia62493f2021-01-19 11:10:56 +000020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaiad010792021-01-11 16:53:38 +080021import static android.net.NetworkRequest.Type.LISTEN;
22import static android.net.NetworkRequest.Type.REQUEST;
23import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +090024import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Brightf9e945b2020-06-15 16:10:01 -070025import static android.net.QosCallback.QosCallbackRegistrationException;
junyulaid05a1922019-01-15 11:32:44 +080026
junyulai4c95b082018-12-27 17:25:29 +080027import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080028import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090029import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000030import android.annotation.Nullable;
Jeff Sharkey656584a2017-04-24 11:18:03 -060031import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080032import android.annotation.SdkConstant;
33import android.annotation.SdkConstant.SdkConstantType;
Junyu Laia62493f2021-01-19 11:10:56 +000034import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080035import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060036import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070037import android.app.PendingIntent;
Artur Satayev9c2add62019-12-10 17:47:52 +000038import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070039import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070040import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080041import android.net.IpSecManager.UdpEncapsulationSocket;
42import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080043import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080044import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080045import android.net.TetheringManager.TetheringRequest;
Robert Greenwalt2034b912009-08-12 16:08:25 -070046import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000047import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070048import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080049import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070050import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080051import android.os.IBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070052import android.os.Looper;
53import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070054import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080055import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070056import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090057import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080058import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080059import android.os.ResultReceiver;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080060import android.os.ServiceManager;
Hugo Benichia590ab82017-05-11 13:16:17 +090061import android.os.ServiceSpecificException;
Jeff Sharkey971cd162011-08-29 16:02:57 -070062import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080063import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080064import android.telephony.TelephonyManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080065import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070066import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090067import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090068import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090070import com.android.connectivity.aidl.INetworkAgent;
markchien6ae63e52020-01-21 13:11:06 +080071import com.android.internal.annotations.GuardedBy;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090072import com.android.internal.util.Protocol;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070073
Paul Jensen3e2917c2014-08-27 12:38:45 -040074import libcore.net.event.NetworkEventDispatcher;
75
junyulai7e06ad42019-03-04 22:45:36 +080076import java.io.IOException;
77import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080078import java.lang.annotation.Retention;
79import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090080import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080081import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070082import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080083import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090084import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090085import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080086import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090087import java.util.List;
88import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080089import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080090import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080091import java.util.concurrent.ExecutorService;
92import java.util.concurrent.Executors;
93import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -080094
The Android Open Source Project28527d22009-03-03 19:31:44 -080095/**
96 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060097 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -080098 * <p>
99 * The primary responsibilities of this class are to:
100 * <ol>
101 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
102 * <li>Send broadcast intents when network connectivity changes</li>
103 * <li>Attempt to "fail over" to another network when connectivity to a network
104 * is lost</li>
105 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
106 * state of the available networks</li>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700107 * <li>Provide an API that allows applications to request and select networks for their data
108 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800109 * </ol>
110 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600111@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700112public class ConnectivityManager {
113 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900114 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700115
The Android Open Source Project28527d22009-03-03 19:31:44 -0800116 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700117 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800118 * been established or lost. The NetworkInfo for the affected network is
119 * sent as an extra; it should be consulted to see what kind of
120 * connectivity event occurred.
121 * <p/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800122 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
123 * broadcast if they declare the broadcast receiver in their manifest. Apps
124 * will still receive broadcasts if they register their
125 * {@link android.content.BroadcastReceiver} with
126 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
127 * and that context is still valid.
128 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800129 * If this is a connection that was the result of failing over from a
130 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
131 * set to true.
132 * <p/>
133 * For a loss of connectivity, if the connectivity manager is attempting
134 * to connect (or has already connected) to another network, the
135 * NetworkInfo for the new network is also passed as an extra. This lets
136 * any receivers of the broadcast know that they should not necessarily
137 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800138 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800139 * the failover attempt succeeded (and so there is still overall data
140 * connectivity), or that the failover attempt failed, meaning that all
141 * connectivity has been lost.
142 * <p/>
143 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
144 * is set to {@code true} if there are no connected networks at all.
Chalard Jean52e23962018-02-10 05:33:50 +0900145 *
146 * @deprecated apps should use the more versatile {@link #requestNetwork},
147 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
148 * functions instead for faster and more detailed updates about the network
149 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800150 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800151 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900152 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800153 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700154
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500156 * The device has connected to a network that has presented a captive
157 * portal, which is blocking Internet connectivity. The user was presented
158 * with a notification that network sign in is required,
159 * and the user invoked the notification's action indicating they
Paul Jensen75e0adb2015-05-22 10:50:39 -0400160 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500161 * facilitate signing in to the network. This action includes a
162 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
163 * the network presenting the captive portal; all communication with the
164 * captive portal must be done using this {@code Network} object.
165 * <p/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400166 * This activity includes a {@link CaptivePortal} extra named
167 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
168 * outcomes of the captive portal sign in to the system:
169 * <ul>
170 * <li> When the app handling this action believes the user has signed in to
171 * the network and the captive portal has been dismissed, the app should
172 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
173 * reevaluate the network. If reevaluation finds the network no longer
174 * subject to a captive portal, the network may become the default active
Chalard Jean9dd11612018-06-04 16:52:49 +0900175 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400176 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500177 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400178 * {@link CaptivePortal#ignoreNetwork}. </li>
179 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500180 */
181 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
182 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
183
184 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800185 * The lookup key for a {@link NetworkInfo} object. Retrieve with
186 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700187 *
Chalard Jean97021a12019-01-11 16:47:53 +0900188 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
189 * can't accurately represent modern network characteristics.
190 * Please obtain information about networks from the {@link NetworkCapabilities}
191 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800192 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700193 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800194 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700195
The Android Open Source Project28527d22009-03-03 19:31:44 -0800196 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700197 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700198 *
199 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900200 * @deprecated The network type is not rich enough to represent the characteristics
201 * of modern networks. Please use {@link NetworkCapabilities} instead,
202 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700203 */
Chalard Jean97021a12019-01-11 16:47:53 +0900204 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700205 public static final String EXTRA_NETWORK_TYPE = "networkType";
206
207 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800208 * The lookup key for a boolean that indicates whether a connect event
209 * is for a network to which the connectivity manager was failing over
210 * following a disconnect on another network.
211 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai9826e7f2018-12-13 12:47:51 +0800212 *
213 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214 */
junyulai9826e7f2018-12-13 12:47:51 +0800215 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800216 public static final String EXTRA_IS_FAILOVER = "isFailover";
217 /**
218 * The lookup key for a {@link NetworkInfo} object. This is supplied when
219 * there is another network that it may be possible to connect to. Retrieve with
220 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800221 *
222 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800223 */
junyulai9826e7f2018-12-13 12:47:51 +0800224 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800225 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
226 /**
227 * The lookup key for a boolean that indicates whether there is a
228 * complete lack of connectivity, i.e., no network is available.
229 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
230 */
231 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
232 /**
233 * The lookup key for a string that indicates why an attempt to connect
234 * to a network failed. The string has no particular structure. It is
235 * intended to be used in notifications presented to users. Retrieve
236 * it with {@link android.content.Intent#getStringExtra(String)}.
237 */
238 public static final String EXTRA_REASON = "reason";
239 /**
240 * The lookup key for a string that provides optionally supplied
241 * extra information about the network state. The information
242 * may be passed up from the lower networking layers, and its
243 * meaning may be specific to a particular network type. Retrieve
244 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800245 *
246 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800247 */
junyulai9826e7f2018-12-13 12:47:51 +0800248 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800249 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700250 /**
251 * The lookup key for an int that provides information about
252 * our connection to the internet at large. 0 indicates no connection,
253 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700254 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700255 * {@hide}
256 */
257 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800258 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400259 * The lookup key for a {@link CaptivePortal} object included with the
260 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
261 * object can be used to either indicate to the system that the captive
262 * portal has been dismissed or that the user does not want to pursue
263 * signing in to captive portal. Retrieve it with
264 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500265 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400266 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700267
268 /**
269 * Key for passing a URL to the captive portal login activity.
270 */
271 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
272
Paul Jensen60df4aa2015-02-27 22:55:47 -0500273 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900274 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
275 * portal login activity.
276 * {@hide}
277 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900278 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900279 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
280 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
281
282 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900283 * Key for passing a user agent string to the captive portal login activity.
284 * {@hide}
285 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900286 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900287 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
288 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
289
290 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700291 * Broadcast action to indicate the change of data activity status
292 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800293 * The network becomes active when data transmission is started, or
294 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700295 * {@hide}
296 */
297 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900298 public static final String ACTION_DATA_ACTIVITY_CHANGE =
299 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700300 /**
301 * The lookup key for an enum that indicates the network device type on which this data activity
302 * change happens.
303 * {@hide}
304 */
305 public static final String EXTRA_DEVICE_TYPE = "deviceType";
306 /**
307 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
308 * it is actively sending or receiving data and {@code false} means it is idle.
309 * {@hide}
310 */
311 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700312 /**
313 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
314 * {@hide}
315 */
316 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700317
318 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800319 * Broadcast Action: The setting for background data usage has changed
320 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
321 * <p>
322 * If an application uses the network in the background, it should listen
323 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700324 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800325 * <p>
326 *
327 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
328 * of background data depends on several combined factors, and
329 * this broadcast is no longer sent. Instead, when background
330 * data is unavailable, {@link #getActiveNetworkInfo()} will now
331 * appear disconnected. During first boot after a platform
332 * upgrade, this broadcast will be sent once if
333 * {@link #getBackgroundDataSetting()} was {@code false} before
334 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800335 */
336 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800337 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800338 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
339 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
340
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700341 /**
342 * Broadcast Action: The network connection may not be good
343 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
344 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
345 * the network and it's condition.
346 * @hide
347 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800348 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100349 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700350 public static final String INET_CONDITION_ACTION =
351 "android.net.conn.INET_CONDITION_ACTION";
352
Robert Greenwalt2034b912009-08-12 16:08:25 -0700353 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800354 * Broadcast Action: A tetherable connection has come or gone.
355 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900356 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
357 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800358 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
359 * the current state of tethering. Each include a list of
360 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800361 * @hide
362 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800363 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000364 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800365 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800366 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800367
368 /**
369 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800370 * gives a String[] listing all the interfaces configured for
371 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800372 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000373 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800374 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800375
376 /**
377 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900378 * gives a String[] listing all the interfaces currently in local-only
379 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800380 */
markchiena0f8fd92019-12-25 19:40:32 +0800381 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900382
383 /**
384 * @hide
385 * gives a String[] listing all the interfaces currently tethered
386 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
387 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000388 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800389 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800390
391 /**
392 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800393 * gives a String[] listing all the interfaces we tried to tether and
394 * failed. Use {@link #getLastTetherError} to find the error code
395 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800396 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000397 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800398 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800399
400 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800401 * Broadcast Action: The captive portal tracker has finished its test.
402 * Sent only while running Setup Wizard, in lieu of showing a user
403 * notification.
404 * @hide
405 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800406 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800407 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
408 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
409 /**
410 * The lookup key for a boolean that indicates whether a captive portal was detected.
411 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
412 * @hide
413 */
414 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
415
416 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900417 * Action used to display a dialog that asks the user whether to connect to a network that is
418 * not validated. This intent is used to start the dialog in settings via startActivity.
419 *
420 * @hide
421 */
422 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
423
424 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900425 * Action used to display a dialog that asks the user whether to avoid a network that is no
426 * longer validated. This intent is used to start the dialog in settings via startActivity.
427 *
428 * @hide
429 */
430 public static final String ACTION_PROMPT_LOST_VALIDATION =
431 "android.net.conn.PROMPT_LOST_VALIDATION";
432
433 /**
lucaslin2240ef62019-03-12 13:08:03 +0800434 * Action used to display a dialog that asks the user whether to stay connected to a network
435 * that has not validated. This intent is used to start the dialog in settings via
436 * startActivity.
437 *
438 * @hide
439 */
440 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
441 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
442
443 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800444 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900445 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800446 * @hide
447 */
markchiena0f8fd92019-12-25 19:40:32 +0800448 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800449
450 /**
451 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900452 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800453 * @hide
454 */
455 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900456 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800457
458 /**
459 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900460 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800461 * @hide
462 */
463 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900464 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800465
466 /**
467 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900468 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800469 * @hide
470 */
471 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900472 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800473
474 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800475 * Wifi P2p tethering type.
476 * Wifi P2p tethering is set through events automatically, and don't
477 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
478 * @hide
479 */
markchiena0f8fd92019-12-25 19:40:32 +0800480 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800481
482 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800483 * Extra used for communicating with the TetherService. Includes the type of tethering to
484 * enable if any.
485 * @hide
486 */
markchien6ae63e52020-01-21 13:11:06 +0800487 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800488
489 /**
490 * Extra used for communicating with the TetherService. Includes the type of tethering for
491 * which to cancel provisioning.
492 * @hide
493 */
markchien6ae63e52020-01-21 13:11:06 +0800494 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800495
496 /**
497 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
498 * provisioning.
499 * @hide
500 */
markchien6ae63e52020-01-21 13:11:06 +0800501 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800502
503 /**
504 * Tells the TetherService to run a provision check now.
505 * @hide
506 */
markchien6ae63e52020-01-21 13:11:06 +0800507 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800508
509 /**
510 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
511 * which will receive provisioning results. Can be left empty.
512 * @hide
513 */
markchien6ae63e52020-01-21 13:11:06 +0800514 public static final String EXTRA_PROVISION_CALLBACK =
515 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800516
517 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800518 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700519 * @hide
520 */
paulhu74357e72020-01-13 16:46:45 +0800521 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700522 public static final int TYPE_NONE = -1;
523
524 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900525 * A Mobile data connection. Devices may support more than one.
526 *
527 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
528 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
529 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700530 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900531 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700532 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900533
Robert Greenwalt2034b912009-08-12 16:08:25 -0700534 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900535 * A WIFI data connection. Devices may support more than one.
536 *
537 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
538 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
539 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700540 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900541 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700542 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900543
Robert Greenwalt2034b912009-08-12 16:08:25 -0700544 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800545 * An MMS-specific Mobile data connection. This network type may use the
546 * same network interface as {@link #TYPE_MOBILE} or it may use a different
547 * one. This is used by applications needing to talk to the carrier's
548 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900549 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900550 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900551 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900552 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700553 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700554 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700555 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900556
Robert Greenwalt2034b912009-08-12 16:08:25 -0700557 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800558 * A SUPL-specific Mobile data connection. This network type may use the
559 * same network interface as {@link #TYPE_MOBILE} or it may use a different
560 * one. This is used by applications needing to talk to the carrier's
561 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900562 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900563 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900564 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900565 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700566 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700567 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700568 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900569
Robert Greenwalt2034b912009-08-12 16:08:25 -0700570 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800571 * A DUN-specific Mobile data connection. This network type may use the
572 * same network interface as {@link #TYPE_MOBILE} or it may use a different
573 * one. This is sometimes by the system when setting up an upstream connection
574 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900575 *
576 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
577 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
578 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700579 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900580 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700581 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900582
Robert Greenwalt2034b912009-08-12 16:08:25 -0700583 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800584 * A High Priority Mobile data connection. This network type uses the
585 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900586 * is different.
587 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900588 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
589 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
590 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700591 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700592 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700593 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900594
jshbfa81722010-03-11 15:04:43 -0800595 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900596 * A WiMAX data connection.
597 *
598 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
599 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
600 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800601 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900602 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800603 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800604
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800605 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900606 * A Bluetooth data connection.
607 *
608 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
609 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
610 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800611 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900612 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800613 public static final int TYPE_BLUETOOTH = 7;
614
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700615 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800616 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900617 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700618 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900619 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800620 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800621
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700622 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900623 * An Ethernet data connection.
624 *
625 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
626 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
627 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700628 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900629 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800630 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700631
Wink Savilleb7c92c72011-03-12 14:52:01 -0800632 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800633 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900634 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800635 * {@hide}
636 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900637 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900638 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800639 public static final int TYPE_MOBILE_FOTA = 10;
640
641 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800642 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900643 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800644 * {@hide}
645 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900646 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100647 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800648 public static final int TYPE_MOBILE_IMS = 11;
649
650 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800651 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900652 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800653 * {@hide}
654 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900655 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900656 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800657 public static final int TYPE_MOBILE_CBS = 12;
658
repo syncf5de5572011-07-29 23:55:49 -0700659 /**
660 * A Wi-Fi p2p connection. Only requesting processes will have access to
661 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900662 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700663 * {@hide}
664 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900665 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800666 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700667 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800668
Wink Saville512c2202013-07-29 15:00:57 -0700669 /**
670 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900671 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700672 * {@hide}
673 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900674 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100675 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700676 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700677
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900678 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700679 * Emergency PDN connection for emergency services. This
680 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900681 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700682 * {@hide}
683 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900684 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900685 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700686 public static final int TYPE_MOBILE_EMERGENCY = 15;
687
Hui Lu865b70d2014-01-15 11:05:36 -0500688 /**
689 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900690 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500691 * {@hide}
692 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900693 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900694 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500695 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700696
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700697 /**
698 * A virtual network using one or more native bearers.
699 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900700 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700701 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900702 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700703 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500704
Benedict Wongbdfaa482018-11-14 17:40:55 -0800705 /**
706 * A network that is exclusively meant to be used for testing
707 *
708 * @deprecated Use {@link NetworkCapabilities} instead.
709 * @hide
710 */
711 @Deprecated
712 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700713
Chalard Jeanaea539a2020-03-25 01:24:04 +0900714 /**
715 * @deprecated Use {@link NetworkCapabilities} instead.
716 * @hide
717 */
718 @Deprecated
719 @Retention(RetentionPolicy.SOURCE)
720 @IntDef(prefix = { "TYPE_" }, value = {
721 TYPE_NONE,
722 TYPE_MOBILE,
723 TYPE_WIFI,
724 TYPE_MOBILE_MMS,
725 TYPE_MOBILE_SUPL,
726 TYPE_MOBILE_DUN,
727 TYPE_MOBILE_HIPRI,
728 TYPE_WIMAX,
729 TYPE_BLUETOOTH,
730 TYPE_DUMMY,
731 TYPE_ETHERNET,
732 TYPE_MOBILE_FOTA,
733 TYPE_MOBILE_IMS,
734 TYPE_MOBILE_CBS,
735 TYPE_WIFI_P2P,
736 TYPE_MOBILE_IA,
737 TYPE_MOBILE_EMERGENCY,
738 TYPE_PROXY,
739 TYPE_VPN,
740 TYPE_TEST
741 })
742 public @interface LegacyNetworkType {}
743
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900744 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
745 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
746 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
747 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
748 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
749
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700750 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800751 public static final int MAX_RADIO_TYPE = TYPE_TEST;
752
753 /** {@hide} */
754 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800755
Hugo Benichiad353f42017-06-20 14:07:59 +0900756 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
757
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800758 /**
759 * If you want to set the default network preference,you can directly
760 * change the networkAttributes array in framework's config.xml.
761 *
762 * @deprecated Since we support so many more networks now, the single
763 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800764 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800765 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800766 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800767 * from an App.
768 */
769 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800770 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
771
Jeff Sharkey8c870452012-09-26 22:03:49 -0700772 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700773 * @hide
774 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900775 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700776
Paul Jensen5dea4352014-07-11 12:28:19 -0400777 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900778 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
779 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900780 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900781 * @hide
782 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900783 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900784 new NetworkRequest.Builder().clearCapabilities().build();
785
786 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400787 * A NetID indicating no Network is selected.
788 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
789 * @hide
790 */
791 public static final int NETID_UNSET = 0;
792
Erik Klineb0be3e62017-10-30 15:29:44 +0900793 /**
794 * Private DNS Mode values.
795 *
796 * The "private_dns_mode" global setting stores a String value which is
797 * expected to be one of the following.
798 */
799
800 /**
801 * @hide
802 */
803 public static final String PRIVATE_DNS_MODE_OFF = "off";
804 /**
805 * @hide
806 */
807 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
808 /**
809 * @hide
810 */
811 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
812 /**
813 * The default Private DNS mode.
814 *
815 * This may change from release to release or may become dependent upon
816 * the capabilities of the underlying platform.
817 *
818 * @hide
819 */
Erik Klinea7edf6f2018-05-16 16:41:57 +0900820 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Klineb0be3e62017-10-30 15:29:44 +0900821
Chalard Jeana3b77512019-04-09 15:46:21 +0900822 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700823 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900824
Paul Jensenc0618a62014-12-10 15:12:18 -0500825 /**
826 * A kludge to facilitate static access where a Context pointer isn't available, like in the
827 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
828 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
829 * methods that take a Context argument.
830 */
831 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800832
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900833 private final Context mContext;
834
Felipe Leme30511352016-01-22 09:44:57 -0800835 private INetworkPolicyManager mNPManager;
Amos Bianchia9b415a2020-03-04 11:07:38 -0800836 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800837
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800838 /**
839 * Tests if a given integer represents a valid network type.
840 * @param networkType the type to be tested
841 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400842 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
843 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800844 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700845 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700846 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900847 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800848 }
849
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800850 /**
851 * Returns a non-localized string representing a given network type.
852 * ONLY used for debugging output.
853 * @param type the type needing naming
854 * @return a String for the given type, or a string version of the type ("87")
855 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900856 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800857 * {@hide}
858 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900859 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000860 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700861 public static String getNetworkTypeName(int type) {
862 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900863 case TYPE_NONE:
864 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700865 case TYPE_MOBILE:
866 return "MOBILE";
867 case TYPE_WIFI:
868 return "WIFI";
869 case TYPE_MOBILE_MMS:
870 return "MOBILE_MMS";
871 case TYPE_MOBILE_SUPL:
872 return "MOBILE_SUPL";
873 case TYPE_MOBILE_DUN:
874 return "MOBILE_DUN";
875 case TYPE_MOBILE_HIPRI:
876 return "MOBILE_HIPRI";
877 case TYPE_WIMAX:
878 return "WIMAX";
879 case TYPE_BLUETOOTH:
880 return "BLUETOOTH";
881 case TYPE_DUMMY:
882 return "DUMMY";
883 case TYPE_ETHERNET:
884 return "ETHERNET";
885 case TYPE_MOBILE_FOTA:
886 return "MOBILE_FOTA";
887 case TYPE_MOBILE_IMS:
888 return "MOBILE_IMS";
889 case TYPE_MOBILE_CBS:
890 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700891 case TYPE_WIFI_P2P:
892 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700893 case TYPE_MOBILE_IA:
894 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700895 case TYPE_MOBILE_EMERGENCY:
896 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500897 case TYPE_PROXY:
898 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900899 case TYPE_VPN:
900 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700901 default:
902 return Integer.toString(type);
903 }
904 }
905
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800906 /**
Aaron Huang96011892020-06-27 07:18:23 +0800907 * @hide
908 * TODO: Expose for SystemServer when becomes a module.
909 */
910 public void systemReady() {
911 try {
912 mService.systemReady();
913 } catch (RemoteException e) {
914 throw e.rethrowFromSystemServer();
915 }
916 }
917
918 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800919 * Checks if a given type uses the cellular data connection.
920 * This should be replaced in the future by a network property.
921 * @param networkType the type to check
922 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900923 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800924 * {@hide}
925 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900926 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900927 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700928 public static boolean isNetworkTypeMobile(int networkType) {
929 switch (networkType) {
930 case TYPE_MOBILE:
931 case TYPE_MOBILE_MMS:
932 case TYPE_MOBILE_SUPL:
933 case TYPE_MOBILE_DUN:
934 case TYPE_MOBILE_HIPRI:
935 case TYPE_MOBILE_FOTA:
936 case TYPE_MOBILE_IMS:
937 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -0700938 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -0700939 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700940 return true;
941 default:
942 return false;
943 }
944 }
945
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800946 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700947 * Checks if the given network type is backed by a Wi-Fi radio.
948 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900949 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700950 * @hide
951 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900952 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700953 public static boolean isNetworkTypeWifi(int networkType) {
954 switch (networkType) {
955 case TYPE_WIFI:
956 case TYPE_WIFI_P2P:
957 return true;
958 default:
959 return false;
960 }
961 }
962
963 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800964 * Specifies the preferred network type. When the device has more
965 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800966 *
967 * @param preference the network type to prefer over all others. It is
968 * unspecified what happens to the old preferred network in the
969 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700970 * @deprecated Functionality has been removed as it no longer makes sense,
971 * with many more than two networks - we'd need an array to express
972 * preference. Instead we use dynamic network properties of
973 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800974 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700975 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800976 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800977 }
978
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800979 /**
980 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800981 *
982 * @return an integer representing the preferred network type
983 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700984 * @deprecated Functionality has been removed as it no longer makes sense,
985 * with many more than two networks - we'd need an array to express
986 * preference. Instead we use dynamic network properties of
987 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800988 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700989 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -0600990 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -0800991 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700992 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800993 }
994
Scott Mainf58b7d82011-10-06 19:02:28 -0700995 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800996 * Returns details about the currently active default data network. When
997 * connected, this network is the default route for outgoing connections.
998 * You should always check {@link NetworkInfo#isConnected()} before initiating
999 * network traffic. This may return {@code null} when there is no default
1000 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001001 * Note that if the default network is a VPN, this method will return the
1002 * NetworkInfo for one of its underlying networks instead, or null if the
1003 * VPN agent did not specify any. Apps interested in learning about VPNs
1004 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001005 *
1006 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001007 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001008 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001009 */
junyulai9826e7f2018-12-13 12:47:51 +08001010 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001011 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001012 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001013 public NetworkInfo getActiveNetworkInfo() {
1014 try {
1015 return mService.getActiveNetworkInfo();
1016 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001017 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001018 }
1019 }
1020
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001021 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001022 * Returns a {@link Network} object corresponding to the currently active
1023 * default data network. In the event that the current active default data
1024 * network disconnects, the returned {@code Network} object will no longer
1025 * be usable. This will return {@code null} when there is no default
1026 * network.
1027 *
1028 * @return a {@link Network} object for the current default network or
1029 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001030 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001031 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001032 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001033 public Network getActiveNetwork() {
1034 try {
1035 return mService.getActiveNetwork();
1036 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001037 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001038 }
1039 }
1040
1041 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001042 * Returns a {@link Network} object corresponding to the currently active
1043 * default data network for a specific UID. In the event that the default data
1044 * network disconnects, the returned {@code Network} object will no longer
1045 * be usable. This will return {@code null} when there is no default
1046 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001047 *
1048 * @return a {@link Network} object for the current default network for the
1049 * given UID or {@code null} if no default network is currently active
1050 *
1051 * @hide
1052 */
paulhu8e96a752019-08-12 16:25:11 +08001053 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001054 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001055 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001056 return getActiveNetworkForUid(uid, false);
1057 }
1058
1059 /** {@hide} */
1060 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001061 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001062 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001063 } catch (RemoteException e) {
1064 throw e.rethrowFromSystemServer();
1065 }
1066 }
1067
1068 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001069 * Adds or removes a requirement for given UID ranges to use the VPN.
1070 *
1071 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1072 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1073 * otherwise have permission to bypass the VPN (e.g., because they have the
1074 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1075 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1076 * set to {@code false}, a previously-added restriction is removed.
1077 * <p>
1078 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1079 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1080 * remove a previously-added range, the exact range must be removed as is.
1081 * <p>
1082 * The changes are applied asynchronously and may not have been applied by the time the method
1083 * returns. Apps will be notified about any changes that apply to them via
1084 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1085 * effect.
1086 * <p>
1087 * This method should be called only by the VPN code.
1088 *
1089 * @param ranges the UID ranges to restrict
1090 * @param requireVpn whether the specified UID ranges must use a VPN
1091 *
1092 * TODO: expose as @SystemApi.
1093 * @hide
1094 */
1095 @RequiresPermission(anyOf = {
1096 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1097 android.Manifest.permission.NETWORK_STACK})
1098 public void setRequireVpnForUids(boolean requireVpn,
1099 @NonNull Collection<Range<Integer>> ranges) {
1100 Objects.requireNonNull(ranges);
1101 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1102 // This method is not necessarily expected to be used outside the system server, so
1103 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1104 // stack process, or by tests.
1105 UidRange[] rangesArray = new UidRange[ranges.size()];
1106 int index = 0;
1107 for (Range<Integer> range : ranges) {
1108 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1109 }
1110 try {
1111 mService.setRequireVpnForUids(requireVpn, rangesArray);
1112 } catch (RemoteException e) {
1113 throw e.rethrowFromSystemServer();
1114 }
1115 }
1116
1117 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001118 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1119 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1120 * but is still supported for backwards compatibility.
1121 * <p>
1122 * This type of VPN is assumed always to use the system default network, and must always declare
1123 * exactly one underlying network, which is the network that was the default when the VPN
1124 * connected.
1125 * <p>
1126 * Calling this method with {@code true} enables legacy behaviour, specifically:
1127 * <ul>
1128 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1129 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1130 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1131 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1132 * underlying the VPN.</li>
1133 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1134 * similarly replaced by the VPN network state.</li>
1135 * <li>Information on current network interfaces passed to NetworkStatsService will not
1136 * include any VPN interfaces.</li>
1137 * </ul>
1138 *
1139 * @param enabled whether legacy lockdown VPN is enabled or disabled
1140 *
1141 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1142 *
1143 * @hide
1144 */
1145 @RequiresPermission(anyOf = {
1146 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1147 android.Manifest.permission.NETWORK_SETTINGS})
1148 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1149 try {
1150 mService.setLegacyLockdownVpnEnabled(enabled);
1151 } catch (RemoteException e) {
1152 throw e.rethrowFromSystemServer();
1153 }
1154 }
1155
1156 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001157 * Returns details about the currently active default data network
1158 * for a given uid. This is for internal use only to avoid spying
1159 * other apps.
1160 *
1161 * @return a {@link NetworkInfo} object for the current default network
1162 * for the given uid or {@code null} if no default network is
1163 * available for the specified uid.
1164 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001165 * {@hide}
1166 */
paulhu8e96a752019-08-12 16:25:11 +08001167 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001168 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001169 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001170 return getActiveNetworkInfoForUid(uid, false);
1171 }
1172
1173 /** {@hide} */
1174 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001175 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001176 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001177 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001178 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001179 }
1180 }
1181
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001182 /**
1183 * Returns connection status information about a particular
1184 * network type.
1185 *
1186 * @param networkType integer specifying which networkType in
1187 * which you're interested.
1188 * @return a {@link NetworkInfo} object for the requested
1189 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001190 * supported by the device. If {@code networkType} is
1191 * TYPE_VPN and a VPN is active for the calling app,
1192 * then this method will try to return one of the
1193 * underlying networks for the VPN or null if the
1194 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001195 *
Paul Jensendda8e592015-03-18 12:23:02 -04001196 * @deprecated This method does not support multiple connected networks
1197 * of the same type. Use {@link #getAllNetworks} and
1198 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001199 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001200 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001201 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001202 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001203 public NetworkInfo getNetworkInfo(int networkType) {
1204 try {
1205 return mService.getNetworkInfo(networkType);
1206 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001207 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001208 }
1209 }
1210
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001211 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001212 * Returns connection status information about a particular
1213 * Network.
1214 *
1215 * @param network {@link Network} specifying which network
1216 * in which you're interested.
1217 * @return a {@link NetworkInfo} object for the requested
1218 * network or {@code null} if the {@code Network}
1219 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001220 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001221 */
junyulai9826e7f2018-12-13 12:47:51 +08001222 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001223 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001224 @Nullable
1225 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001226 return getNetworkInfoForUid(network, Process.myUid(), false);
1227 }
1228
1229 /** {@hide} */
1230 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001231 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001232 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001233 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001234 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001235 }
1236 }
1237
1238 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001239 * Returns connection status information about all network
1240 * types supported by the device.
1241 *
1242 * @return an array of {@link NetworkInfo} objects. Check each
1243 * {@link NetworkInfo#getType} for which type each applies.
1244 *
Paul Jensendda8e592015-03-18 12:23:02 -04001245 * @deprecated This method does not support multiple connected networks
1246 * of the same type. Use {@link #getAllNetworks} and
1247 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001248 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001249 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001250 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001251 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001252 public NetworkInfo[] getAllNetworkInfo() {
1253 try {
1254 return mService.getAllNetworkInfo();
1255 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001256 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001257 }
1258 }
1259
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001260 /**
junyulaiebd15162021-03-03 12:09:05 +08001261 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1262 * connected.
1263 * @hide
1264 */
1265 @SystemApi(client = MODULE_LIBRARIES)
1266 @RequiresPermission(anyOf = {
1267 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1268 android.Manifest.permission.NETWORK_STACK,
1269 android.Manifest.permission.NETWORK_SETTINGS})
1270 @NonNull
1271 public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
1272 try {
1273 return mService.getAllNetworkStateSnapshot();
1274 } catch (RemoteException e) {
1275 throw e.rethrowFromSystemServer();
1276 }
1277 }
1278
1279 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001280 * Returns the {@link Network} object currently serving a given type, or
1281 * null if the given type is not connected.
1282 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001283 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001284 * @deprecated This method does not support multiple connected networks
1285 * of the same type. Use {@link #getAllNetworks} and
1286 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001287 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001288 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001289 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001290 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001291 public Network getNetworkForType(int networkType) {
1292 try {
1293 return mService.getNetworkForType(networkType);
1294 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001295 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001296 }
1297 }
1298
1299 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001300 * Returns an array of all {@link Network} currently tracked by the
1301 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001302 *
1303 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001304 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001305 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001306 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001307 public Network[] getAllNetworks() {
1308 try {
1309 return mService.getAllNetworks();
1310 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001311 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001312 }
1313 }
1314
1315 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001316 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001317 * the Networks that applications run by the given user will use by default.
1318 * @hide
1319 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001320 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001321 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1322 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001323 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001324 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001325 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001326 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001327 }
1328 }
1329
1330 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001331 * Returns the IP information for the current default network.
1332 *
1333 * @return a {@link LinkProperties} object describing the IP info
1334 * for the current default network, or {@code null} if there
1335 * is no current default network.
1336 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001337 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001338 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1339 * value of {@link #getActiveNetwork()} instead. In particular,
1340 * this method will return non-null LinkProperties even if the
1341 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001342 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001343 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001344 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001345 public LinkProperties getActiveLinkProperties() {
1346 try {
1347 return mService.getActiveLinkProperties();
1348 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001349 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001350 }
1351 }
1352
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001353 /**
1354 * Returns the IP information for a given network type.
1355 *
1356 * @param networkType the network type of interest.
1357 * @return a {@link LinkProperties} object describing the IP info
1358 * for the given networkType, or {@code null} if there is
1359 * no current default network.
1360 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001361 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001362 * @deprecated This method does not support multiple connected networks
1363 * of the same type. Use {@link #getAllNetworks},
1364 * {@link #getNetworkInfo(android.net.Network)}, and
1365 * {@link #getLinkProperties(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 Jeana3b77512019-04-09 15:46:21 +09001369 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001370 public LinkProperties getLinkProperties(int networkType) {
1371 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001372 return mService.getLinkPropertiesForType(networkType);
1373 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001374 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001375 }
1376 }
1377
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001378 /**
1379 * Get the {@link LinkProperties} for the given {@link Network}. This
1380 * will return {@code null} if the network is unknown.
1381 *
1382 * @param network The {@link Network} object identifying the network in question.
1383 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001384 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001385 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001386 @Nullable
1387 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001388 try {
1389 return mService.getLinkProperties(network);
1390 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001391 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001392 }
1393 }
1394
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001395 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001396 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001397 * will return {@code null} if the network is unknown.
1398 *
1399 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001400 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001401 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001402 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001403 @Nullable
1404 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001405 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001406 return mService.getNetworkCapabilities(
1407 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001408 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001409 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001410 }
1411 }
1412
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001413 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001414 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001415 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1416 * portal is present.
1417 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1418 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1419 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001420 * The system network validation may be using different strategies to detect captive portals,
1421 * so this method does not necessarily return a URL used by the system. It only returns a URL
1422 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001423 *
Udam Sainicd645462016-01-04 12:16:14 -08001424 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001425 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1426 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001427 */
paulhu8e96a752019-08-12 16:25:11 +08001428 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001429 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001430 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001431 public String getCaptivePortalServerUrl() {
1432 try {
1433 return mService.getCaptivePortalServerUrl();
1434 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001435 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001436 }
1437 }
1438
1439 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001440 * Tells the underlying networking system that the caller wants to
1441 * begin using the named feature. The interpretation of {@code feature}
1442 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001443 *
1444 * <p>This method requires the caller to hold either the
1445 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1446 * or the ability to modify system settings as determined by
1447 * {@link android.provider.Settings.System#canWrite}.</p>
1448 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001449 * @param networkType specifies which network the request pertains to
1450 * @param feature the name of the feature to be used
1451 * @return an integer value representing the outcome of the request.
1452 * The interpretation of this value is specific to each networking
1453 * implementation+feature combination, except that the value {@code -1}
1454 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001455 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001456 * @deprecated Deprecated in favor of the cleaner
1457 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001458 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001459 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001460 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001461 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001462 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001463 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001464 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001465 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1466 if (netCap == null) {
1467 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1468 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001469 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001470 }
1471
1472 NetworkRequest request = null;
1473 synchronized (sLegacyRequests) {
1474 LegacyRequest l = sLegacyRequests.get(netCap);
1475 if (l != null) {
1476 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1477 renewRequestLocked(l);
1478 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001479 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001480 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001481 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001482 }
1483 }
1484
1485 request = requestNetworkForFeatureLocked(netCap);
1486 }
1487 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001488 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001489 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001490 } else {
1491 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001492 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001493 }
1494 }
1495
1496 /**
1497 * Tells the underlying networking system that the caller is finished
1498 * using the named feature. The interpretation of {@code feature}
1499 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001500 *
1501 * <p>This method requires the caller to hold either the
1502 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1503 * or the ability to modify system settings as determined by
1504 * {@link android.provider.Settings.System#canWrite}.</p>
1505 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001506 * @param networkType specifies which network the request pertains to
1507 * @param feature the name of the feature that is no longer needed
1508 * @return an integer value representing the outcome of the request.
1509 * The interpretation of this value is specific to each networking
1510 * implementation+feature combination, except that the value {@code -1}
1511 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001512 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001513 * @deprecated Deprecated in favor of the cleaner
1514 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001515 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001516 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001517 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001518 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001519 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001520 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001521 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001522 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1523 if (netCap == null) {
1524 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1525 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001526 return -1;
1527 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001528
Paul Jensen49f74a32014-12-17 10:39:34 -05001529 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001530 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001531 }
1532 return 1;
1533 }
1534
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001535 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001536 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1537 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001538 switch (feature) {
1539 case "enableCBS":
1540 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1541 case "enableDUN":
1542 case "enableDUNAlways":
1543 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1544 case "enableFOTA":
1545 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1546 case "enableHIPRI":
1547 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1548 case "enableIMS":
1549 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1550 case "enableMMS":
1551 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1552 case "enableSUPL":
1553 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1554 default:
1555 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001556 }
Erik Klinece55eb12017-01-26 18:08:28 +09001557 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1558 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001559 }
1560 return null;
1561 }
1562
Robert Greenwalt802c1102014-06-02 15:32:02 -07001563 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001564 if (netCap == null) return TYPE_NONE;
1565 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1566 return TYPE_MOBILE_CBS;
1567 }
1568 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1569 return TYPE_MOBILE_IMS;
1570 }
1571 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1572 return TYPE_MOBILE_FOTA;
1573 }
1574 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1575 return TYPE_MOBILE_DUN;
1576 }
1577 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1578 return TYPE_MOBILE_SUPL;
1579 }
1580 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1581 return TYPE_MOBILE_MMS;
1582 }
1583 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1584 return TYPE_MOBILE_HIPRI;
1585 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001586 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1587 return TYPE_WIFI_P2P;
1588 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001589 return TYPE_NONE;
1590 }
1591
1592 private static class LegacyRequest {
1593 NetworkCapabilities networkCapabilities;
1594 NetworkRequest networkRequest;
1595 int expireSequenceNumber;
1596 Network currentNetwork;
1597 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001598
1599 private void clearDnsBinding() {
1600 if (currentNetwork != null) {
1601 currentNetwork = null;
1602 setProcessDefaultNetworkForHostResolution(null);
1603 }
1604 }
1605
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001606 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001607 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001608 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001609 currentNetwork = network;
1610 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001611 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001612 }
1613 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001614 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001615 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001616 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1617 }
1618 };
1619 }
1620
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001621 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001622 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1623 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001624
1625 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1626 synchronized (sLegacyRequests) {
1627 LegacyRequest l = sLegacyRequests.get(netCap);
1628 if (l != null) return l.networkRequest;
1629 }
1630 return null;
1631 }
1632
1633 private void renewRequestLocked(LegacyRequest l) {
1634 l.expireSequenceNumber++;
1635 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1636 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1637 }
1638
1639 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1640 int ourSeqNum = -1;
1641 synchronized (sLegacyRequests) {
1642 LegacyRequest l = sLegacyRequests.get(netCap);
1643 if (l == null) return;
1644 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001645 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001646 }
1647 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1648 }
1649
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001650 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001651 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1652 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001653 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001654 try {
1655 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001656 } catch (RemoteException e) {
1657 throw e.rethrowFromSystemServer();
1658 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001659 LegacyRequest l = new LegacyRequest();
1660 l.networkCapabilities = netCap;
1661 l.delay = delay;
1662 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001663 l.networkRequest = sendRequestForNetwork(
1664 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001665 if (l.networkRequest == null) return null;
1666 sLegacyRequests.put(netCap, l);
1667 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1668 return l.networkRequest;
1669 }
1670
1671 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1672 if (delay >= 0) {
1673 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001674 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001675 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1676 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001677 }
1678 }
1679
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001680 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001681 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1682 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001683 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001684 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001685 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001686 if (l == null) return false;
1687 unregisterNetworkCallback(l.networkCallback);
1688 l.clearDnsBinding();
1689 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001690 }
1691
Erik Klinece55eb12017-01-26 18:08:28 +09001692 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1693 static {
1694 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1695 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1696 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1697 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1698 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1699 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1700 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1701 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1702 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1703 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1704 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1705 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1706 }
1707
1708 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1709 static {
1710 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1711 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1712 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1713 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1714 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1715 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1716 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1717 }
1718
1719 /**
1720 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1721 * instance suitable for registering a request or callback. Throws an
1722 * IllegalArgumentException if no mapping from the legacy type to
1723 * NetworkCapabilities is known.
1724 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001725 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1726 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001727 * @hide
1728 */
1729 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1730 final NetworkCapabilities nc = new NetworkCapabilities();
1731
1732 // Map from type to transports.
1733 final int NOT_FOUND = -1;
1734 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09001735 if (transport == NOT_FOUND) {
1736 throw new IllegalArgumentException("unknown legacy type: " + type);
1737 }
Erik Klinece55eb12017-01-26 18:08:28 +09001738 nc.addTransportType(transport);
1739
1740 // Map from type to capabilities.
1741 nc.addCapability(sLegacyTypeToCapability.get(
1742 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1743 nc.maybeMarkCapabilitiesRestricted();
1744 return nc;
1745 }
1746
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001747 /** @hide */
1748 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001749 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001750 public PacketKeepaliveCallback() {
1751 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001752 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001753 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001754 public void onStarted() {}
1755 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001756 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001757 public void onStopped() {}
1758 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001759 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001760 public void onError(int error) {}
1761 }
1762
1763 /**
1764 * Allows applications to request that the system periodically send specific packets on their
1765 * behalf, using hardware offload to save battery power.
1766 *
1767 * To request that the system send keepalives, call one of the methods that return a
1768 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1769 * passing in a non-null callback. If the callback is successfully started, the callback's
1770 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1771 * specifying one of the {@code ERROR_*} constants in this class.
1772 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001773 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1774 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1775 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001776 *
junyulai4c95b082018-12-27 17:25:29 +08001777 * @deprecated Use {@link SocketKeepalive} instead.
1778 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001779 * @hide
1780 */
1781 public class PacketKeepalive {
1782
1783 private static final String TAG = "PacketKeepalive";
1784
1785 /** @hide */
1786 public static final int SUCCESS = 0;
1787
1788 /** @hide */
1789 public static final int NO_KEEPALIVE = -1;
1790
1791 /** @hide */
1792 public static final int BINDER_DIED = -10;
1793
1794 /** The specified {@code Network} is not connected. */
1795 public static final int ERROR_INVALID_NETWORK = -20;
1796 /** The specified IP addresses are invalid. For example, the specified source IP address is
1797 * not configured on the specified {@code Network}. */
1798 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1799 /** The requested port is invalid. */
1800 public static final int ERROR_INVALID_PORT = -22;
1801 /** The packet length is invalid (e.g., too long). */
1802 public static final int ERROR_INVALID_LENGTH = -23;
1803 /** The packet transmission interval is invalid (e.g., too short). */
1804 public static final int ERROR_INVALID_INTERVAL = -24;
1805
1806 /** The hardware does not support this request. */
1807 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001808 /** The hardware returned an error. */
1809 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001810
Nathan Harold0990bc82018-02-14 13:09:45 -08001811 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001812 public static final int NATT_PORT = 4500;
1813
Nathan Harold0990bc82018-02-14 13:09:45 -08001814 /** The minimum interval in seconds between keepalive packet transmissions */
1815 public static final int MIN_INTERVAL = 10;
1816
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001817 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001818 private final ISocketKeepaliveCallback mCallback;
1819 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001820
1821 private volatile Integer mSlot;
1822
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001823 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001824 public void stop() {
1825 try {
junyulai070f9ff2019-01-16 20:23:34 +08001826 mExecutor.execute(() -> {
1827 try {
1828 if (mSlot != null) {
1829 mService.stopKeepalive(mNetwork, mSlot);
1830 }
1831 } catch (RemoteException e) {
1832 Log.e(TAG, "Error stopping packet keepalive: ", e);
1833 throw e.rethrowFromSystemServer();
1834 }
1835 });
1836 } catch (RejectedExecutionException e) {
1837 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001838 }
1839 }
1840
1841 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09001842 Objects.requireNonNull(network, "network cannot be null");
1843 Objects.requireNonNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001844 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001845 mExecutor = Executors.newSingleThreadExecutor();
1846 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001847 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001848 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001849 final long token = Binder.clearCallingIdentity();
1850 try {
1851 mExecutor.execute(() -> {
1852 mSlot = slot;
1853 callback.onStarted();
1854 });
1855 } finally {
1856 Binder.restoreCallingIdentity(token);
1857 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001858 }
junyulai070f9ff2019-01-16 20:23:34 +08001859
1860 @Override
1861 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001862 final long token = Binder.clearCallingIdentity();
1863 try {
1864 mExecutor.execute(() -> {
1865 mSlot = null;
1866 callback.onStopped();
1867 });
1868 } finally {
1869 Binder.restoreCallingIdentity(token);
1870 }
junyulai070f9ff2019-01-16 20:23:34 +08001871 mExecutor.shutdown();
1872 }
1873
1874 @Override
1875 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001876 final long token = Binder.clearCallingIdentity();
1877 try {
1878 mExecutor.execute(() -> {
1879 mSlot = null;
1880 callback.onError(error);
1881 });
1882 } finally {
1883 Binder.restoreCallingIdentity(token);
1884 }
junyulai070f9ff2019-01-16 20:23:34 +08001885 mExecutor.shutdown();
1886 }
1887
1888 @Override
1889 public void onDataReceived() {
1890 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1891 // this callback when data is received.
1892 }
1893 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001894 }
1895 }
1896
1897 /**
1898 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1899 *
junyulai4c95b082018-12-27 17:25:29 +08001900 * @deprecated Use {@link #createSocketKeepalive} instead.
1901 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001902 * @hide
1903 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001904 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001905 public PacketKeepalive startNattKeepalive(
1906 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1907 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1908 final PacketKeepalive k = new PacketKeepalive(network, callback);
1909 try {
junyulai070f9ff2019-01-16 20:23:34 +08001910 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001911 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1912 } catch (RemoteException e) {
1913 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001914 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001915 }
1916 return k;
1917 }
1918
Chiachang Wang619319a2021-01-15 11:06:21 +08001919 // Construct an invalid fd.
1920 private ParcelFileDescriptor createInvalidFd() {
1921 final int invalidFd = -1;
1922 return ParcelFileDescriptor.adoptFd(invalidFd);
1923 }
1924
The Android Open Source Project28527d22009-03-03 19:31:44 -08001925 /**
junyulai4c95b082018-12-27 17:25:29 +08001926 * Request that keepalives be started on a IPsec NAT-T socket.
1927 *
1928 * @param network The {@link Network} the socket is on.
1929 * @param socket The socket that needs to be kept alive.
1930 * @param source The source address of the {@link UdpEncapsulationSocket}.
1931 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1932 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1933 * must run callback sequentially, otherwise the order of callbacks cannot be
1934 * guaranteed.
1935 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1936 * changes. Must be extended by applications that use this API.
1937 *
junyulai0835a1e2019-01-08 20:04:33 +08001938 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1939 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001940 **/
junyulai7e06ad42019-03-04 22:45:36 +08001941 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001942 @NonNull UdpEncapsulationSocket socket,
1943 @NonNull InetAddress source,
1944 @NonNull InetAddress destination,
1945 @NonNull @CallbackExecutor Executor executor,
1946 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001947 ParcelFileDescriptor dup;
1948 try {
junyulai828dad12019-03-27 11:00:37 +08001949 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1950 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001951 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1952 } catch (IOException ignored) {
1953 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1954 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001955 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001956 }
1957 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1958 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08001959 }
1960
1961 /**
1962 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1963 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1964 *
1965 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08001966 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1967 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1968 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08001969 * @param source The source address of the {@link UdpEncapsulationSocket}.
1970 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1971 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1972 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1973 * must run callback sequentially, otherwise the order of callbacks cannot be
1974 * guaranteed.
1975 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1976 * changes. Must be extended by applications that use this API.
1977 *
junyulai0835a1e2019-01-08 20:04:33 +08001978 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1979 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08001980 * @hide
1981 */
1982 @SystemApi
1983 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08001984 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1985 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08001986 @NonNull InetAddress source,
1987 @NonNull InetAddress destination,
1988 @NonNull @CallbackExecutor Executor executor,
1989 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001990 ParcelFileDescriptor dup;
1991 try {
junyulai828dad12019-03-27 11:00:37 +08001992 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08001993 dup = pfd.dup();
1994 } catch (IOException ignored) {
1995 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1996 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001997 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001998 }
1999 return new NattSocketKeepalive(mService, network, dup,
2000 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002001 }
2002
2003 /**
junyulai0835a1e2019-01-08 20:04:33 +08002004 * Request that keepalives be started on a TCP socket.
2005 * The socket must be established.
2006 *
2007 * @param network The {@link Network} the socket is on.
2008 * @param socket The socket that needs to be kept alive.
2009 * @param executor The executor on which callback will be invoked. This implementation assumes
2010 * the provided {@link Executor} runs the callbacks in sequence with no
2011 * concurrency. Failing this, no guarantee of correctness can be made. It is
2012 * the responsibility of the caller to ensure the executor provides this
2013 * guarantee. A simple way of creating such an executor is with the standard
2014 * tool {@code Executors.newSingleThreadExecutor}.
2015 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2016 * changes. Must be extended by applications that use this API.
2017 *
2018 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2019 * given socket.
2020 * @hide
2021 */
2022 @SystemApi
2023 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002024 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002025 @NonNull Socket socket,
2026 @NonNull Executor executor,
2027 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002028 ParcelFileDescriptor dup;
2029 try {
2030 dup = ParcelFileDescriptor.fromSocket(socket);
2031 } catch (UncheckedIOException ignored) {
2032 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2033 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002034 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002035 }
2036 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002037 }
2038
2039 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002040 * Ensure that a network route exists to deliver traffic to the specified
2041 * host via the specified network interface. An attempt to add a route that
2042 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002043 *
2044 * <p>This method requires the caller to hold either the
2045 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2046 * or the ability to modify system settings as determined by
2047 * {@link android.provider.Settings.System#canWrite}.</p>
2048 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002049 * @param networkType the type of the network over which traffic to the specified
2050 * host is to be routed
2051 * @param hostAddress the IP address of the host to which the route is desired
2052 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002053 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002054 * @deprecated Deprecated in favor of the
2055 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2056 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002057 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002058 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002059 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002060 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002061 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002062 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002063 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002064 }
2065
2066 /**
2067 * Ensure that a network route exists to deliver traffic to the specified
2068 * host via the specified network interface. An attempt to add a route that
2069 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002070 *
2071 * <p>This method requires the caller to hold either the
2072 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2073 * or the ability to modify system settings as determined by
2074 * {@link android.provider.Settings.System#canWrite}.</p>
2075 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002076 * @param networkType the type of the network over which traffic to the specified
2077 * host is to be routed
2078 * @param hostAddress the IP address of the host to which the route is desired
2079 * @return {@code true} on success, {@code false} on failure
2080 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002081 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002082 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002083 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002084 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002085 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002086 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002087 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002088 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002089 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2090 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002091 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002092 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002093 }
2094 }
2095
2096 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002097 * @return the context's attribution tag
2098 */
2099 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2100 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002101 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002102 }
2103
2104 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002105 * Returns the value of the setting for background data usage. If false,
2106 * applications should not use the network if the application is not in the
2107 * foreground. Developers should respect this setting, and check the value
2108 * of this before performing any background data operations.
2109 * <p>
2110 * All applications that have background services that use the network
2111 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002112 * <p>
Scott Main50589142011-10-06 18:32:43 -07002113 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002114 * background data depends on several combined factors, and this method will
2115 * always return {@code true}. Instead, when background data is unavailable,
2116 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002117 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002118 * @return Whether background data usage is allowed.
2119 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002120 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002121 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002122 // assume that background data is allowed; final authority is
2123 // NetworkInfo which may be blocked.
2124 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002125 }
2126
2127 /**
2128 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002129 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002130 * @param allowBackgroundData Whether an application should use data while
2131 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002132 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002133 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2134 * @see #getBackgroundDataSetting()
2135 * @hide
2136 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002137 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002138 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002139 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002140 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002141 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002142
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002143 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002144 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002145 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002146 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002147 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002148 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002149 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002150 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2151 if (tm != null) {
2152 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2153 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2154 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2155 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2156 + " retVal=" + retVal);
2157 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002158 }
Wink Saville689f7042014-12-05 11:10:30 -08002159 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002160 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002161 }
2162
The Android Open Source Project28527d22009-03-03 19:31:44 -08002163 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002164 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002165 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002166 */
2167 public interface OnNetworkActiveListener {
2168 /**
2169 * Called on the main thread of the process to report that the current data network
2170 * has become active, and it is now a good time to perform any pending network
2171 * operations. Note that this listener only tells you when the network becomes
2172 * active; if at any other time you want to know whether it is active (and thus okay
2173 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002174 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002175 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002176 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002177 }
2178
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002179 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002180 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002181
2182 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002183 * Start listening to reports when the system's default data network is active, meaning it is
2184 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2185 * to determine the current state of the system's default network after registering the
2186 * listener.
2187 * <p>
2188 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002189 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002190 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002191 *
2192 * @param l The listener to be told when the network is active.
2193 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002194 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002195 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2196 @Override
2197 public void onNetworkActive() throws RemoteException {
2198 l.onNetworkActive();
2199 }
2200 };
2201
2202 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002203 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002204 mNetworkActivityListeners.put(l, rl);
2205 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002206 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002207 }
2208 }
2209
2210 /**
2211 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002212 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002213 *
2214 * @param l Previously registered listener.
2215 */
Chalard Jean158702d2019-01-07 19:26:34 +09002216 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002217 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09002218 if (rl == null) {
2219 throw new IllegalArgumentException("Listener was not registered.");
2220 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002221 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002222 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002223 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002224 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002225 }
2226 }
2227
2228 /**
2229 * Return whether the data network is currently active. An active network means that
2230 * it is currently in a high power state for performing data transmission. On some
2231 * types of networks, it may be expensive to move and stay in such a state, so it is
2232 * more power efficient to batch network traffic together when the radio is already in
2233 * this state. This method tells you whether right now is currently a good time to
2234 * initiate network traffic, as the network is already active.
2235 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002236 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002237 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002238 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002239 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002240 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002241 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002242 }
2243
2244 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002245 * {@hide}
2246 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002247 public ConnectivityManager(Context context, IConnectivityManager service) {
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09002248 mContext = Objects.requireNonNull(context, "missing context");
2249 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002250 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002251 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002252 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002253
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002254 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002255 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002256 public static ConnectivityManager from(Context context) {
2257 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2258 }
2259
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002260 /** @hide */
2261 public NetworkRequest getDefaultRequest() {
2262 try {
2263 // This is not racy as the default request is final in ConnectivityService.
2264 return mService.getDefaultRequest();
2265 } catch (RemoteException e) {
2266 throw e.rethrowFromSystemServer();
2267 }
2268 }
2269
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002270 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002271 * Check if the package is a allowed to write settings. This also accounts that such an access
2272 * happened.
2273 *
2274 * @return {@code true} iff the package is allowed to write settings.
2275 */
2276 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2277 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2278 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2279 boolean throwException) {
2280 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2281 throwException);
2282 }
2283
2284 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002285 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2286 * situations where a Context pointer is unavailable.
2287 * @hide
2288 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002289 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002290 static ConnectivityManager getInstanceOrNull() {
2291 return sInstance;
2292 }
2293
2294 /**
2295 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2296 * situations where a Context pointer is unavailable.
2297 * @hide
2298 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002299 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002300 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002301 private static ConnectivityManager getInstance() {
2302 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002303 throw new IllegalStateException("No ConnectivityManager yet constructed");
2304 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002305 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002306 }
2307
2308 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002309 * Get the set of tetherable, available interfaces. This list is limited by
2310 * device configuration and current interface existence.
2311 *
2312 * @return an array of 0 or more Strings of tetherable interface names.
2313 *
markchien6ae63e52020-01-21 13:11:06 +08002314 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002315 * {@hide}
2316 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002317 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002318 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002319 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002320 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002321 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002322 }
2323
2324 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002325 * Get the set of tethered interfaces.
2326 *
2327 * @return an array of 0 or more String of currently tethered interface names.
2328 *
markchien6ae63e52020-01-21 13:11:06 +08002329 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002330 * {@hide}
2331 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002332 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002333 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002334 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002335 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002336 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002337 }
2338
2339 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002340 * Get the set of interface names which attempted to tether but
2341 * failed. Re-attempting to tether may cause them to reset to the Tethered
2342 * state. Alternatively, causing the interface to be destroyed and recreated
2343 * may cause them to reset to the available state.
2344 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2345 * information on the cause of the errors.
2346 *
2347 * @return an array of 0 or more String indicating the interface names
2348 * which failed to tether.
2349 *
markchien6ae63e52020-01-21 13:11:06 +08002350 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002351 * {@hide}
2352 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002353 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002354 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002355 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002356 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002357 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002358 }
2359
2360 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002361 * Get the set of tethered dhcp ranges.
2362 *
markchien2e6ba522020-02-14 11:55:48 +08002363 * @deprecated This method is not supported.
2364 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002365 * {@hide}
2366 */
paulhu8e96a752019-08-12 16:25:11 +08002367 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002368 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002369 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002370 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002371 }
2372
2373 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002374 * Attempt to tether the named interface. This will setup a dhcp server
2375 * on the interface, forward and NAT IP packets and forward DNS requests
2376 * to the best active upstream network interface. Note that if no upstream
2377 * IP network interface is available, dhcp will still run and traffic will be
2378 * allowed between the tethered devices and this device, though upstream net
2379 * access will of course fail until an upstream network interface becomes
2380 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002381 *
2382 * <p>This method requires the caller to hold either the
2383 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2384 * or the ability to modify system settings as determined by
2385 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002386 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002387 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2388 * and WifiStateMachine which need direct access. All other clients should use
2389 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2390 * logic.</p>
2391 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002392 * @param iface the interface name to tether.
2393 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002394 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002395 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002396 * {@hide}
2397 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002398 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002399 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002400 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002401 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002402 }
2403
2404 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002405 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002406 *
2407 * <p>This method requires the caller to hold either the
2408 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2409 * or the ability to modify system settings as determined by
2410 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002411 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002412 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2413 * and WifiStateMachine which need direct access. All other clients should use
2414 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2415 * logic.</p>
2416 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002417 * @param iface the interface name to untether.
2418 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2419 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002420 * {@hide}
2421 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002422 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002423 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002424 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002425 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002426 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002427
2428 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002429 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002430 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002431 * due to device configuration.
2432 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002433 * <p>If this app does not have permission to use this API, it will always
2434 * return false rather than throw an exception.</p>
2435 *
2436 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2437 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2438 *
2439 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2440 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2441 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002442 * @return a boolean - {@code true} indicating Tethering is supported.
2443 *
markchien6ae63e52020-01-21 13:11:06 +08002444 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002445 * {@hide}
2446 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002447 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002448 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2449 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002450 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002451 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002452 }
2453
2454 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002455 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002456 *
2457 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002458 * @hide
2459 */
2460 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002461 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002462 public static abstract class OnStartTetheringCallback {
2463 /**
2464 * Called when tethering has been successfully started.
2465 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002466 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002467
2468 /**
2469 * Called when starting tethering failed.
2470 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002471 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002472 }
2473
2474 /**
2475 * Convenient overload for
2476 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2477 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002478 *
2479 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002480 * @hide
2481 */
2482 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002483 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002484 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002485 public void startTethering(int type, boolean showProvisioningUi,
2486 final OnStartTetheringCallback callback) {
2487 startTethering(type, showProvisioningUi, callback, null);
2488 }
2489
2490 /**
2491 * Runs tether provisioning for the given type if needed and then starts tethering if
2492 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2493 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2494 * schedules tether provisioning re-checks if appropriate.
2495 *
2496 * @param type The type of tethering to start. Must be one of
2497 * {@link ConnectivityManager.TETHERING_WIFI},
2498 * {@link ConnectivityManager.TETHERING_USB}, or
2499 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2500 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2501 * is one. This should be true the first time this function is called and also any time
2502 * the user can see this UI. It gives users information from their carrier about the
2503 * check failing and how they can sign up for tethering if possible.
2504 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2505 * of the result of trying to tether.
2506 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002507 *
2508 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002509 * @hide
2510 */
2511 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002512 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002513 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002514 public void startTethering(int type, boolean showProvisioningUi,
2515 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09002516 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002517
markchien91c78e52020-01-20 19:31:56 +08002518 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002519 @Override
markchien91c78e52020-01-20 19:31:56 +08002520 public void execute(Runnable command) {
2521 if (handler == null) {
2522 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002523 } else {
markchien91c78e52020-01-20 19:31:56 +08002524 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002525 }
2526 }
2527 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002528
markchien91c78e52020-01-20 19:31:56 +08002529 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2530 @Override
2531 public void onTetheringStarted() {
2532 callback.onTetheringStarted();
2533 }
2534
2535 @Override
markchienf47d8342020-03-19 13:37:43 +08002536 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002537 callback.onTetheringFailed();
2538 }
2539 };
2540
2541 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002542 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002543
Amos Bianchia9b415a2020-03-04 11:07:38 -08002544 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002545 }
2546
2547 /**
2548 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2549 * applicable.
2550 *
2551 * @param type The type of tethering to stop. Must be one of
2552 * {@link ConnectivityManager.TETHERING_WIFI},
2553 * {@link ConnectivityManager.TETHERING_USB}, or
2554 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002555 *
2556 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002557 * @hide
2558 */
2559 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002560 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002561 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002562 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002563 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002564 }
2565
2566 /**
markchien4ef53e82019-02-27 14:56:11 +08002567 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2568 * upstream status.
2569 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002570 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002571 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002572 */
2573 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002574 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002575 public abstract static class OnTetheringEventCallback {
2576
2577 /**
2578 * Called when tethering upstream changed. This can be called multiple times and can be
2579 * called any time.
2580 *
2581 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2582 * have any upstream.
2583 */
2584 public void onUpstreamChanged(@Nullable Network network) {}
2585 }
2586
markchien6ae63e52020-01-21 13:11:06 +08002587 @GuardedBy("mTetheringEventCallbacks")
2588 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2589 mTetheringEventCallbacks = new ArrayMap<>();
2590
markchien4ef53e82019-02-27 14:56:11 +08002591 /**
2592 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002593 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002594 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2595 * with a null argument. The same callback object cannot be registered twice.
2596 *
2597 * @param executor the executor on which callback will be invoked.
2598 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002599 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002600 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002601 * @hide
2602 */
2603 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002604 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002605 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2606 public void registerTetheringEventCallback(
2607 @NonNull @CallbackExecutor Executor executor,
2608 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09002609 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
markchien4ef53e82019-02-27 14:56:11 +08002610
markchien6ae63e52020-01-21 13:11:06 +08002611 final TetheringEventCallback tetherCallback =
2612 new TetheringEventCallback() {
2613 @Override
2614 public void onUpstreamChanged(@Nullable Network network) {
2615 callback.onUpstreamChanged(network);
2616 }
2617 };
2618
2619 synchronized (mTetheringEventCallbacks) {
2620 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002621 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002622 }
markchien4ef53e82019-02-27 14:56:11 +08002623 }
2624
2625 /**
2626 * Remove tethering event callback previously registered with
2627 * {@link #registerTetheringEventCallback}.
2628 *
2629 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002630 *
2631 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002632 * @hide
2633 */
2634 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002635 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002636 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2637 public void unregisterTetheringEventCallback(
2638 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002639 Objects.requireNonNull(callback, "The callback must be non-null");
2640 synchronized (mTetheringEventCallbacks) {
2641 final TetheringEventCallback tetherCallback =
2642 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002643 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002644 }
markchien4ef53e82019-02-27 14:56:11 +08002645 }
2646
2647
2648 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002649 * Get the list of regular expressions that define any tetherable
2650 * USB network interfaces. If USB tethering is not supported by the
2651 * device, this list should be empty.
2652 *
2653 * @return an array of 0 or more regular expression Strings defining
2654 * what interfaces are considered tetherable usb interfaces.
2655 *
markchien6ae63e52020-01-21 13:11:06 +08002656 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002657 * {@hide}
2658 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002659 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002660 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002661 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002662 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002663 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002664 }
2665
2666 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002667 * Get the list of regular expressions that define any tetherable
2668 * Wifi network interfaces. If Wifi tethering is not supported by the
2669 * device, this list should be empty.
2670 *
2671 * @return an array of 0 or more regular expression Strings defining
2672 * what interfaces are considered tetherable wifi interfaces.
2673 *
markchien6ae63e52020-01-21 13:11:06 +08002674 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002675 * {@hide}
2676 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002677 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002678 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002679 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002680 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002681 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002682 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002683
Danica Chang96567052010-08-11 14:54:43 -07002684 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002685 * Get the list of regular expressions that define any tetherable
2686 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2687 * device, this list should be empty.
2688 *
2689 * @return an array of 0 or more regular expression Strings defining
2690 * what interfaces are considered tetherable bluetooth interfaces.
2691 *
markchien6ae63e52020-01-21 13:11:06 +08002692 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2693 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002694 * {@hide}
2695 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002696 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002697 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002698 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002699 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002700 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002701 }
2702
Mike Lockwooded4a1742011-07-19 13:04:47 -07002703 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002704 * Attempt to both alter the mode of USB and Tethering of USB. A
2705 * utility method to deal with some of the complexity of USB - will
2706 * attempt to switch to Rndis and subsequently tether the resulting
2707 * interface on {@code true} or turn off tethering and switch off
2708 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002709 *
2710 * <p>This method requires the caller to hold either the
2711 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2712 * or the ability to modify system settings as determined by
2713 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002714 *
2715 * @param enable a boolean - {@code true} to enable tethering
2716 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002717 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002718 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002719 * {@hide}
2720 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002721 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002722 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002723 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002724 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002725 }
2726
markchien6ae63e52020-01-21 13:11:06 +08002727 /**
2728 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2729 * {@hide}
2730 */
markchien0f45bb92019-01-16 17:44:13 +08002731 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002732 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002733 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002734 /**
2735 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2736 * {@hide}
2737 */
2738 @Deprecated
2739 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2740 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2741 /**
2742 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2743 * {@hide}
2744 */
2745 @Deprecated
2746 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2747 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2748 /**
2749 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2750 * {@hide}
2751 */
2752 @Deprecated
2753 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2754 /**
2755 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2756 * {@hide}
2757 */
2758 @Deprecated
2759 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2760 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2761 /**
markchienf47d8342020-03-19 13:37:43 +08002762 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002763 * {@hide}
2764 */
2765 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002766 public static final int TETHER_ERROR_MASTER_ERROR =
2767 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002768 /**
2769 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2770 * {@hide}
2771 */
2772 @Deprecated
2773 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2774 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2775 /**
2776 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2777 * {@hide}
2778 */
2779 @Deprecated
2780 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2781 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2782 /**
markchienf47d8342020-03-19 13:37:43 +08002783 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002784 * {@hide}
2785 */
2786 @Deprecated
2787 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002788 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002789 /**
markchienf47d8342020-03-19 13:37:43 +08002790 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002791 * {@hide}
2792 */
2793 @Deprecated
2794 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002795 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002796 /**
2797 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2798 * {@hide}
2799 */
2800 @Deprecated
2801 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2802 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2803 /**
markchienf47d8342020-03-19 13:37:43 +08002804 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002805 * {@hide}
2806 */
markchien0f45bb92019-01-16 17:44:13 +08002807 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002808 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002809 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002810 /**
2811 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2812 * {@hide}
2813 */
2814 @Deprecated
2815 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2816 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2817 /**
2818 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2819 * {@hide}
2820 */
markchien0f45bb92019-01-16 17:44:13 +08002821 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002822 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002823 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002824
2825 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002826 * Get a more detailed error code after a Tethering or Untethering
2827 * request asynchronously failed.
2828 *
2829 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002830 * @return error The error code of the last error tethering or untethering the named
2831 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002832 *
markchien6ae63e52020-01-21 13:11:06 +08002833 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002834 * {@hide}
2835 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002836 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002837 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002838 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002839 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002840 int error = mTetheringManager.getLastTetherError(iface);
2841 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2842 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2843 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2844 // instead.
2845 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2846 }
2847 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002848 }
2849
markchienbf5ab012019-03-06 16:25:00 +08002850 /** @hide */
2851 @Retention(RetentionPolicy.SOURCE)
2852 @IntDef(value = {
2853 TETHER_ERROR_NO_ERROR,
2854 TETHER_ERROR_PROVISION_FAILED,
2855 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2856 })
2857 public @interface EntitlementResultCode {
2858 }
2859
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002860 /**
markchienbf5ab012019-03-06 16:25:00 +08002861 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002862 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002863 *
2864 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002865 * @hide
2866 */
2867 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002868 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002869 public interface OnTetheringEntitlementResultListener {
2870 /**
2871 * Called to notify entitlement result.
2872 *
2873 * @param resultCode an int value of entitlement result. It may be one of
2874 * {@link #TETHER_ERROR_NO_ERROR},
2875 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2876 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2877 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002878 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002879 }
2880
2881 /**
markchien0f45bb92019-01-16 17:44:13 +08002882 * Get the last value of the entitlement check on this downstream. If the cached value is
2883 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2884 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2885 * guaranteed that the UI-based entitlement check will complete in any specific time period
2886 * and may in fact never complete. Any successful entitlement check the platform performs for
2887 * any reason will update the cached value.
2888 *
2889 * @param type the downstream type of tethering. Must be one of
2890 * {@link #TETHERING_WIFI},
2891 * {@link #TETHERING_USB}, or
2892 * {@link #TETHERING_BLUETOOTH}.
2893 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002894 * @param executor the executor on which callback will be invoked.
2895 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2896 * notify the caller of the result of entitlement check. The listener may be called zero
2897 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002898 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002899 * {@hide}
2900 */
2901 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002902 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002903 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002904 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2905 @NonNull @CallbackExecutor Executor executor,
2906 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09002907 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
markchienbf5ab012019-03-06 16:25:00 +08002908 ResultReceiver wrappedListener = new ResultReceiver(null) {
2909 @Override
2910 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08002911 final long token = Binder.clearCallingIdentity();
2912 try {
2913 executor.execute(() -> {
2914 listener.onTetheringEntitlementResult(resultCode);
2915 });
2916 } finally {
2917 Binder.restoreCallingIdentity(token);
2918 }
markchienbf5ab012019-03-06 16:25:00 +08002919 }
2920 };
2921
Amos Bianchia9b415a2020-03-04 11:07:38 -08002922 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002923 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002924 }
2925
2926 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002927 * Report network connectivity status. This is currently used only
2928 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002929 * <p>This method requires the caller to hold the permission
2930 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002931 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002932 * @param networkType The type of network you want to report on
2933 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002934 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002935 * {@hide}
2936 */
2937 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002938 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002939 try {
2940 mService.reportInetCondition(networkType, percentage);
2941 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002942 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002943 }
2944 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002945
2946 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002947 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07002948 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002949 * the framework to re-evaluate network connectivity and/or switch to another
2950 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002951 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002952 * @param network The {@link Network} the application was attempting to use
2953 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04002954 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2955 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002956 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002957 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09002958 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002959 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002960 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04002961 // One of these will be ignored because it matches system's current state.
2962 // The other will trigger the necessary reevaluation.
2963 mService.reportNetworkConnectivity(network, true);
2964 mService.reportNetworkConnectivity(network, false);
2965 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002966 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04002967 }
2968 }
2969
2970 /**
2971 * Report to the framework whether a network has working connectivity.
2972 * This provides a hint to the system that a particular network is providing
2973 * working connectivity or not. In response the framework may re-evaluate
2974 * the network's connectivity and might take further action thereafter.
2975 *
2976 * @param network The {@link Network} the application was attempting to use
2977 * or {@code null} to indicate the current default network.
2978 * @param hasConnectivity {@code true} if the application was able to successfully access the
2979 * Internet using {@code network} or {@code false} if not.
2980 */
Chalard Jean158702d2019-01-07 19:26:34 +09002981 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002982 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04002983 try {
2984 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002985 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002986 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002987 }
2988 }
2989
2990 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002991 * Set a network-independent global http proxy. This is not normally what you want
2992 * for typical HTTP proxies - they are general network dependent. However if you're
2993 * doing something unusual like general internal filtering this may be useful. On
2994 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002995 *
2996 * @param p A {@link ProxyInfo} object defining the new global
2997 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002998 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002999 */
paulhu8e96a752019-08-12 16:25:11 +08003000 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04003001 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003002 try {
3003 mService.setGlobalProxy(p);
3004 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003005 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003006 }
3007 }
3008
3009 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003010 * Retrieve any network-independent global HTTP proxy.
3011 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003012 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003013 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003014 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003015 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003016 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003017 try {
3018 return mService.getGlobalProxy();
3019 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003020 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003021 }
3022 }
3023
3024 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003025 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3026 * network-specific HTTP proxy. If {@code network} is null, the
3027 * network-specific proxy returned is the proxy of the default active
3028 * network.
3029 *
3030 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3031 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3032 * or when {@code network} is {@code null},
3033 * the {@code ProxyInfo} for the default active network. Returns
3034 * {@code null} when no proxy applies or the caller doesn't have
3035 * permission to use {@code network}.
3036 * @hide
3037 */
3038 public ProxyInfo getProxyForNetwork(Network network) {
3039 try {
3040 return mService.getProxyForNetwork(network);
3041 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003042 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003043 }
3044 }
3045
3046 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003047 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3048 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003049 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003050 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003051 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003052 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003053 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003054 */
Chalard Jean158702d2019-01-07 19:26:34 +09003055 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003056 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003057 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003058 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003059
3060 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003061 * Returns true if the hardware supports the given network type
3062 * else it returns false. This doesn't indicate we have coverage
3063 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003064 * hardware supports it. For example a GSM phone without a SIM
3065 * should still return {@code true} for mobile data, but a wifi only
3066 * tablet would return {@code false}.
3067 *
3068 * @param networkType The network type we'd like to check
3069 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003070 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003071 * @hide
3072 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003073 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003074 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003075 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003076 public boolean isNetworkSupported(int networkType) {
3077 try {
3078 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003079 } catch (RemoteException e) {
3080 throw e.rethrowFromSystemServer();
3081 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003082 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003083
3084 /**
3085 * Returns if the currently active data network is metered. A network is
3086 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003087 * that connection due to monetary costs, data limitations or
3088 * battery/performance issues. You should check this before doing large
3089 * data transfers, and warn the user or delay the operation until another
3090 * network is available.
3091 *
3092 * @return {@code true} if large transfers should be avoided, otherwise
3093 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003094 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003095 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003096 public boolean isActiveNetworkMetered() {
3097 try {
3098 return mService.isActiveNetworkMetered();
3099 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003100 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003101 }
3102 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003103
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003104 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003105 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003106 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003107 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003108 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003109 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003110 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003111 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003112 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003113 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003114 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003115 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003116 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003117 }
3118 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003119
3120 /**
3121 * Set the value for enabling/disabling airplane mode
3122 *
3123 * @param enable whether to enable airplane mode or not
3124 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003125 * @hide
3126 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003127 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003128 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003129 android.Manifest.permission.NETWORK_SETTINGS,
3130 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3131 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003132 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003133 public void setAirplaneMode(boolean enable) {
3134 try {
3135 mService.setAirplaneMode(enable);
3136 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003137 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003138 }
3139 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003140
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003141 /**
3142 * Registers the specified {@link NetworkProvider}.
3143 * Each listener must only be registered once. The listener can be unregistered with
3144 * {@link #unregisterNetworkProvider}.
3145 *
3146 * @param provider the provider to register
3147 * @return the ID of the provider. This ID must be used by the provider when registering
3148 * {@link android.net.NetworkAgent}s.
3149 * @hide
3150 */
3151 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003152 @RequiresPermission(anyOf = {
3153 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3154 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003155 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3156 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003157 throw new IllegalStateException("NetworkProviders can only be registered once");
3158 }
3159
3160 try {
3161 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3162 provider.getName());
3163 provider.setProviderId(providerId);
3164 } catch (RemoteException e) {
3165 throw e.rethrowFromSystemServer();
3166 }
3167 return provider.getProviderId();
3168 }
3169
3170 /**
3171 * Unregisters the specified NetworkProvider.
3172 *
3173 * @param provider the provider to unregister
3174 * @hide
3175 */
3176 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003177 @RequiresPermission(anyOf = {
3178 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3179 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003180 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3181 try {
3182 mService.unregisterNetworkProvider(provider.getMessenger());
3183 } catch (RemoteException e) {
3184 throw e.rethrowFromSystemServer();
3185 }
3186 provider.setProviderId(NetworkProvider.ID_NONE);
3187 }
3188
3189
3190 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003191 @RequiresPermission(anyOf = {
3192 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3193 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003194 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3195 try {
3196 mService.declareNetworkRequestUnfulfillable(request);
3197 } catch (RemoteException e) {
3198 throw e.rethrowFromSystemServer();
3199 }
3200 }
3201
Chalard Jean29d06db2018-05-02 21:14:54 +09003202 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3203 // of dependent changes that would conflict throughout the automerger graph. Having this
3204 // temporarily helps with the process of going through with all these dependent changes across
3205 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003206 /**
3207 * @hide
3208 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003209 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003210 */
paulhub6ba8e82020-03-04 09:43:41 +08003211 @RequiresPermission(anyOf = {
3212 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3213 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003214 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003215 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003216 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003217 }
3218
3219 /**
3220 * @hide
3221 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003222 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003223 */
paulhub6ba8e82020-03-04 09:43:41 +08003224 @RequiresPermission(anyOf = {
3225 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3226 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003227 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003228 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003229 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003230 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003231 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003232 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003233 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003234 }
3235
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003236 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003237 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3238 * changes. Should be extended by applications wanting notifications.
3239 *
3240 * A {@code NetworkCallback} is registered by calling
3241 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3242 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003243 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003244 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3245 * A {@code NetworkCallback} should be registered at most once at any time.
3246 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003247 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003248 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003249 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003250 * Called when the framework connects to a new network to evaluate whether it satisfies this
3251 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3252 * callback. There is no guarantee that this new network will satisfy any requests, or that
3253 * the network will stay connected for longer than the time necessary to evaluate it.
3254 * <p>
3255 * Most applications <b>should not</b> act on this callback, and should instead use
3256 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3257 * the framework in properly evaluating the network &mdash; for example, an application that
3258 * can automatically log in to a captive portal without user intervention.
3259 *
3260 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003261 *
3262 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003263 */
paulhu1a407652019-03-22 16:35:06 +08003264 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003265
3266 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003267 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003268 * This callback may be called more than once if the {@link Network} that is
3269 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003270 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003271 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003272 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3273 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003274 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003275 * @hide
3276 */
paulhu1a407652019-03-22 16:35:06 +08003277 public void onAvailable(@NonNull Network network,
3278 @NonNull NetworkCapabilities networkCapabilities,
3279 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003280 // Internally only this method is called when a new network is available, and
3281 // it calls the callback in the same way and order that older versions used
3282 // to call so as not to change the behavior.
3283 onAvailable(network);
3284 if (!networkCapabilities.hasCapability(
3285 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3286 onNetworkSuspended(network);
3287 }
3288 onCapabilitiesChanged(network, networkCapabilities);
3289 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003290 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003291 }
3292
3293 /**
3294 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003295 *
3296 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3297 * be available at the same time, and onAvailable will be called for each of these as they
3298 * appear.
3299 *
3300 * <p>For callbacks registered with {@link #requestNetwork} and
3301 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3302 * is the new best network for this request and is now tracked by this callback ; this
3303 * callback will no longer receive method calls about other networks that may have been
3304 * passed to this method previously. The previously-best network may have disconnected, or
3305 * it may still be around and the newly-best network may simply be better.
3306 *
3307 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3308 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3309 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3310 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3311 *
3312 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3313 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3314 * this callback as this is prone to race conditions (there is no guarantee the objects
3315 * returned by these methods will be current). Instead, wait for a call to
3316 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3317 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3318 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003319 *
3320 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003321 */
paulhu1a407652019-03-22 16:35:06 +08003322 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003323
3324 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003325 * Called when the network is about to be lost, typically because there are no outstanding
3326 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3327 * with the new replacement network for graceful handover. This method is not guaranteed
3328 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3329 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003330 *
Chalard Jean01378b62019-08-30 16:27:28 +09003331 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3332 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3333 * this callback as this is prone to race conditions ; calling these methods while in a
3334 * callback may return an outdated or even a null object.
3335 *
3336 * @param network The {@link Network} that is about to be lost.
3337 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3338 * connected for graceful handover; note that the network may still
3339 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003340 */
paulhu1a407652019-03-22 16:35:06 +08003341 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003342
3343 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003344 * Called when a network disconnects or otherwise no longer satisfies this request or
3345 * callback.
3346 *
3347 * <p>If the callback was registered with requestNetwork() or
3348 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3349 * returned by onAvailable() when that network is lost and no other network satisfies
3350 * the criteria of the request.
3351 *
3352 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3353 * each network which no longer satisfies the criteria of the callback.
3354 *
3355 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3356 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3357 * this callback as this is prone to race conditions ; calling these methods while in a
3358 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003359 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003360 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003361 */
paulhu1a407652019-03-22 16:35:06 +08003362 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003363
3364 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003365 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003366 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3367 * requested network request cannot be fulfilled (whether or not a timeout was
3368 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003369 * {@link NetworkRequest} will have already been removed and released, as if
3370 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003371 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003372 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003373
3374 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003375 * Called when the network corresponding to this request changes capabilities but still
3376 * satisfies the requested criteria.
3377 *
3378 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3379 * to be called immediately after {@link #onAvailable}.
3380 *
3381 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3382 * ConnectivityManager methods in this callback as this is prone to race conditions :
3383 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003384 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003385 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003386 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3387 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003388 */
paulhu1a407652019-03-22 16:35:06 +08003389 public void onCapabilitiesChanged(@NonNull Network network,
3390 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003391
3392 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003393 * Called when the network corresponding to this request changes {@link LinkProperties}.
3394 *
3395 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3396 * to be called immediately after {@link #onAvailable}.
3397 *
3398 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3399 * ConnectivityManager methods in this callback as this is prone to race conditions :
3400 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003401 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003402 * @param network The {@link Network} whose link properties have changed.
3403 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003404 */
paulhu1a407652019-03-22 16:35:06 +08003405 public void onLinkPropertiesChanged(@NonNull Network network,
3406 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003407
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003408 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003409 * Called when the network the framework connected to for this request suspends data
3410 * transmission temporarily.
3411 *
3412 * <p>This generally means that while the TCP connections are still live temporarily
3413 * network data fails to transfer. To give a specific example, this is used on cellular
3414 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3415 * means read operations on sockets on this network will block once the buffers are
3416 * drained, and write operations will block once the buffers are full.
3417 *
3418 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3419 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3420 * this callback as this is prone to race conditions (there is no guarantee the objects
3421 * returned by these methods will be current).
3422 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003423 * @hide
3424 */
paulhu1a407652019-03-22 16:35:06 +08003425 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003426
3427 /**
3428 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003429 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3430 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003431
3432 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3433 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3434 * this callback as this is prone to race conditions : calling these methods while in a
3435 * callback may return an outdated or even a null object.
3436 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003437 * @hide
3438 */
paulhu1a407652019-03-22 16:35:06 +08003439 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003440
junyulaif2c67e42018-08-07 19:50:45 +08003441 /**
3442 * Called when access to the specified network is blocked or unblocked.
3443 *
Chalard Jean01378b62019-08-30 16:27:28 +09003444 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3445 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3446 * this callback as this is prone to race conditions : calling these methods while in a
3447 * callback may return an outdated or even a null object.
3448 *
junyulaif2c67e42018-08-07 19:50:45 +08003449 * @param network The {@link Network} whose blocked status has changed.
3450 * @param blocked The blocked status of this {@link Network}.
3451 */
junyulai7e06ad42019-03-04 22:45:36 +08003452 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003453
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003454 private NetworkRequest networkRequest;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003455 }
3456
Hugo Benichia590ab82017-05-11 13:16:17 +09003457 /**
3458 * Constant error codes used by ConnectivityService to communicate about failures and errors
3459 * across a Binder boundary.
3460 * @hide
3461 */
3462 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003463 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003464 }
3465
3466 /** @hide */
3467 public static class TooManyRequestsException extends RuntimeException {}
3468
3469 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3470 switch (e.errorCode) {
3471 case Errors.TOO_MANY_REQUESTS:
3472 return new TooManyRequestsException();
3473 default:
3474 Log.w(TAG, "Unknown service error code " + e.errorCode);
3475 return new RuntimeException(e);
3476 }
3477 }
3478
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003479 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003480 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003481 public static final int CALLBACK_PRECHECK = BASE + 1;
3482 /** @hide */
3483 public static final int CALLBACK_AVAILABLE = BASE + 2;
3484 /** @hide arg1 = TTL */
3485 public static final int CALLBACK_LOSING = BASE + 3;
3486 /** @hide */
3487 public static final int CALLBACK_LOST = BASE + 4;
3488 /** @hide */
3489 public static final int CALLBACK_UNAVAIL = BASE + 5;
3490 /** @hide */
3491 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3492 /** @hide */
3493 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003494 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003495 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003496 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003497 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003498 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003499 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003500 /** @hide */
3501 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003502
Erik Kline155a59a2015-11-25 12:49:38 +09003503 /** @hide */
3504 public static String getCallbackName(int whichCallback) {
3505 switch (whichCallback) {
3506 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3507 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3508 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3509 case CALLBACK_LOST: return "CALLBACK_LOST";
3510 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3511 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3512 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003513 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3514 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3515 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003516 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003517 default:
3518 return Integer.toString(whichCallback);
3519 }
3520 }
3521
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003522 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003523 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003524 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003525
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003526 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003527 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003528 }
3529
Hugo Benichifd44e912017-02-02 17:02:36 +09003530 CallbackHandler(Handler handler) {
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09003531 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003532 }
3533
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003534 @Override
3535 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003536 if (message.what == EXPIRE_LEGACY_REQUEST) {
3537 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3538 return;
3539 }
3540
3541 final NetworkRequest request = getObject(message, NetworkRequest.class);
3542 final Network network = getObject(message, Network.class);
3543 final NetworkCallback callback;
3544 synchronized (sCallbacks) {
3545 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003546 if (callback == null) {
3547 Log.w(TAG,
3548 "callback not found for " + getCallbackName(message.what) + " message");
3549 return;
3550 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003551 if (message.what == CALLBACK_UNAVAIL) {
3552 sCallbacks.remove(request);
3553 callback.networkRequest = ALREADY_UNREGISTERED;
3554 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003555 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003556 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003557 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003558 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003559
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003560 switch (message.what) {
3561 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003562 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003563 break;
3564 }
3565 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003566 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3567 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003568 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003569 break;
3570 }
3571 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003572 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003573 break;
3574 }
3575 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003576 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003577 break;
3578 }
3579 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003580 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003581 break;
3582 }
3583 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003584 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3585 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003586 break;
3587 }
3588 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003589 LinkProperties lp = getObject(message, LinkProperties.class);
3590 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003591 break;
3592 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003593 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003594 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003595 break;
3596 }
3597 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003598 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003599 break;
3600 }
junyulaif2c67e42018-08-07 19:50:45 +08003601 case CALLBACK_BLK_CHANGED: {
3602 boolean blocked = message.arg1 != 0;
3603 callback.onBlockedStatusChanged(network, blocked);
3604 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003605 }
3606 }
3607
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003608 private <T> T getObject(Message msg, Class<T> c) {
3609 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003610 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003611 }
3612
Hugo Benichifd44e912017-02-02 17:02:36 +09003613 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003614 synchronized (sCallbacks) {
3615 if (sCallbackHandler == null) {
3616 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003617 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003618 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003619 }
3620 }
3621
Hugo Benichibc4ac972017-02-03 14:18:44 +09003622 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3623 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003624
Hugo Benichibc4ac972017-02-03 14:18:44 +09003625 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003626 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003627 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003628 checkCallbackNotNull(callback);
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09003629 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
3630 throw new IllegalArgumentException("null NetworkCapabilities");
3631 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003632 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003633 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003634 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003635 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003636 if (callback.networkRequest != null
3637 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003638 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3639 // and requests (http://b/20701525).
3640 Log.e(TAG, "NetworkCallback was already registered");
3641 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003642 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003643 Binder binder = new Binder();
junyulaiad010792021-01-11 16:53:38 +08003644 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003645 request = mService.listenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003646 need, messenger, binder, callingPackageName,
3647 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003648 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003649 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003650 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3651 callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003652 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003653 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003654 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003655 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003656 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003657 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003658 } catch (RemoteException e) {
3659 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003660 } catch (ServiceSpecificException e) {
3661 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003662 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003663 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003664 }
3665
3666 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003667 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003668 *
markchienfac84a22020-03-18 21:16:15 +08003669 * This API is only for use in internal system code that requests networks with legacy type and
3670 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003671 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003672 *
markchiend6eeffd2020-01-14 00:55:21 +08003673 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003674 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3675 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3676 * be a positive value (i.e. >0).
3677 * @param legacyType to specify the network type(#TYPE_*).
3678 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003679 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3680 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003681 *
3682 * @hide
3683 */
markchiend6eeffd2020-01-14 00:55:21 +08003684 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003685 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003686 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003687 int timeoutMs, int legacyType, @NonNull Handler handler,
3688 @NonNull NetworkCallback networkCallback) {
3689 if (legacyType == TYPE_NONE) {
3690 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3691 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003692 CallbackHandler cbHandler = new CallbackHandler(handler);
3693 NetworkCapabilities nc = request.networkCapabilities;
3694 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003695 }
3696
3697 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003698 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003699 *
Chalard Jean01378b62019-08-30 16:27:28 +09003700 * <p>This method will attempt to find the best network that matches the passed
3701 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3702 * criteria. The platform will evaluate which network is the best at its own discretion.
3703 * Throughput, latency, cost per byte, policy, user preference and other considerations
3704 * may be factored in the decision of what is considered the best network.
3705 *
3706 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3707 * matching this request, while always attempting to match the request to a better network if
3708 * possible. If a better match is found, the platform will switch this request to the now-best
3709 * network and inform the app of the newly best network by invoking
3710 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3711 * will not try to maintain any other network than the best one currently matching the request:
3712 * a network not matching any network request may be disconnected at any time.
3713 *
3714 * <p>For example, an application could use this method to obtain a connected cellular network
3715 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3716 * radio to consume additional power. Or, an application could inform the system that it wants
3717 * a network supporting sending MMSes and have the system let it know about the currently best
3718 * MMS-supporting network through the provided {@link NetworkCallback}.
3719 *
3720 * <p>The status of the request can be followed by listening to the various callbacks described
3721 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3722 * used to direct traffic to the network (although accessing some networks may be subject to
3723 * holding specific permissions). Callers will learn about the specific characteristics of the
3724 * network through
3725 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3726 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3727 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3728 * matching the request at any given time; therefore when a better network matching the request
3729 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3730 * with the new network after which no further updates are given about the previously-best
3731 * network, unless it becomes the best again at some later time. All callbacks are invoked
3732 * in order on the same thread, which by default is a thread created by the framework running
3733 * in the app.
3734 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3735 * callbacks are invoked.
3736 *
3737 * <p>This{@link NetworkRequest} will live until released via
3738 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3739 * which point the system may let go of the network at any time.
3740 *
3741 * <p>A version of this method which takes a timeout is
3742 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3743 * wait for a limited amount of time for the network to become unavailable.
3744 *
Paul Jensenee52d232015-06-16 15:11:58 -04003745 * <p>It is presently unsupported to request a network with mutable
3746 * {@link NetworkCapabilities} such as
3747 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3748 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3749 * as these {@code NetworkCapabilities} represent states that a particular
3750 * network may never attain, and whether a network will attain these states
3751 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003752 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003753 *
3754 * <p>This method requires the caller to hold either the
3755 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3756 * or the ability to modify system settings as determined by
3757 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003758 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003759 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3760 * number of outstanding requests to 100 per app (identified by their UID), shared with
3761 * all variants of this method, of {@link #registerNetworkCallback} as well as
3762 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3763 * Requesting a network with this method will count toward this limit. If this limit is
3764 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3765 * make sure to unregister the callbacks with
3766 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3767 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003768 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003769 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3770 * the callback must not be shared - it uniquely specifies this request.
3771 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003772 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3773 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003774 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003775 */
Chalard Jean158702d2019-01-07 19:26:34 +09003776 public void requestNetwork(@NonNull NetworkRequest request,
3777 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003778 requestNetwork(request, networkCallback, getDefaultHandler());
3779 }
3780
3781 /**
3782 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3783 *
Chalard Jean01378b62019-08-30 16:27:28 +09003784 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3785 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003786 *
Chalard Jean01378b62019-08-30 16:27:28 +09003787 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003788 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3789 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003790 *
3791 * @param request {@link NetworkRequest} describing this request.
3792 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3793 * the callback must not be shared - it uniquely specifies this request.
3794 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003795 */
Chalard Jean158702d2019-01-07 19:26:34 +09003796 public void requestNetwork(@NonNull NetworkRequest request,
3797 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003798 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003799 NetworkCapabilities nc = request.networkCapabilities;
3800 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003801 }
3802
3803 /**
Etan Cohenf67bde92017-03-01 12:47:28 -08003804 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3805 * by a timeout.
3806 *
3807 * This function behaves identically to the non-timed-out version
3808 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3809 * is not found within the given time (in milliseconds) the
3810 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3811 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3812 * not have to be released if timed-out (it is automatically released). Unregistering a
3813 * request that timed out is not an error.
3814 *
3815 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3816 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3817 * for that purpose. Calling this method will attempt to bring up the requested network.
3818 *
Chalard Jean01378b62019-08-30 16:27:28 +09003819 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003820 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3821 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003822 *
3823 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003824 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3825 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003826 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3827 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3828 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003829 */
Chalard Jean158702d2019-01-07 19:26:34 +09003830 public void requestNetwork(@NonNull NetworkRequest request,
3831 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003832 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003833 NetworkCapabilities nc = request.networkCapabilities;
3834 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3835 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003836 }
3837
Hugo Benichifd44e912017-02-02 17:02:36 +09003838 /**
3839 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3840 * by a timeout.
3841 *
Chalard Jean01378b62019-08-30 16:27:28 +09003842 * This method behaves identically to
3843 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3844 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003845 *
Chalard Jean01378b62019-08-30 16:27:28 +09003846 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003847 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3848 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003849 *
3850 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003851 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3852 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003853 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003854 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3855 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003856 */
Chalard Jean158702d2019-01-07 19:26:34 +09003857 public void requestNetwork(@NonNull NetworkRequest request,
3858 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003859 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003860 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003861 NetworkCapabilities nc = request.networkCapabilities;
3862 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003863 }
3864
3865 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003866 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003867 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003868 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003869 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003870 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3871 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003872 */
Erik Kline8a826212014-11-19 12:12:24 +09003873 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003874
3875 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003876 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003877 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003878 * {@link android.content.Intent#getParcelableExtra(String)}.
3879 */
Erik Kline8a826212014-11-19 12:12:24 +09003880 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003881
3882
3883 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003884 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003885 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003886 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003887 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003888 * the request may outlive the calling application and get called back when a suitable
3889 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003890 * <p>
3891 * The operation is an Intent broadcast that goes to a broadcast receiver that
3892 * you registered with {@link Context#registerReceiver} or through the
3893 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3894 * <p>
3895 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003896 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3897 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003898 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003899 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003900 * Intent to reserve the network or it will be released shortly after the Intent
3901 * is processed.
3902 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003903 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003904 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003905 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003906 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003907 * The request may be released normally by calling
3908 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003909 * <p>It is presently unsupported to request a network with either
3910 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3911 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3912 * as these {@code NetworkCapabilities} represent states that a particular
3913 * network may never attain, and whether a network will attain these states
3914 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003915 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003916 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003917 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3918 * number of outstanding requests to 100 per app (identified by their UID), shared with
3919 * all variants of this method, of {@link #registerNetworkCallback} as well as
3920 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3921 * Requesting a network with this method will count toward this limit. If this limit is
3922 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3923 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3924 * or {@link #releaseNetworkRequest(PendingIntent)}.
3925 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003926 * <p>This method requires the caller to hold either the
3927 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3928 * or the ability to modify system settings as determined by
3929 * {@link android.provider.Settings.System#canWrite}.</p>
3930 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003931 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003932 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003933 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003934 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09003935 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3936 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003937 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003938 */
Chalard Jean158702d2019-01-07 19:26:34 +09003939 public void requestNetwork(@NonNull NetworkRequest request,
3940 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003941 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003942 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003943 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003944 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003945 request.networkCapabilities, operation, mContext.getOpPackageName(),
3946 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003947 } catch (RemoteException e) {
3948 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003949 } catch (ServiceSpecificException e) {
3950 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003951 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003952 }
3953
3954 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003955 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3956 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09003957 * This method has the same behavior as
3958 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003959 * releasing network resources and disconnecting.
3960 *
3961 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3962 * PendingIntent passed to
3963 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3964 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3965 */
Chalard Jean158702d2019-01-07 19:26:34 +09003966 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003967 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003968 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003969 try {
3970 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003971 } catch (RemoteException e) {
3972 throw e.rethrowFromSystemServer();
3973 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003974 }
3975
Hugo Benichibc1104b2017-05-09 15:19:01 +09003976 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09003977 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Hugo Benichibc1104b2017-05-09 15:19:01 +09003978 }
3979
3980 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09003981 Objects.requireNonNull(callback, "null NetworkCallback");
Hugo Benichibc1104b2017-05-09 15:19:01 +09003982 }
3983
3984 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09003985 if (timeoutMs <= 0) {
3986 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
3987 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003988 }
3989
3990 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003991 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003992 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08003993 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3994 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003995 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003996 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3997 * number of outstanding requests to 100 per app (identified by their UID), shared with
3998 * all variants of this method, of {@link #requestNetwork} as well as
3999 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4000 * Requesting a network with this method will count toward this limit. If this limit is
4001 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4002 * make sure to unregister the callbacks with
4003 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4004 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004005 * @param request {@link NetworkRequest} describing this request.
4006 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4007 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004008 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004009 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004010 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004011 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004012 public void registerNetworkCallback(@NonNull NetworkRequest request,
4013 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004014 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4015 }
4016
4017 /**
4018 * Registers to receive notifications about all networks which satisfy the given
4019 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004020 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4021 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004022 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004023 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4024 * number of outstanding requests to 100 per app (identified by their UID), shared with
4025 * all variants of this method, of {@link #requestNetwork} as well as
4026 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4027 * Requesting a network with this method will count toward this limit. If this limit is
4028 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4029 * make sure to unregister the callbacks with
4030 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4031 *
4032 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004033 * @param request {@link NetworkRequest} describing this request.
4034 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4035 * networks change state.
4036 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004037 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004038 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004039 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004040 public void registerNetworkCallback(@NonNull NetworkRequest request,
4041 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004042 CallbackHandler cbHandler = new CallbackHandler(handler);
4043 NetworkCapabilities nc = request.networkCapabilities;
4044 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004045 }
4046
4047 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004048 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4049 * {@link NetworkRequest}.
4050 *
4051 * This function behaves identically to the version that takes a NetworkCallback, but instead
4052 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4053 * the request may outlive the calling application and get called back when a suitable
4054 * network is found.
4055 * <p>
4056 * The operation is an Intent broadcast that goes to a broadcast receiver that
4057 * you registered with {@link Context#registerReceiver} or through the
4058 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4059 * <p>
4060 * The operation Intent is delivered with two extras, a {@link Network} typed
4061 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4062 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4063 * the original requests parameters.
4064 * <p>
4065 * If there is already a request for this Intent registered (with the equality of
4066 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4067 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4068 * <p>
4069 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004070 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004071 *
4072 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4073 * number of outstanding requests to 100 per app (identified by their UID), shared with
4074 * all variants of this method, of {@link #requestNetwork} as well as
4075 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4076 * Requesting a network with this method will count toward this limit. If this limit is
4077 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4078 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4079 * or {@link #releaseNetworkRequest(PendingIntent)}.
4080 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004081 * @param request {@link NetworkRequest} describing this request.
4082 * @param operation Action to perform when the network is available (corresponds
4083 * to the {@link NetworkCallback#onAvailable} call. Typically
4084 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004085 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004086 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004087 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004088 public void registerNetworkCallback(@NonNull NetworkRequest request,
4089 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004090 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004091 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004092 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004093 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004094 request.networkCapabilities, operation, mContext.getOpPackageName(),
4095 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004096 } catch (RemoteException e) {
4097 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004098 } catch (ServiceSpecificException e) {
4099 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004100 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004101 }
4102
4103 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004104 * Registers to receive notifications about changes in the application's default network. This
4105 * may be a physical network or a virtual network, such as a VPN that applies to the
4106 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004107 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004108 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004109 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4110 * number of outstanding requests to 100 per app (identified by their UID), shared with
4111 * all variants of this method, of {@link #requestNetwork} as well as
4112 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4113 * Requesting a network with this method will count toward this limit. If this limit is
4114 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4115 * make sure to unregister the callbacks with
4116 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4117 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004118 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004119 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004120 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004121 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004122 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004123 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004124 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004125 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4126 }
4127
4128 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004129 * Registers to receive notifications about changes in the application's default network. This
4130 * may be a physical network or a virtual network, such as a VPN that applies to the
4131 * application. The callbacks will continue to be called until either the application exits or
4132 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4133 *
4134 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4135 * number of outstanding requests to 100 per app (identified by their UID), shared with
4136 * all variants of this method, of {@link #requestNetwork} as well as
4137 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4138 * Requesting a network with this method will count toward this limit. If this limit is
4139 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4140 * make sure to unregister the callbacks with
4141 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4142 *
4143 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4144 * application's default network changes.
4145 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4146 * @throws RuntimeException if the app already has too many callbacks registered.
4147 */
4148 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4149 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4150 @NonNull Handler handler) {
4151 CallbackHandler cbHandler = new CallbackHandler(handler);
4152 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4153 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4154 }
4155
4156 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004157 * Registers to receive notifications about changes in the system default network. The callbacks
4158 * will continue to be called until either the application exits or
4159 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004160 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004161 * This method should not be used to determine networking state seen by applications, because in
4162 * many cases, most or even all application traffic may not use the default network directly,
4163 * and traffic from different applications may go on different networks by default. As an
4164 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4165 * and not onto the system default network. Applications or system components desiring to do
4166 * determine network state as seen by applications should use other methods such as
4167 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4168 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004169 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4170 * number of outstanding requests to 100 per app (identified by their UID), shared with
4171 * all variants of this method, of {@link #requestNetwork} as well as
4172 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4173 * Requesting a network with this method will count toward this limit. If this limit is
4174 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4175 * make sure to unregister the callbacks with
4176 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4177 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004178 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4179 * system default network changes.
4180 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004181 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004182 *
4183 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004184 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004185 @SystemApi(client = MODULE_LIBRARIES)
4186 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4187 @RequiresPermission(anyOf = {
4188 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4189 android.Manifest.permission.NETWORK_SETTINGS})
4190 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004191 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004192 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004193 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004194 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004195 }
4196
4197 /**
fenglub00f4882015-04-21 17:12:05 -07004198 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4199 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4200 * network connection for updated bandwidth information. The caller will be notified via
4201 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004202 * method assumes that the caller has previously called
4203 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4204 * changes.
fenglu3f357402015-03-20 11:29:56 -07004205 *
fengluea2d9282015-04-27 14:28:04 -07004206 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004207 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004208 */
Chalard Jean158702d2019-01-07 19:26:34 +09004209 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004210 try {
fenglub00f4882015-04-21 17:12:05 -07004211 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004212 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004213 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004214 }
4215 }
4216
4217 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004218 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004219 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4220 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4221 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004222 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4223 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004224 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004225 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4226 * triggering it as soon as this call returns.
4227 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004228 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004229 */
Chalard Jean158702d2019-01-07 19:26:34 +09004230 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004231 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004232 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004233 final List<NetworkRequest> reqs = new ArrayList<>();
4234 // Find all requests associated to this callback and stop callback triggers immediately.
4235 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4236 synchronized (sCallbacks) {
Remi NGUYEN VAN62b1df42021-03-11 20:49:13 +09004237 if (networkCallback.networkRequest == null) {
4238 throw new IllegalArgumentException("NetworkCallback was not registered");
4239 }
Etan Cohen6cb65992019-04-16 15:07:55 -07004240 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4241 Log.d(TAG, "NetworkCallback was already unregistered");
4242 return;
4243 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004244 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4245 if (e.getValue() == networkCallback) {
4246 reqs.add(e.getKey());
4247 }
4248 }
4249 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4250 for (NetworkRequest r : reqs) {
4251 try {
4252 mService.releaseNetworkRequest(r);
4253 } catch (RemoteException e) {
4254 throw e.rethrowFromSystemServer();
4255 }
4256 // Only remove mapping if rpc was successful.
4257 sCallbacks.remove(r);
4258 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004259 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004260 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004261 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004262
4263 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004264 * Unregisters a callback previously registered via
4265 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4266 *
4267 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4268 * PendingIntent passed to
4269 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4270 * Cannot be null.
4271 */
Chalard Jean158702d2019-01-07 19:26:34 +09004272 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004273 releaseNetworkRequest(operation);
4274 }
4275
4276 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004277 * Informs the system whether it should switch to {@code network} regardless of whether it is
4278 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4279 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4280 * the system default network regardless of any other network that's currently connected. If
4281 * {@code always} is true, then the choice is remembered, so that the next time the user
4282 * connects to this network, the system will switch to it.
4283 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004284 * @param network The network to accept.
4285 * @param accept Whether to accept the network even if unvalidated.
4286 * @param always Whether to remember this choice in the future.
4287 *
4288 * @hide
4289 */
lucaslin2240ef62019-03-12 13:08:03 +08004290 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004291 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4292 try {
4293 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004294 } catch (RemoteException e) {
4295 throw e.rethrowFromSystemServer();
4296 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004297 }
4298
4299 /**
lucaslin2240ef62019-03-12 13:08:03 +08004300 * Informs the system whether it should consider the network as validated even if it only has
4301 * partial connectivity. If {@code accept} is true, then the network will be considered as
4302 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4303 * is remembered, so that the next time the user connects to this network, the system will
4304 * switch to it.
4305 *
4306 * @param network The network to accept.
4307 * @param accept Whether to consider the network as validated even if it has partial
4308 * connectivity.
4309 * @param always Whether to remember this choice in the future.
4310 *
4311 * @hide
4312 */
4313 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4314 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4315 try {
4316 mService.setAcceptPartialConnectivity(network, accept, always);
4317 } catch (RemoteException e) {
4318 throw e.rethrowFromSystemServer();
4319 }
4320 }
4321
4322 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004323 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4324 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4325 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4326 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4327 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004328 * @param network The network to accept.
4329 *
4330 * @hide
4331 */
lucaslin2240ef62019-03-12 13:08:03 +08004332 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004333 public void setAvoidUnvalidated(Network network) {
4334 try {
4335 mService.setAvoidUnvalidated(network);
4336 } catch (RemoteException e) {
4337 throw e.rethrowFromSystemServer();
4338 }
4339 }
4340
4341 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004342 * Requests that the system open the captive portal app on the specified network.
4343 *
4344 * @param network The network to log into.
4345 *
4346 * @hide
4347 */
paulhu8e96a752019-08-12 16:25:11 +08004348 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004349 public void startCaptivePortalApp(Network network) {
4350 try {
4351 mService.startCaptivePortalApp(network);
4352 } catch (RemoteException e) {
4353 throw e.rethrowFromSystemServer();
4354 }
4355 }
4356
4357 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004358 * Requests that the system open the captive portal app with the specified extras.
4359 *
4360 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4361 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004362 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004363 * @param appExtras Extras to include in the app start intent.
4364 * @hide
4365 */
4366 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004367 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004368 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004369 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004370 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004371 } catch (RemoteException e) {
4372 throw e.rethrowFromSystemServer();
4373 }
4374 }
4375
4376 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004377 * Determine whether the device is configured to avoid bad wifi.
4378 * @hide
4379 */
4380 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004381 @RequiresPermission(anyOf = {
4382 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4383 android.Manifest.permission.NETWORK_STACK})
4384 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004385 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004386 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004387 } catch (RemoteException e) {
4388 throw e.rethrowFromSystemServer();
4389 }
4390 }
4391
4392 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004393 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4394 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004395 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4396 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004397 *
4398 * An example of such an operation might be a time-sensitive foreground activity, such as a
4399 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4400 */
4401 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4402
4403 /**
4404 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4405 * a backup channel for traffic that is primarily going over another network.
4406 *
4407 * An example might be maintaining backup connections to peers or servers for the purpose of
4408 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4409 * on backup paths should be negligible compared to the traffic on the main path.
4410 */
4411 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4412
4413 /**
4414 * It is acceptable to use metered data to improve network latency and performance.
4415 */
4416 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4417
4418 /**
4419 * Return value to use for unmetered networks. On such networks we currently set all the flags
4420 * to true.
4421 * @hide
4422 */
4423 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4424 MULTIPATH_PREFERENCE_HANDOVER |
4425 MULTIPATH_PREFERENCE_RELIABILITY |
4426 MULTIPATH_PREFERENCE_PERFORMANCE;
4427
4428 /** @hide */
4429 @Retention(RetentionPolicy.SOURCE)
4430 @IntDef(flag = true, value = {
4431 MULTIPATH_PREFERENCE_HANDOVER,
4432 MULTIPATH_PREFERENCE_RELIABILITY,
4433 MULTIPATH_PREFERENCE_PERFORMANCE,
4434 })
4435 public @interface MultipathPreference {
4436 }
4437
4438 /**
4439 * Provides a hint to the calling application on whether it is desirable to use the
4440 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4441 * for multipath data transfer on this network when it is not the system default network.
4442 * Applications desiring to use multipath network protocols should call this method before
4443 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004444 *
4445 * @param network The network on which the application desires to use multipath data.
4446 * If {@code null}, this method will return the a preference that will generally
4447 * apply to metered networks.
4448 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4449 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004450 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004451 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004452 try {
4453 return mService.getMultipathPreference(network);
4454 } catch (RemoteException e) {
4455 throw e.rethrowFromSystemServer();
4456 }
4457 }
4458
4459 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004460 * Resets all connectivity manager settings back to factory defaults.
4461 * @hide
4462 */
paulhu8e96a752019-08-12 16:25:11 +08004463 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004464 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004465 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004466 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004467 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004468 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004469 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004470 }
4471 }
4472
4473 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004474 * Binds the current process to {@code network}. All Sockets created in the future
4475 * (and not explicitly bound via a bound SocketFactory from
4476 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4477 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4478 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4479 * work and all host name resolutions will fail. This is by design so an application doesn't
4480 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4481 * To clear binding pass {@code null} for {@code network}. Using individually bound
4482 * Sockets created by Network.getSocketFactory().createSocket() and
4483 * performing network-specific host name resolutions via
4484 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004485 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004486 *
4487 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4488 * the current binding.
4489 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4490 */
Chalard Jean158702d2019-01-07 19:26:34 +09004491 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004492 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004493 // instantiated.
4494 return setProcessDefaultNetwork(network);
4495 }
4496
4497 /**
4498 * Binds the current process to {@code network}. All Sockets created in the future
4499 * (and not explicitly bound via a bound SocketFactory from
4500 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4501 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4502 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4503 * work and all host name resolutions will fail. This is by design so an application doesn't
4504 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4505 * To clear binding pass {@code null} for {@code network}. Using individually bound
4506 * Sockets created by Network.getSocketFactory().createSocket() and
4507 * performing network-specific host name resolutions via
4508 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4509 * {@code setProcessDefaultNetwork}.
4510 *
4511 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4512 * the current binding.
4513 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4514 * @deprecated This function can throw {@link IllegalStateException}. Use
4515 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4516 * is a direct replacement.
4517 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004518 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004519 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004520 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004521 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4522
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004523 if (netId != NETID_UNSET) {
4524 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004525 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004526
4527 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4528 return false;
4529 }
4530
4531 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004532 // Set HTTP proxy system properties to match network.
4533 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004534 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004535 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004536 } catch (SecurityException e) {
4537 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4538 Log.e(TAG, "Can't set proxy properties", e);
4539 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004540 // Must flush DNS cache as new network may have different DNS resolutions.
4541 InetAddress.clearDnsCache();
4542 // Must flush socket pool as idle sockets will be bound to previous network and may
4543 // cause subsequent fetches to be performed on old network.
4544 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004545 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004546
4547 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004548 }
4549
4550 /**
4551 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004552 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004553 *
4554 * @return {@code Network} to which this process is bound, or {@code null}.
4555 */
Chalard Jean158702d2019-01-07 19:26:34 +09004556 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004557 public Network getBoundNetworkForProcess() {
4558 // Forcing callers to call thru non-static function ensures ConnectivityManager
4559 // instantiated.
4560 return getProcessDefaultNetwork();
4561 }
4562
4563 /**
4564 * Returns the {@link Network} currently bound to this process via
4565 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4566 *
4567 * @return {@code Network} to which this process is bound, or {@code null}.
4568 * @deprecated Using this function can lead to other functions throwing
4569 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4570 * {@code getBoundNetworkForProcess} is a direct replacement.
4571 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004572 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004573 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004574 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004575 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004576 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004577 return new Network(netId);
4578 }
4579
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004580 private void unsupportedStartingFrom(int version) {
4581 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004582 // The getApplicationInfo() call we make below is not supported in system context. Let
4583 // the call through here, and rely on the fact that ConnectivityService will refuse to
4584 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004585 return;
4586 }
4587
4588 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4589 throw new UnsupportedOperationException(
4590 "This method is not supported in target SDK version " + version + " and above");
4591 }
4592 }
4593
4594 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4595 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004596 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004597 // remove these exemptions. Note that this check is not secure, and apps can still access these
4598 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4599 // so is unsupported and may break in the future. http://b/22728205
4600 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004601 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004602 }
4603
Paul Jensen8cdda642014-05-29 10:12:39 -04004604 /**
4605 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004606 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004607 *
4608 * @param network The {@link Network} to bind host resolutions from the current process to, or
4609 * {@code null} to clear the current binding.
4610 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4611 * @hide
4612 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4613 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004614 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004615 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004616 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004617 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004618 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004619 }
Felipe Leme30511352016-01-22 09:44:57 -08004620
4621 /**
4622 * Device is not restricting metered network activity while application is running on
4623 * background.
4624 */
4625 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4626
4627 /**
4628 * Device is restricting metered network activity while application is running on background,
4629 * but application is allowed to bypass it.
4630 * <p>
4631 * In this state, application should take action to mitigate metered network access.
4632 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4633 */
4634 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4635
4636 /**
4637 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004638 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004639 * In this state, application should not try to use the network while running on background,
4640 * because it would be denied.
4641 */
4642 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4643
Felipe Lemed34c9af2016-01-27 14:46:39 -08004644 /**
4645 * A change in the background metered network activity restriction has occurred.
4646 * <p>
4647 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4648 * applies to them.
4649 * <p>
4650 * This is only sent to registered receivers, not manifest receivers.
4651 */
4652 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4653 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4654 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4655
Felipe Leme7e4c1852016-01-25 11:48:04 -08004656 /** @hide */
4657 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004658 @IntDef(flag = false, value = {
4659 RESTRICT_BACKGROUND_STATUS_DISABLED,
4660 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4661 RESTRICT_BACKGROUND_STATUS_ENABLED,
4662 })
Felipe Leme30511352016-01-22 09:44:57 -08004663 public @interface RestrictBackgroundStatus {
4664 }
4665
4666 private INetworkPolicyManager getNetworkPolicyManager() {
4667 synchronized (this) {
4668 if (mNPManager != null) {
4669 return mNPManager;
4670 }
4671 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4672 .getService(Context.NETWORK_POLICY_SERVICE));
4673 return mNPManager;
4674 }
4675 }
4676
4677 /**
4678 * Determines if the calling application is subject to metered network restrictions while
4679 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004680 *
4681 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4682 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4683 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004684 */
4685 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4686 try {
4687 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4688 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004689 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004690 }
4691 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004692
4693 /**
4694 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004695 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4696 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004697 *
4698 * @return Hash of network watchlist config file. Null if config does not exist.
4699 */
Chalard Jean158702d2019-01-07 19:26:34 +09004700 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004701 public byte[] getNetworkWatchlistConfigHash() {
4702 try {
4703 return mService.getNetworkWatchlistConfigHash();
4704 } catch (RemoteException e) {
4705 Log.e(TAG, "Unable to get watchlist config hash");
4706 throw e.rethrowFromSystemServer();
4707 }
4708 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004709
4710 /**
4711 * Returns the {@code uid} of the owner of a network connection.
4712 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004713 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4714 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004715 * @param local The local {@link InetSocketAddress} of a connection.
4716 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004717 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004718 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4719 * android.os.Process#INVALID_UID} if the connection is not found.
4720 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4721 * user.
4722 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004723 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004724 public int getConnectionOwnerUid(
4725 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004726 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4727 try {
4728 return mService.getConnectionOwnerUid(connectionInfo);
4729 } catch (RemoteException e) {
4730 throw e.rethrowFromSystemServer();
4731 }
4732 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004733
4734 private void printStackTrace() {
4735 if (DEBUG) {
4736 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4737 final StringBuffer sb = new StringBuffer();
4738 for (int i = 3; i < callStack.length; i++) {
4739 final String stackTrace = callStack[i].toString();
4740 if (stackTrace == null || stackTrace.contains("android.os")) {
4741 break;
4742 }
4743 sb.append(" [").append(stackTrace).append("]");
4744 }
4745 Log.d(TAG, "StackLog:" + sb.toString());
4746 }
4747 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004748
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004749 /** @hide */
4750 public TestNetworkManager startOrGetTestNetworkManager() {
4751 final IBinder tnBinder;
4752 try {
4753 tnBinder = mService.startOrGetTestNetworkService();
4754 } catch (RemoteException e) {
4755 throw e.rethrowFromSystemServer();
4756 }
4757
4758 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4759 }
4760
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004761 /** @hide */
4762 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4763 return new ConnectivityDiagnosticsManager(mContext, mService);
4764 }
4765
Cody Kestingf53a0752020-04-15 12:33:28 -07004766 /**
4767 * Simulates a Data Stall for the specified Network.
4768 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004769 * <p>This method should only be used for tests.
4770 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004771 * <p>The caller must be the owner of the specified Network.
4772 *
4773 * @param detectionMethod The detection method used to identify the Data Stall.
4774 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4775 * @param network The Network for which a Data Stall is being simluated.
4776 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4777 * @throws SecurityException if the caller is not the owner of the given network.
4778 * @hide
4779 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004780 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004781 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4782 android.Manifest.permission.NETWORK_STACK})
4783 public void simulateDataStall(int detectionMethod, long timestampMillis,
4784 @NonNull Network network, @NonNull PersistableBundle extras) {
4785 try {
4786 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4787 } catch (RemoteException e) {
4788 e.rethrowFromSystemServer();
4789 }
4790 }
James Mattis356a8792020-10-28 21:48:54 -07004791
Daniel Brightf9e945b2020-06-15 16:10:01 -07004792 @NonNull
4793 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4794
4795 /**
4796 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4797 * receive available QoS events related to the {@link Network} and local ip + port
4798 * specified within socketInfo.
4799 * <p/>
4800 * The same {@link QosCallback} must be unregistered before being registered a second time,
4801 * otherwise {@link QosCallbackRegistrationException} is thrown.
4802 * <p/>
4803 * This API does not, in itself, require any permission if called with a network that is not
4804 * restricted. However, the underlying implementation currently only supports the IMS network,
4805 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4806 * useful, because they'd never be called back on networks that they would have access to.
4807 *
4808 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4809 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4810 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4811 * @throws RuntimeException if the app already has too many callbacks registered.
4812 *
4813 * Exceptions after the time of registration is passed through
4814 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4815 *
4816 * @param socketInfo the socket information used to match QoS events
4817 * @param callback receives qos events that satisfy socketInfo
4818 * @param executor The executor on which the callback will be invoked. The provided
4819 * {@link Executor} must run callback sequentially, otherwise the order of
4820 * callbacks cannot be guaranteed.
4821 *
4822 * @hide
4823 */
4824 @SystemApi
4825 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4826 @NonNull final QosCallback callback,
4827 @CallbackExecutor @NonNull final Executor executor) {
4828 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4829 Objects.requireNonNull(callback, "callback must be non-null");
4830 Objects.requireNonNull(executor, "executor must be non-null");
4831
4832 try {
4833 synchronized (mQosCallbackConnections) {
4834 if (getQosCallbackConnection(callback) == null) {
4835 final QosCallbackConnection connection =
4836 new QosCallbackConnection(this, callback, executor);
4837 mQosCallbackConnections.add(connection);
4838 mService.registerQosSocketCallback(socketInfo, connection);
4839 } else {
4840 Log.e(TAG, "registerQosCallback: Callback already registered");
4841 throw new QosCallbackRegistrationException();
4842 }
4843 }
4844 } catch (final RemoteException e) {
4845 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4846
4847 // The same unregister method method is called for consistency even though nothing
4848 // will be sent to the ConnectivityService since the callback was never successfully
4849 // registered.
4850 unregisterQosCallback(callback);
4851 e.rethrowFromSystemServer();
4852 } catch (final ServiceSpecificException e) {
4853 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4854 unregisterQosCallback(callback);
4855 throw convertServiceException(e);
4856 }
4857 }
4858
4859 /**
4860 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4861 * events once unregistered and can be registered a second time.
4862 * <p/>
4863 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4864 *
4865 * @param callback the callback being unregistered
4866 *
4867 * @hide
4868 */
4869 @SystemApi
4870 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4871 Objects.requireNonNull(callback, "The callback must be non-null");
4872 try {
4873 synchronized (mQosCallbackConnections) {
4874 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4875 if (connection != null) {
4876 connection.stopReceivingMessages();
4877 mService.unregisterQosCallback(connection);
4878 mQosCallbackConnections.remove(connection);
4879 } else {
4880 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4881 }
4882 }
4883 } catch (final RemoteException e) {
4884 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4885 e.rethrowFromSystemServer();
4886 }
4887 }
4888
4889 /**
4890 * Gets the connection related to the callback.
4891 *
4892 * @param callback the callback to look up
4893 * @return the related connection
4894 */
4895 @Nullable
4896 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4897 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4898 // Checking by reference here is intentional
4899 if (connection.getCallback() == callback) {
4900 return connection;
4901 }
4902 }
4903 return null;
4904 }
Junyu Laia62493f2021-01-19 11:10:56 +00004905
4906 /**
4907 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4908 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4909 * be used to request that the system provide a network without causing the network to be
4910 * in the foreground.
4911 *
4912 * <p>This method will attempt to find the best network that matches the passed
4913 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4914 * criteria. The platform will evaluate which network is the best at its own discretion.
4915 * Throughput, latency, cost per byte, policy, user preference and other considerations
4916 * may be factored in the decision of what is considered the best network.
4917 *
4918 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4919 * matching this request, while always attempting to match the request to a better network if
4920 * possible. If a better match is found, the platform will switch this request to the now-best
4921 * network and inform the app of the newly best network by invoking
4922 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4923 * will not try to maintain any other network than the best one currently matching the request:
4924 * a network not matching any network request may be disconnected at any time.
4925 *
4926 * <p>For example, an application could use this method to obtain a connected cellular network
4927 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4928 * radio to consume additional power. Or, an application could inform the system that it wants
4929 * a network supporting sending MMSes and have the system let it know about the currently best
4930 * MMS-supporting network through the provided {@link NetworkCallback}.
4931 *
4932 * <p>The status of the request can be followed by listening to the various callbacks described
4933 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4934 * used to direct traffic to the network (although accessing some networks may be subject to
4935 * holding specific permissions). Callers will learn about the specific characteristics of the
4936 * network through
4937 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4938 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4939 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4940 * matching the request at any given time; therefore when a better network matching the request
4941 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4942 * with the new network after which no further updates are given about the previously-best
4943 * network, unless it becomes the best again at some later time. All callbacks are invoked
4944 * in order on the same thread, which by default is a thread created by the framework running
4945 * in the app.
4946 *
4947 * <p>This{@link NetworkRequest} will live until released via
4948 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4949 * which point the system may let go of the network at any time.
4950 *
4951 * <p>It is presently unsupported to request a network with mutable
4952 * {@link NetworkCapabilities} such as
4953 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4954 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4955 * as these {@code NetworkCapabilities} represent states that a particular
4956 * network may never attain, and whether a network will attain these states
4957 * is unknown prior to bringing up the network so the framework does not
4958 * know how to go about satisfying a request with these capabilities.
4959 *
4960 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4961 * number of outstanding requests to 100 per app (identified by their UID), shared with
4962 * all variants of this method, of {@link #registerNetworkCallback} as well as
4963 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4964 * Requesting a network with this method will count toward this limit. If this limit is
4965 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4966 * make sure to unregister the callbacks with
4967 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4968 *
4969 * @param request {@link NetworkRequest} describing this request.
4970 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4971 * If null, the callback is invoked on the default internal Handler.
4972 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4973 * the callback must not be shared - it uniquely specifies this request.
4974 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4975 * @throws SecurityException if missing the appropriate permissions.
4976 * @throws RuntimeException if the app already has too many callbacks registered.
4977 *
4978 * @hide
4979 */
4980 @SystemApi(client = MODULE_LIBRARIES)
4981 @SuppressLint("ExecutorRegistration")
4982 @RequiresPermission(anyOf = {
4983 android.Manifest.permission.NETWORK_SETTINGS,
4984 android.Manifest.permission.NETWORK_STACK,
4985 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4986 })
4987 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
4988 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
4989 final NetworkCapabilities nc = request.networkCapabilities;
4990 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
4991 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
4992 }
James Mattis45d81842021-01-10 14:24:24 -08004993
4994 /**
4995 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
4996 * OnSetOemNetworkPreferenceListener)}.
James Mattisda32cfe2021-01-26 16:23:52 -08004997 * @hide
James Mattis45d81842021-01-10 14:24:24 -08004998 */
James Mattisda32cfe2021-01-26 16:23:52 -08004999 @SystemApi
5000 public interface OnSetOemNetworkPreferenceListener {
James Mattis45d81842021-01-10 14:24:24 -08005001 /**
5002 * Called when setOemNetworkPreference() successfully completes.
5003 */
5004 void onComplete();
5005 }
5006
5007 /**
5008 * Used by automotive devices to set the network preferences used to direct traffic at an
5009 * application level as per the given OemNetworkPreferences. An example use-case would be an
5010 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5011 * vehicle via a particular network.
5012 *
5013 * Calling this will overwrite the existing preference.
5014 *
5015 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5016 * @param executor the executor on which listener will be invoked.
5017 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5018 * communicate completion of setOemNetworkPreference(). This will only be
5019 * called once upon successful completion of setOemNetworkPreference().
5020 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5021 * @throws SecurityException if missing the appropriate permissions.
5022 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005023 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005024 */
James Mattisda32cfe2021-01-26 16:23:52 -08005025 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005026 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005027 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005028 @Nullable @CallbackExecutor final Executor executor,
5029 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5030 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5031 if (null != listener) {
5032 Objects.requireNonNull(executor, "Executor must be non-null");
5033 }
5034 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5035 new IOnSetOemNetworkPreferenceListener.Stub() {
5036 @Override
5037 public void onComplete() {
5038 executor.execute(listener::onComplete);
5039 }
5040 };
5041
5042 try {
5043 mService.setOemNetworkPreference(preference, listenerInternal);
5044 } catch (RemoteException e) {
5045 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5046 throw e.rethrowFromSystemServer();
5047 }
5048 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005049}