blob: 77e67bac8a866606741e5b5b1bd709fb531525d4 [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;
Junyu Laia62493f2021-01-19 11:10:56 +000019import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaiad010792021-01-11 16:53:38 +080020import static android.net.NetworkRequest.Type.LISTEN;
21import static android.net.NetworkRequest.Type.REQUEST;
22import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +090023import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Brightf9e945b2020-06-15 16:10:01 -070024import static android.net.QosCallback.QosCallbackRegistrationException;
junyulaid05a1922019-01-15 11:32:44 +080025
junyulai4c95b082018-12-27 17:25:29 +080026import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080027import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090028import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000029import android.annotation.Nullable;
Jeff Sharkey656584a2017-04-24 11:18:03 -060030import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080031import android.annotation.SdkConstant;
32import android.annotation.SdkConstant.SdkConstantType;
Junyu Laia62493f2021-01-19 11:10:56 +000033import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080034import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060035import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070036import android.app.PendingIntent;
Artur Satayev9c2add62019-12-10 17:47:52 +000037import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070038import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070039import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080040import android.net.IpSecManager.UdpEncapsulationSocket;
41import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080042import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080043import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080044import android.net.TetheringManager.TetheringRequest;
Robert Greenwalt2034b912009-08-12 16:08:25 -070045import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000046import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070047import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080048import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070049import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080050import android.os.IBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070051import android.os.Looper;
52import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070053import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080054import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070055import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090056import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080057import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080058import android.os.ResultReceiver;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080059import android.os.ServiceManager;
Hugo Benichia590ab82017-05-11 13:16:17 +090060import android.os.ServiceSpecificException;
Jeff Sharkey971cd162011-08-29 16:02:57 -070061import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080062import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080063import android.telephony.TelephonyManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080064import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070065import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090066import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090067import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080068
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090069import com.android.connectivity.aidl.INetworkAgent;
markchien6ae63e52020-01-21 13:11:06 +080070import com.android.internal.annotations.GuardedBy;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090071import com.android.internal.util.Preconditions;
72import 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);
Hugo Benichibc1104b2017-05-09 15:19:01 +09001735 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001736 nc.addTransportType(transport);
1737
1738 // Map from type to capabilities.
1739 nc.addCapability(sLegacyTypeToCapability.get(
1740 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1741 nc.maybeMarkCapabilitiesRestricted();
1742 return nc;
1743 }
1744
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001745 /** @hide */
1746 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001747 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001748 public PacketKeepaliveCallback() {
1749 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001750 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001751 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001752 public void onStarted() {}
1753 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001754 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001755 public void onStopped() {}
1756 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001757 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001758 public void onError(int error) {}
1759 }
1760
1761 /**
1762 * Allows applications to request that the system periodically send specific packets on their
1763 * behalf, using hardware offload to save battery power.
1764 *
1765 * To request that the system send keepalives, call one of the methods that return a
1766 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1767 * passing in a non-null callback. If the callback is successfully started, the callback's
1768 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1769 * specifying one of the {@code ERROR_*} constants in this class.
1770 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001771 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1772 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1773 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001774 *
junyulai4c95b082018-12-27 17:25:29 +08001775 * @deprecated Use {@link SocketKeepalive} instead.
1776 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001777 * @hide
1778 */
1779 public class PacketKeepalive {
1780
1781 private static final String TAG = "PacketKeepalive";
1782
1783 /** @hide */
1784 public static final int SUCCESS = 0;
1785
1786 /** @hide */
1787 public static final int NO_KEEPALIVE = -1;
1788
1789 /** @hide */
1790 public static final int BINDER_DIED = -10;
1791
1792 /** The specified {@code Network} is not connected. */
1793 public static final int ERROR_INVALID_NETWORK = -20;
1794 /** The specified IP addresses are invalid. For example, the specified source IP address is
1795 * not configured on the specified {@code Network}. */
1796 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1797 /** The requested port is invalid. */
1798 public static final int ERROR_INVALID_PORT = -22;
1799 /** The packet length is invalid (e.g., too long). */
1800 public static final int ERROR_INVALID_LENGTH = -23;
1801 /** The packet transmission interval is invalid (e.g., too short). */
1802 public static final int ERROR_INVALID_INTERVAL = -24;
1803
1804 /** The hardware does not support this request. */
1805 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001806 /** The hardware returned an error. */
1807 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001808
Nathan Harold0990bc82018-02-14 13:09:45 -08001809 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001810 public static final int NATT_PORT = 4500;
1811
Nathan Harold0990bc82018-02-14 13:09:45 -08001812 /** The minimum interval in seconds between keepalive packet transmissions */
1813 public static final int MIN_INTERVAL = 10;
1814
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001815 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001816 private final ISocketKeepaliveCallback mCallback;
1817 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001818
1819 private volatile Integer mSlot;
1820
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001821 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001822 public void stop() {
1823 try {
junyulai070f9ff2019-01-16 20:23:34 +08001824 mExecutor.execute(() -> {
1825 try {
1826 if (mSlot != null) {
1827 mService.stopKeepalive(mNetwork, mSlot);
1828 }
1829 } catch (RemoteException e) {
1830 Log.e(TAG, "Error stopping packet keepalive: ", e);
1831 throw e.rethrowFromSystemServer();
1832 }
1833 });
1834 } catch (RejectedExecutionException e) {
1835 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001836 }
1837 }
1838
1839 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09001840 Preconditions.checkNotNull(network, "network cannot be null");
1841 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001842 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001843 mExecutor = Executors.newSingleThreadExecutor();
1844 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001845 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001846 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001847 final long token = Binder.clearCallingIdentity();
1848 try {
1849 mExecutor.execute(() -> {
1850 mSlot = slot;
1851 callback.onStarted();
1852 });
1853 } finally {
1854 Binder.restoreCallingIdentity(token);
1855 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001856 }
junyulai070f9ff2019-01-16 20:23:34 +08001857
1858 @Override
1859 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001860 final long token = Binder.clearCallingIdentity();
1861 try {
1862 mExecutor.execute(() -> {
1863 mSlot = null;
1864 callback.onStopped();
1865 });
1866 } finally {
1867 Binder.restoreCallingIdentity(token);
1868 }
junyulai070f9ff2019-01-16 20:23:34 +08001869 mExecutor.shutdown();
1870 }
1871
1872 @Override
1873 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001874 final long token = Binder.clearCallingIdentity();
1875 try {
1876 mExecutor.execute(() -> {
1877 mSlot = null;
1878 callback.onError(error);
1879 });
1880 } finally {
1881 Binder.restoreCallingIdentity(token);
1882 }
junyulai070f9ff2019-01-16 20:23:34 +08001883 mExecutor.shutdown();
1884 }
1885
1886 @Override
1887 public void onDataReceived() {
1888 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1889 // this callback when data is received.
1890 }
1891 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001892 }
1893 }
1894
1895 /**
1896 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1897 *
junyulai4c95b082018-12-27 17:25:29 +08001898 * @deprecated Use {@link #createSocketKeepalive} instead.
1899 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001900 * @hide
1901 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001902 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001903 public PacketKeepalive startNattKeepalive(
1904 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1905 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1906 final PacketKeepalive k = new PacketKeepalive(network, callback);
1907 try {
junyulai070f9ff2019-01-16 20:23:34 +08001908 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001909 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1910 } catch (RemoteException e) {
1911 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001912 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001913 }
1914 return k;
1915 }
1916
Chiachang Wang619319a2021-01-15 11:06:21 +08001917 // Construct an invalid fd.
1918 private ParcelFileDescriptor createInvalidFd() {
1919 final int invalidFd = -1;
1920 return ParcelFileDescriptor.adoptFd(invalidFd);
1921 }
1922
The Android Open Source Project28527d22009-03-03 19:31:44 -08001923 /**
junyulai4c95b082018-12-27 17:25:29 +08001924 * Request that keepalives be started on a IPsec NAT-T socket.
1925 *
1926 * @param network The {@link Network} the socket is on.
1927 * @param socket The socket that needs to be kept alive.
1928 * @param source The source address of the {@link UdpEncapsulationSocket}.
1929 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1930 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1931 * must run callback sequentially, otherwise the order of callbacks cannot be
1932 * guaranteed.
1933 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1934 * changes. Must be extended by applications that use this API.
1935 *
junyulai0835a1e2019-01-08 20:04:33 +08001936 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1937 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001938 **/
junyulai7e06ad42019-03-04 22:45:36 +08001939 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001940 @NonNull UdpEncapsulationSocket socket,
1941 @NonNull InetAddress source,
1942 @NonNull InetAddress destination,
1943 @NonNull @CallbackExecutor Executor executor,
1944 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001945 ParcelFileDescriptor dup;
1946 try {
junyulai828dad12019-03-27 11:00:37 +08001947 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1948 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001949 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1950 } catch (IOException ignored) {
1951 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1952 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001953 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001954 }
1955 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1956 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08001957 }
1958
1959 /**
1960 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1961 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1962 *
1963 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08001964 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1965 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1966 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08001967 * @param source The source address of the {@link UdpEncapsulationSocket}.
1968 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1969 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1970 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1971 * must run callback sequentially, otherwise the order of callbacks cannot be
1972 * guaranteed.
1973 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1974 * changes. Must be extended by applications that use this API.
1975 *
junyulai0835a1e2019-01-08 20:04:33 +08001976 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1977 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08001978 * @hide
1979 */
1980 @SystemApi
1981 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08001982 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1983 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08001984 @NonNull InetAddress source,
1985 @NonNull InetAddress destination,
1986 @NonNull @CallbackExecutor Executor executor,
1987 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001988 ParcelFileDescriptor dup;
1989 try {
junyulai828dad12019-03-27 11:00:37 +08001990 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08001991 dup = pfd.dup();
1992 } catch (IOException ignored) {
1993 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1994 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001995 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001996 }
1997 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANce355502021-03-11 10:56:49 +00001998 -1 /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08001999 }
2000
2001 /**
junyulai0835a1e2019-01-08 20:04:33 +08002002 * Request that keepalives be started on a TCP socket.
2003 * The socket must be established.
2004 *
2005 * @param network The {@link Network} the socket is on.
2006 * @param socket The socket that needs to be kept alive.
2007 * @param executor The executor on which callback will be invoked. This implementation assumes
2008 * the provided {@link Executor} runs the callbacks in sequence with no
2009 * concurrency. Failing this, no guarantee of correctness can be made. It is
2010 * the responsibility of the caller to ensure the executor provides this
2011 * guarantee. A simple way of creating such an executor is with the standard
2012 * tool {@code Executors.newSingleThreadExecutor}.
2013 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2014 * changes. Must be extended by applications that use this API.
2015 *
2016 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2017 * given socket.
2018 * @hide
2019 */
2020 @SystemApi
2021 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002022 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002023 @NonNull Socket socket,
2024 @NonNull Executor executor,
2025 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002026 ParcelFileDescriptor dup;
2027 try {
2028 dup = ParcelFileDescriptor.fromSocket(socket);
2029 } catch (UncheckedIOException ignored) {
2030 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2031 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002032 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002033 }
2034 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002035 }
2036
2037 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002038 * Ensure that a network route exists to deliver traffic to the specified
2039 * host via the specified network interface. An attempt to add a route that
2040 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002041 *
2042 * <p>This method requires the caller to hold either the
2043 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2044 * or the ability to modify system settings as determined by
2045 * {@link android.provider.Settings.System#canWrite}.</p>
2046 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002047 * @param networkType the type of the network over which traffic to the specified
2048 * host is to be routed
2049 * @param hostAddress the IP address of the host to which the route is desired
2050 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002051 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002052 * @deprecated Deprecated in favor of the
2053 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2054 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002055 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002056 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002057 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002058 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002059 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002060 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002061 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002062 }
2063
2064 /**
2065 * Ensure that a network route exists to deliver traffic to the specified
2066 * host via the specified network interface. An attempt to add a route that
2067 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002068 *
2069 * <p>This method requires the caller to hold either the
2070 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2071 * or the ability to modify system settings as determined by
2072 * {@link android.provider.Settings.System#canWrite}.</p>
2073 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002074 * @param networkType the type of the network over which traffic to the specified
2075 * host is to be routed
2076 * @param hostAddress the IP address of the host to which the route is desired
2077 * @return {@code true} on success, {@code false} on failure
2078 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002079 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002080 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002081 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002082 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002083 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002084 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002085 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002086 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002087 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2088 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002089 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002090 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002091 }
2092 }
2093
2094 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002095 * @return the context's attribution tag
2096 */
2097 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2098 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002099 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002100 }
2101
2102 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002103 * Returns the value of the setting for background data usage. If false,
2104 * applications should not use the network if the application is not in the
2105 * foreground. Developers should respect this setting, and check the value
2106 * of this before performing any background data operations.
2107 * <p>
2108 * All applications that have background services that use the network
2109 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002110 * <p>
Scott Main50589142011-10-06 18:32:43 -07002111 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002112 * background data depends on several combined factors, and this method will
2113 * always return {@code true}. Instead, when background data is unavailable,
2114 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002115 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002116 * @return Whether background data usage is allowed.
2117 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002118 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002119 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002120 // assume that background data is allowed; final authority is
2121 // NetworkInfo which may be blocked.
2122 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002123 }
2124
2125 /**
2126 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002127 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002128 * @param allowBackgroundData Whether an application should use data while
2129 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002130 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002131 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2132 * @see #getBackgroundDataSetting()
2133 * @hide
2134 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002135 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002136 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002138 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002139 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002140
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002141 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002142 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002143 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002144 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002145 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002146 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002147 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002148 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2149 if (tm != null) {
2150 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2151 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2152 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2153 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2154 + " retVal=" + retVal);
2155 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002156 }
Wink Saville689f7042014-12-05 11:10:30 -08002157 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002158 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002159 }
2160
The Android Open Source Project28527d22009-03-03 19:31:44 -08002161 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002162 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002163 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002164 */
2165 public interface OnNetworkActiveListener {
2166 /**
2167 * Called on the main thread of the process to report that the current data network
2168 * has become active, and it is now a good time to perform any pending network
2169 * operations. Note that this listener only tells you when the network becomes
2170 * active; if at any other time you want to know whether it is active (and thus okay
2171 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002172 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002173 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002174 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002175 }
2176
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002177 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002178 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002179
2180 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002181 * Start listening to reports when the system's default data network is active, meaning it is
2182 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2183 * to determine the current state of the system's default network after registering the
2184 * listener.
2185 * <p>
2186 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002187 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002188 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002189 *
2190 * @param l The listener to be told when the network is active.
2191 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002192 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002193 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2194 @Override
2195 public void onNetworkActive() throws RemoteException {
2196 l.onNetworkActive();
2197 }
2198 };
2199
2200 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002201 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002202 mNetworkActivityListeners.put(l, rl);
2203 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002204 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002205 }
2206 }
2207
2208 /**
2209 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002210 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002211 *
2212 * @param l Previously registered listener.
2213 */
Chalard Jean158702d2019-01-07 19:26:34 +09002214 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002215 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichibc1104b2017-05-09 15:19:01 +09002216 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002217 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002218 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002219 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002220 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002221 }
2222 }
2223
2224 /**
2225 * Return whether the data network is currently active. An active network means that
2226 * it is currently in a high power state for performing data transmission. On some
2227 * types of networks, it may be expensive to move and stay in such a state, so it is
2228 * more power efficient to batch network traffic together when the radio is already in
2229 * this state. This method tells you whether right now is currently a good time to
2230 * initiate network traffic, as the network is already active.
2231 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002232 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002233 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002234 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002235 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002236 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002237 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002238 }
2239
2240 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002241 * {@hide}
2242 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002243 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002244 mContext = Preconditions.checkNotNull(context, "missing context");
2245 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002246 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002247 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002248 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002249
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002250 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002251 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002252 public static ConnectivityManager from(Context context) {
2253 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2254 }
2255
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002256 /** @hide */
2257 public NetworkRequest getDefaultRequest() {
2258 try {
2259 // This is not racy as the default request is final in ConnectivityService.
2260 return mService.getDefaultRequest();
2261 } catch (RemoteException e) {
2262 throw e.rethrowFromSystemServer();
2263 }
2264 }
2265
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002266 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002267 * Check if the package is a allowed to write settings. This also accounts that such an access
2268 * happened.
2269 *
2270 * @return {@code true} iff the package is allowed to write settings.
2271 */
2272 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2273 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2274 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2275 boolean throwException) {
2276 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2277 throwException);
2278 }
2279
2280 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002281 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2282 * situations where a Context pointer is unavailable.
2283 * @hide
2284 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002285 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002286 static ConnectivityManager getInstanceOrNull() {
2287 return sInstance;
2288 }
2289
2290 /**
2291 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2292 * situations where a Context pointer is unavailable.
2293 * @hide
2294 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002295 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002296 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002297 private static ConnectivityManager getInstance() {
2298 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002299 throw new IllegalStateException("No ConnectivityManager yet constructed");
2300 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002301 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002302 }
2303
2304 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002305 * Get the set of tetherable, available interfaces. This list is limited by
2306 * device configuration and current interface existence.
2307 *
2308 * @return an array of 0 or more Strings of tetherable interface names.
2309 *
markchien6ae63e52020-01-21 13:11:06 +08002310 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002311 * {@hide}
2312 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002313 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002314 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002315 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002316 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002317 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002318 }
2319
2320 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002321 * Get the set of tethered interfaces.
2322 *
2323 * @return an array of 0 or more String of currently tethered interface names.
2324 *
markchien6ae63e52020-01-21 13:11:06 +08002325 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002326 * {@hide}
2327 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002328 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002329 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002330 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002331 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002332 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002333 }
2334
2335 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002336 * Get the set of interface names which attempted to tether but
2337 * failed. Re-attempting to tether may cause them to reset to the Tethered
2338 * state. Alternatively, causing the interface to be destroyed and recreated
2339 * may cause them to reset to the available state.
2340 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2341 * information on the cause of the errors.
2342 *
2343 * @return an array of 0 or more String indicating the interface names
2344 * which failed to tether.
2345 *
markchien6ae63e52020-01-21 13:11:06 +08002346 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002347 * {@hide}
2348 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002349 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002350 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002351 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002352 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002353 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002354 }
2355
2356 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002357 * Get the set of tethered dhcp ranges.
2358 *
markchien2e6ba522020-02-14 11:55:48 +08002359 * @deprecated This method is not supported.
2360 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002361 * {@hide}
2362 */
paulhu8e96a752019-08-12 16:25:11 +08002363 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002364 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002365 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002366 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002367 }
2368
2369 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002370 * Attempt to tether the named interface. This will setup a dhcp server
2371 * on the interface, forward and NAT IP packets and forward DNS requests
2372 * to the best active upstream network interface. Note that if no upstream
2373 * IP network interface is available, dhcp will still run and traffic will be
2374 * allowed between the tethered devices and this device, though upstream net
2375 * access will of course fail until an upstream network interface becomes
2376 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002377 *
2378 * <p>This method requires the caller to hold either the
2379 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2380 * or the ability to modify system settings as determined by
2381 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002382 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002383 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2384 * and WifiStateMachine which need direct access. All other clients should use
2385 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2386 * logic.</p>
2387 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002388 * @param iface the interface name to tether.
2389 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002390 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002391 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002392 * {@hide}
2393 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002394 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002395 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002396 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002397 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002398 }
2399
2400 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002401 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002402 *
2403 * <p>This method requires the caller to hold either the
2404 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2405 * or the ability to modify system settings as determined by
2406 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002407 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002408 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2409 * and WifiStateMachine which need direct access. All other clients should use
2410 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2411 * logic.</p>
2412 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002413 * @param iface the interface name to untether.
2414 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2415 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002416 * {@hide}
2417 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002418 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002419 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002420 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002421 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002422 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002423
2424 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002425 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002426 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002427 * due to device configuration.
2428 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002429 * <p>If this app does not have permission to use this API, it will always
2430 * return false rather than throw an exception.</p>
2431 *
2432 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2433 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2434 *
2435 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2436 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2437 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002438 * @return a boolean - {@code true} indicating Tethering is supported.
2439 *
markchien6ae63e52020-01-21 13:11:06 +08002440 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002441 * {@hide}
2442 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002443 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002444 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2445 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002446 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002447 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002448 }
2449
2450 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002451 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002452 *
2453 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002454 * @hide
2455 */
2456 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002457 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002458 public static abstract class OnStartTetheringCallback {
2459 /**
2460 * Called when tethering has been successfully started.
2461 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002462 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002463
2464 /**
2465 * Called when starting tethering failed.
2466 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002467 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002468 }
2469
2470 /**
2471 * Convenient overload for
2472 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2473 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002474 *
2475 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002476 * @hide
2477 */
2478 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002479 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002480 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002481 public void startTethering(int type, boolean showProvisioningUi,
2482 final OnStartTetheringCallback callback) {
2483 startTethering(type, showProvisioningUi, callback, null);
2484 }
2485
2486 /**
2487 * Runs tether provisioning for the given type if needed and then starts tethering if
2488 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2489 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2490 * schedules tether provisioning re-checks if appropriate.
2491 *
2492 * @param type The type of tethering to start. Must be one of
2493 * {@link ConnectivityManager.TETHERING_WIFI},
2494 * {@link ConnectivityManager.TETHERING_USB}, or
2495 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2496 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2497 * is one. This should be true the first time this function is called and also any time
2498 * the user can see this UI. It gives users information from their carrier about the
2499 * check failing and how they can sign up for tethering if possible.
2500 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2501 * of the result of trying to tether.
2502 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002503 *
2504 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002505 * @hide
2506 */
2507 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002508 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002509 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002510 public void startTethering(int type, boolean showProvisioningUi,
2511 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002512 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002513
markchien91c78e52020-01-20 19:31:56 +08002514 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002515 @Override
markchien91c78e52020-01-20 19:31:56 +08002516 public void execute(Runnable command) {
2517 if (handler == null) {
2518 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002519 } else {
markchien91c78e52020-01-20 19:31:56 +08002520 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002521 }
2522 }
2523 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002524
markchien91c78e52020-01-20 19:31:56 +08002525 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2526 @Override
2527 public void onTetheringStarted() {
2528 callback.onTetheringStarted();
2529 }
2530
2531 @Override
markchienf47d8342020-03-19 13:37:43 +08002532 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002533 callback.onTetheringFailed();
2534 }
2535 };
2536
2537 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002538 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002539
Amos Bianchia9b415a2020-03-04 11:07:38 -08002540 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002541 }
2542
2543 /**
2544 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2545 * applicable.
2546 *
2547 * @param type The type of tethering to stop. Must be one of
2548 * {@link ConnectivityManager.TETHERING_WIFI},
2549 * {@link ConnectivityManager.TETHERING_USB}, or
2550 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002551 *
2552 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002553 * @hide
2554 */
2555 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002556 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002557 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002558 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002559 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002560 }
2561
2562 /**
markchien4ef53e82019-02-27 14:56:11 +08002563 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2564 * upstream status.
2565 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002566 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002567 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002568 */
2569 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002570 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002571 public abstract static class OnTetheringEventCallback {
2572
2573 /**
2574 * Called when tethering upstream changed. This can be called multiple times and can be
2575 * called any time.
2576 *
2577 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2578 * have any upstream.
2579 */
2580 public void onUpstreamChanged(@Nullable Network network) {}
2581 }
2582
markchien6ae63e52020-01-21 13:11:06 +08002583 @GuardedBy("mTetheringEventCallbacks")
2584 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2585 mTetheringEventCallbacks = new ArrayMap<>();
2586
markchien4ef53e82019-02-27 14:56:11 +08002587 /**
2588 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002589 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002590 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2591 * with a null argument. The same callback object cannot be registered twice.
2592 *
2593 * @param executor the executor on which callback will be invoked.
2594 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002595 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002596 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002597 * @hide
2598 */
2599 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002600 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002601 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2602 public void registerTetheringEventCallback(
2603 @NonNull @CallbackExecutor Executor executor,
2604 @NonNull final OnTetheringEventCallback callback) {
2605 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2606
markchien6ae63e52020-01-21 13:11:06 +08002607 final TetheringEventCallback tetherCallback =
2608 new TetheringEventCallback() {
2609 @Override
2610 public void onUpstreamChanged(@Nullable Network network) {
2611 callback.onUpstreamChanged(network);
2612 }
2613 };
2614
2615 synchronized (mTetheringEventCallbacks) {
2616 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002617 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002618 }
markchien4ef53e82019-02-27 14:56:11 +08002619 }
2620
2621 /**
2622 * Remove tethering event callback previously registered with
2623 * {@link #registerTetheringEventCallback}.
2624 *
2625 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002626 *
2627 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002628 * @hide
2629 */
2630 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002631 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002632 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2633 public void unregisterTetheringEventCallback(
2634 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002635 Objects.requireNonNull(callback, "The callback must be non-null");
2636 synchronized (mTetheringEventCallbacks) {
2637 final TetheringEventCallback tetherCallback =
2638 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002639 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002640 }
markchien4ef53e82019-02-27 14:56:11 +08002641 }
2642
2643
2644 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002645 * Get the list of regular expressions that define any tetherable
2646 * USB network interfaces. If USB tethering is not supported by the
2647 * device, this list should be empty.
2648 *
2649 * @return an array of 0 or more regular expression Strings defining
2650 * what interfaces are considered tetherable usb interfaces.
2651 *
markchien6ae63e52020-01-21 13:11:06 +08002652 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002653 * {@hide}
2654 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002655 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002656 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002657 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002658 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002659 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002660 }
2661
2662 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002663 * Get the list of regular expressions that define any tetherable
2664 * Wifi network interfaces. If Wifi tethering is not supported by the
2665 * device, this list should be empty.
2666 *
2667 * @return an array of 0 or more regular expression Strings defining
2668 * what interfaces are considered tetherable wifi interfaces.
2669 *
markchien6ae63e52020-01-21 13:11:06 +08002670 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002671 * {@hide}
2672 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002673 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002674 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002675 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002676 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002677 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002678 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002679
Danica Chang96567052010-08-11 14:54:43 -07002680 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002681 * Get the list of regular expressions that define any tetherable
2682 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2683 * device, this list should be empty.
2684 *
2685 * @return an array of 0 or more regular expression Strings defining
2686 * what interfaces are considered tetherable bluetooth interfaces.
2687 *
markchien6ae63e52020-01-21 13:11:06 +08002688 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2689 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002690 * {@hide}
2691 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002692 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002693 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002694 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002695 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002696 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002697 }
2698
Mike Lockwooded4a1742011-07-19 13:04:47 -07002699 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002700 * Attempt to both alter the mode of USB and Tethering of USB. A
2701 * utility method to deal with some of the complexity of USB - will
2702 * attempt to switch to Rndis and subsequently tether the resulting
2703 * interface on {@code true} or turn off tethering and switch off
2704 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002705 *
2706 * <p>This method requires the caller to hold either the
2707 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2708 * or the ability to modify system settings as determined by
2709 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002710 *
2711 * @param enable a boolean - {@code true} to enable tethering
2712 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002713 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002714 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002715 * {@hide}
2716 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002717 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002718 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002719 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002720 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002721 }
2722
markchien6ae63e52020-01-21 13:11:06 +08002723 /**
2724 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2725 * {@hide}
2726 */
markchien0f45bb92019-01-16 17:44:13 +08002727 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002728 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002729 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002730 /**
2731 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2732 * {@hide}
2733 */
2734 @Deprecated
2735 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2736 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2737 /**
2738 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2739 * {@hide}
2740 */
2741 @Deprecated
2742 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2743 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2744 /**
2745 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2746 * {@hide}
2747 */
2748 @Deprecated
2749 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2750 /**
2751 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2752 * {@hide}
2753 */
2754 @Deprecated
2755 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2756 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2757 /**
markchienf47d8342020-03-19 13:37:43 +08002758 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002759 * {@hide}
2760 */
2761 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002762 public static final int TETHER_ERROR_MASTER_ERROR =
2763 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002764 /**
2765 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2766 * {@hide}
2767 */
2768 @Deprecated
2769 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2770 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2771 /**
2772 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2773 * {@hide}
2774 */
2775 @Deprecated
2776 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2777 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2778 /**
markchienf47d8342020-03-19 13:37:43 +08002779 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002780 * {@hide}
2781 */
2782 @Deprecated
2783 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002784 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002785 /**
markchienf47d8342020-03-19 13:37:43 +08002786 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002787 * {@hide}
2788 */
2789 @Deprecated
2790 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002791 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002792 /**
2793 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2794 * {@hide}
2795 */
2796 @Deprecated
2797 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2798 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2799 /**
markchienf47d8342020-03-19 13:37:43 +08002800 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002801 * {@hide}
2802 */
markchien0f45bb92019-01-16 17:44:13 +08002803 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002804 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002805 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002806 /**
2807 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2808 * {@hide}
2809 */
2810 @Deprecated
2811 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2812 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2813 /**
2814 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2815 * {@hide}
2816 */
markchien0f45bb92019-01-16 17:44:13 +08002817 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002818 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002819 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002820
2821 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002822 * Get a more detailed error code after a Tethering or Untethering
2823 * request asynchronously failed.
2824 *
2825 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002826 * @return error The error code of the last error tethering or untethering the named
2827 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002828 *
markchien6ae63e52020-01-21 13:11:06 +08002829 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002830 * {@hide}
2831 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002832 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002833 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002834 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002835 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002836 int error = mTetheringManager.getLastTetherError(iface);
2837 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2838 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2839 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2840 // instead.
2841 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2842 }
2843 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002844 }
2845
markchienbf5ab012019-03-06 16:25:00 +08002846 /** @hide */
2847 @Retention(RetentionPolicy.SOURCE)
2848 @IntDef(value = {
2849 TETHER_ERROR_NO_ERROR,
2850 TETHER_ERROR_PROVISION_FAILED,
2851 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2852 })
2853 public @interface EntitlementResultCode {
2854 }
2855
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002856 /**
markchienbf5ab012019-03-06 16:25:00 +08002857 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002858 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002859 *
2860 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002861 * @hide
2862 */
2863 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002864 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002865 public interface OnTetheringEntitlementResultListener {
2866 /**
2867 * Called to notify entitlement result.
2868 *
2869 * @param resultCode an int value of entitlement result. It may be one of
2870 * {@link #TETHER_ERROR_NO_ERROR},
2871 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2872 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2873 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002874 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002875 }
2876
2877 /**
markchien0f45bb92019-01-16 17:44:13 +08002878 * Get the last value of the entitlement check on this downstream. If the cached value is
2879 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2880 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2881 * guaranteed that the UI-based entitlement check will complete in any specific time period
2882 * and may in fact never complete. Any successful entitlement check the platform performs for
2883 * any reason will update the cached value.
2884 *
2885 * @param type the downstream type of tethering. Must be one of
2886 * {@link #TETHERING_WIFI},
2887 * {@link #TETHERING_USB}, or
2888 * {@link #TETHERING_BLUETOOTH}.
2889 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002890 * @param executor the executor on which callback will be invoked.
2891 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2892 * notify the caller of the result of entitlement check. The listener may be called zero
2893 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002894 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002895 * {@hide}
2896 */
2897 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002898 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002899 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002900 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2901 @NonNull @CallbackExecutor Executor executor,
2902 @NonNull final OnTetheringEntitlementResultListener listener) {
2903 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2904 ResultReceiver wrappedListener = new ResultReceiver(null) {
2905 @Override
2906 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslinc6170bb2021-03-04 09:38:21 +08002907 final long token = Binder.clearCallingIdentity();
2908 try {
2909 executor.execute(() -> {
2910 listener.onTetheringEntitlementResult(resultCode);
2911 });
2912 } finally {
2913 Binder.restoreCallingIdentity(token);
2914 }
markchienbf5ab012019-03-06 16:25:00 +08002915 }
2916 };
2917
Amos Bianchia9b415a2020-03-04 11:07:38 -08002918 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002919 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002920 }
2921
2922 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002923 * Report network connectivity status. This is currently used only
2924 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002925 * <p>This method requires the caller to hold the permission
2926 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002927 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002928 * @param networkType The type of network you want to report on
2929 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002930 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002931 * {@hide}
2932 */
2933 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002934 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002935 try {
2936 mService.reportInetCondition(networkType, percentage);
2937 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002938 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002939 }
2940 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002941
2942 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002943 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07002944 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002945 * the framework to re-evaluate network connectivity and/or switch to another
2946 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002947 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002948 * @param network The {@link Network} the application was attempting to use
2949 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04002950 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2951 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002952 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002953 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09002954 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002955 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002956 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04002957 // One of these will be ignored because it matches system's current state.
2958 // The other will trigger the necessary reevaluation.
2959 mService.reportNetworkConnectivity(network, true);
2960 mService.reportNetworkConnectivity(network, false);
2961 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002962 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04002963 }
2964 }
2965
2966 /**
2967 * Report to the framework whether a network has working connectivity.
2968 * This provides a hint to the system that a particular network is providing
2969 * working connectivity or not. In response the framework may re-evaluate
2970 * the network's connectivity and might take further action thereafter.
2971 *
2972 * @param network The {@link Network} the application was attempting to use
2973 * or {@code null} to indicate the current default network.
2974 * @param hasConnectivity {@code true} if the application was able to successfully access the
2975 * Internet using {@code network} or {@code false} if not.
2976 */
Chalard Jean158702d2019-01-07 19:26:34 +09002977 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002978 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04002979 try {
2980 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002981 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002982 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002983 }
2984 }
2985
2986 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002987 * Set a network-independent global http proxy. This is not normally what you want
2988 * for typical HTTP proxies - they are general network dependent. However if you're
2989 * doing something unusual like general internal filtering this may be useful. On
2990 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002991 *
2992 * @param p A {@link ProxyInfo} object defining the new global
2993 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002994 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002995 */
paulhu8e96a752019-08-12 16:25:11 +08002996 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04002997 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002998 try {
2999 mService.setGlobalProxy(p);
3000 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003001 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003002 }
3003 }
3004
3005 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003006 * Retrieve any network-independent global HTTP proxy.
3007 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003008 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003009 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003010 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003011 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003012 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003013 try {
3014 return mService.getGlobalProxy();
3015 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003016 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003017 }
3018 }
3019
3020 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003021 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3022 * network-specific HTTP proxy. If {@code network} is null, the
3023 * network-specific proxy returned is the proxy of the default active
3024 * network.
3025 *
3026 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3027 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3028 * or when {@code network} is {@code null},
3029 * the {@code ProxyInfo} for the default active network. Returns
3030 * {@code null} when no proxy applies or the caller doesn't have
3031 * permission to use {@code network}.
3032 * @hide
3033 */
3034 public ProxyInfo getProxyForNetwork(Network network) {
3035 try {
3036 return mService.getProxyForNetwork(network);
3037 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003038 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003039 }
3040 }
3041
3042 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003043 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3044 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003045 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003046 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003047 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003048 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003049 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003050 */
Chalard Jean158702d2019-01-07 19:26:34 +09003051 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003052 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003053 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003054 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003055
3056 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003057 * Returns true if the hardware supports the given network type
3058 * else it returns false. This doesn't indicate we have coverage
3059 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003060 * hardware supports it. For example a GSM phone without a SIM
3061 * should still return {@code true} for mobile data, but a wifi only
3062 * tablet would return {@code false}.
3063 *
3064 * @param networkType The network type we'd like to check
3065 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003066 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003067 * @hide
3068 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003069 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003070 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003071 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003072 public boolean isNetworkSupported(int networkType) {
3073 try {
3074 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003075 } catch (RemoteException e) {
3076 throw e.rethrowFromSystemServer();
3077 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003078 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003079
3080 /**
3081 * Returns if the currently active data network is metered. A network is
3082 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003083 * that connection due to monetary costs, data limitations or
3084 * battery/performance issues. You should check this before doing large
3085 * data transfers, and warn the user or delay the operation until another
3086 * network is available.
3087 *
3088 * @return {@code true} if large transfers should be avoided, otherwise
3089 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003090 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003091 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003092 public boolean isActiveNetworkMetered() {
3093 try {
3094 return mService.isActiveNetworkMetered();
3095 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003096 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003097 }
3098 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003099
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003100 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003101 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003102 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003103 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003104 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003105 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003106 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003107 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003108 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003109 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003110 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003111 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003112 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003113 }
3114 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003115
3116 /**
3117 * Set the value for enabling/disabling airplane mode
3118 *
3119 * @param enable whether to enable airplane mode or not
3120 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003121 * @hide
3122 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003123 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003124 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003125 android.Manifest.permission.NETWORK_SETTINGS,
3126 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3127 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003128 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003129 public void setAirplaneMode(boolean enable) {
3130 try {
3131 mService.setAirplaneMode(enable);
3132 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003133 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003134 }
3135 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003136
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003137 /**
3138 * Registers the specified {@link NetworkProvider}.
3139 * Each listener must only be registered once. The listener can be unregistered with
3140 * {@link #unregisterNetworkProvider}.
3141 *
3142 * @param provider the provider to register
3143 * @return the ID of the provider. This ID must be used by the provider when registering
3144 * {@link android.net.NetworkAgent}s.
3145 * @hide
3146 */
3147 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003148 @RequiresPermission(anyOf = {
3149 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3150 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003151 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3152 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003153 throw new IllegalStateException("NetworkProviders can only be registered once");
3154 }
3155
3156 try {
3157 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3158 provider.getName());
3159 provider.setProviderId(providerId);
3160 } catch (RemoteException e) {
3161 throw e.rethrowFromSystemServer();
3162 }
3163 return provider.getProviderId();
3164 }
3165
3166 /**
3167 * Unregisters the specified NetworkProvider.
3168 *
3169 * @param provider the provider to unregister
3170 * @hide
3171 */
3172 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003173 @RequiresPermission(anyOf = {
3174 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3175 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003176 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3177 try {
3178 mService.unregisterNetworkProvider(provider.getMessenger());
3179 } catch (RemoteException e) {
3180 throw e.rethrowFromSystemServer();
3181 }
3182 provider.setProviderId(NetworkProvider.ID_NONE);
3183 }
3184
3185
3186 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003187 @RequiresPermission(anyOf = {
3188 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3189 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003190 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3191 try {
3192 mService.declareNetworkRequestUnfulfillable(request);
3193 } catch (RemoteException e) {
3194 throw e.rethrowFromSystemServer();
3195 }
3196 }
3197
Chalard Jean29d06db2018-05-02 21:14:54 +09003198 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3199 // of dependent changes that would conflict throughout the automerger graph. Having this
3200 // temporarily helps with the process of going through with all these dependent changes across
3201 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003202 /**
3203 * @hide
3204 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003205 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003206 */
paulhub6ba8e82020-03-04 09:43:41 +08003207 @RequiresPermission(anyOf = {
3208 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3209 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003210 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003211 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003212 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003213 }
3214
3215 /**
3216 * @hide
3217 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003218 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003219 */
paulhub6ba8e82020-03-04 09:43:41 +08003220 @RequiresPermission(anyOf = {
3221 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3222 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003223 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003224 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003225 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003226 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003227 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003228 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003229 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003230 }
3231
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003232 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003233 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3234 * changes. Should be extended by applications wanting notifications.
3235 *
3236 * A {@code NetworkCallback} is registered by calling
3237 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3238 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003239 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003240 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3241 * A {@code NetworkCallback} should be registered at most once at any time.
3242 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003243 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003244 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003245 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003246 * Called when the framework connects to a new network to evaluate whether it satisfies this
3247 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3248 * callback. There is no guarantee that this new network will satisfy any requests, or that
3249 * the network will stay connected for longer than the time necessary to evaluate it.
3250 * <p>
3251 * Most applications <b>should not</b> act on this callback, and should instead use
3252 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3253 * the framework in properly evaluating the network &mdash; for example, an application that
3254 * can automatically log in to a captive portal without user intervention.
3255 *
3256 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003257 *
3258 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003259 */
paulhu1a407652019-03-22 16:35:06 +08003260 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003261
3262 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003263 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003264 * This callback may be called more than once if the {@link Network} that is
3265 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003266 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003267 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003268 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3269 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003270 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003271 * @hide
3272 */
paulhu1a407652019-03-22 16:35:06 +08003273 public void onAvailable(@NonNull Network network,
3274 @NonNull NetworkCapabilities networkCapabilities,
3275 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003276 // Internally only this method is called when a new network is available, and
3277 // it calls the callback in the same way and order that older versions used
3278 // to call so as not to change the behavior.
3279 onAvailable(network);
3280 if (!networkCapabilities.hasCapability(
3281 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3282 onNetworkSuspended(network);
3283 }
3284 onCapabilitiesChanged(network, networkCapabilities);
3285 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003286 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003287 }
3288
3289 /**
3290 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003291 *
3292 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3293 * be available at the same time, and onAvailable will be called for each of these as they
3294 * appear.
3295 *
3296 * <p>For callbacks registered with {@link #requestNetwork} and
3297 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3298 * is the new best network for this request and is now tracked by this callback ; this
3299 * callback will no longer receive method calls about other networks that may have been
3300 * passed to this method previously. The previously-best network may have disconnected, or
3301 * it may still be around and the newly-best network may simply be better.
3302 *
3303 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3304 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3305 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3306 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3307 *
3308 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3309 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3310 * this callback as this is prone to race conditions (there is no guarantee the objects
3311 * returned by these methods will be current). Instead, wait for a call to
3312 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3313 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3314 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003315 *
3316 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003317 */
paulhu1a407652019-03-22 16:35:06 +08003318 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003319
3320 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003321 * Called when the network is about to be lost, typically because there are no outstanding
3322 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3323 * with the new replacement network for graceful handover. This method is not guaranteed
3324 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3325 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003326 *
Chalard Jean01378b62019-08-30 16:27:28 +09003327 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3328 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3329 * this callback as this is prone to race conditions ; calling these methods while in a
3330 * callback may return an outdated or even a null object.
3331 *
3332 * @param network The {@link Network} that is about to be lost.
3333 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3334 * connected for graceful handover; note that the network may still
3335 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003336 */
paulhu1a407652019-03-22 16:35:06 +08003337 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003338
3339 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003340 * Called when a network disconnects or otherwise no longer satisfies this request or
3341 * callback.
3342 *
3343 * <p>If the callback was registered with requestNetwork() or
3344 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3345 * returned by onAvailable() when that network is lost and no other network satisfies
3346 * the criteria of the request.
3347 *
3348 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3349 * each network which no longer satisfies the criteria of the callback.
3350 *
3351 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3352 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3353 * this callback as this is prone to race conditions ; calling these methods while in a
3354 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003355 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003356 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003357 */
paulhu1a407652019-03-22 16:35:06 +08003358 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003359
3360 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003361 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003362 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3363 * requested network request cannot be fulfilled (whether or not a timeout was
3364 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003365 * {@link NetworkRequest} will have already been removed and released, as if
3366 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003367 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003368 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003369
3370 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003371 * Called when the network corresponding to this request changes capabilities but still
3372 * satisfies the requested criteria.
3373 *
3374 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3375 * to be called immediately after {@link #onAvailable}.
3376 *
3377 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3378 * ConnectivityManager methods in this callback as this is prone to race conditions :
3379 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003380 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003381 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003382 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3383 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003384 */
paulhu1a407652019-03-22 16:35:06 +08003385 public void onCapabilitiesChanged(@NonNull Network network,
3386 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003387
3388 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003389 * Called when the network corresponding to this request changes {@link LinkProperties}.
3390 *
3391 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3392 * to be called immediately after {@link #onAvailable}.
3393 *
3394 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3395 * ConnectivityManager methods in this callback as this is prone to race conditions :
3396 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003397 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003398 * @param network The {@link Network} whose link properties have changed.
3399 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003400 */
paulhu1a407652019-03-22 16:35:06 +08003401 public void onLinkPropertiesChanged(@NonNull Network network,
3402 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003403
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003404 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003405 * Called when the network the framework connected to for this request suspends data
3406 * transmission temporarily.
3407 *
3408 * <p>This generally means that while the TCP connections are still live temporarily
3409 * network data fails to transfer. To give a specific example, this is used on cellular
3410 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3411 * means read operations on sockets on this network will block once the buffers are
3412 * drained, and write operations will block once the buffers are full.
3413 *
3414 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3415 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3416 * this callback as this is prone to race conditions (there is no guarantee the objects
3417 * returned by these methods will be current).
3418 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003419 * @hide
3420 */
paulhu1a407652019-03-22 16:35:06 +08003421 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003422
3423 /**
3424 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003425 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3426 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003427
3428 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3429 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3430 * this callback as this is prone to race conditions : calling these methods while in a
3431 * callback may return an outdated or even a null object.
3432 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003433 * @hide
3434 */
paulhu1a407652019-03-22 16:35:06 +08003435 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003436
junyulaif2c67e42018-08-07 19:50:45 +08003437 /**
3438 * Called when access to the specified network is blocked or unblocked.
3439 *
Chalard Jean01378b62019-08-30 16:27:28 +09003440 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3441 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3442 * this callback as this is prone to race conditions : calling these methods while in a
3443 * callback may return an outdated or even a null object.
3444 *
junyulaif2c67e42018-08-07 19:50:45 +08003445 * @param network The {@link Network} whose blocked status has changed.
3446 * @param blocked The blocked status of this {@link Network}.
3447 */
junyulai7e06ad42019-03-04 22:45:36 +08003448 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003449
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003450 private NetworkRequest networkRequest;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003451 }
3452
Hugo Benichia590ab82017-05-11 13:16:17 +09003453 /**
3454 * Constant error codes used by ConnectivityService to communicate about failures and errors
3455 * across a Binder boundary.
3456 * @hide
3457 */
3458 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003459 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003460 }
3461
3462 /** @hide */
3463 public static class TooManyRequestsException extends RuntimeException {}
3464
3465 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3466 switch (e.errorCode) {
3467 case Errors.TOO_MANY_REQUESTS:
3468 return new TooManyRequestsException();
3469 default:
3470 Log.w(TAG, "Unknown service error code " + e.errorCode);
3471 return new RuntimeException(e);
3472 }
3473 }
3474
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003475 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003476 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003477 public static final int CALLBACK_PRECHECK = BASE + 1;
3478 /** @hide */
3479 public static final int CALLBACK_AVAILABLE = BASE + 2;
3480 /** @hide arg1 = TTL */
3481 public static final int CALLBACK_LOSING = BASE + 3;
3482 /** @hide */
3483 public static final int CALLBACK_LOST = BASE + 4;
3484 /** @hide */
3485 public static final int CALLBACK_UNAVAIL = BASE + 5;
3486 /** @hide */
3487 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3488 /** @hide */
3489 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003490 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003491 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003492 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003493 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003494 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003495 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003496 /** @hide */
3497 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003498
Erik Kline155a59a2015-11-25 12:49:38 +09003499 /** @hide */
3500 public static String getCallbackName(int whichCallback) {
3501 switch (whichCallback) {
3502 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3503 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3504 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3505 case CALLBACK_LOST: return "CALLBACK_LOST";
3506 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3507 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3508 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003509 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3510 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3511 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003512 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003513 default:
3514 return Integer.toString(whichCallback);
3515 }
3516 }
3517
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003518 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003519 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003520 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003521
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003522 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003523 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003524 }
3525
Hugo Benichifd44e912017-02-02 17:02:36 +09003526 CallbackHandler(Handler handler) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003527 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003528 }
3529
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003530 @Override
3531 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003532 if (message.what == EXPIRE_LEGACY_REQUEST) {
3533 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3534 return;
3535 }
3536
3537 final NetworkRequest request = getObject(message, NetworkRequest.class);
3538 final Network network = getObject(message, Network.class);
3539 final NetworkCallback callback;
3540 synchronized (sCallbacks) {
3541 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003542 if (callback == null) {
3543 Log.w(TAG,
3544 "callback not found for " + getCallbackName(message.what) + " message");
3545 return;
3546 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003547 if (message.what == CALLBACK_UNAVAIL) {
3548 sCallbacks.remove(request);
3549 callback.networkRequest = ALREADY_UNREGISTERED;
3550 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003551 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003552 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003553 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003554 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003555
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003556 switch (message.what) {
3557 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003558 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003559 break;
3560 }
3561 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003562 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3563 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003564 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003565 break;
3566 }
3567 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003568 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003569 break;
3570 }
3571 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003572 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003573 break;
3574 }
3575 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003576 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003577 break;
3578 }
3579 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003580 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3581 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003582 break;
3583 }
3584 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003585 LinkProperties lp = getObject(message, LinkProperties.class);
3586 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003587 break;
3588 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003589 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003590 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003591 break;
3592 }
3593 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003594 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003595 break;
3596 }
junyulaif2c67e42018-08-07 19:50:45 +08003597 case CALLBACK_BLK_CHANGED: {
3598 boolean blocked = message.arg1 != 0;
3599 callback.onBlockedStatusChanged(network, blocked);
3600 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003601 }
3602 }
3603
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003604 private <T> T getObject(Message msg, Class<T> c) {
3605 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003606 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003607 }
3608
Hugo Benichifd44e912017-02-02 17:02:36 +09003609 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003610 synchronized (sCallbacks) {
3611 if (sCallbackHandler == null) {
3612 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003613 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003614 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003615 }
3616 }
3617
Hugo Benichibc4ac972017-02-03 14:18:44 +09003618 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3619 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003620
Hugo Benichibc4ac972017-02-03 14:18:44 +09003621 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003622 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003623 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003624 checkCallbackNotNull(callback);
junyulaiad010792021-01-11 16:53:38 +08003625 Preconditions.checkArgument(
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09003626 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3627 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003628 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003629 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003630 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003631 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003632 if (callback.networkRequest != null
3633 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003634 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3635 // and requests (http://b/20701525).
3636 Log.e(TAG, "NetworkCallback was already registered");
3637 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003638 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003639 Binder binder = new Binder();
junyulaiad010792021-01-11 16:53:38 +08003640 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003641 request = mService.listenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003642 need, messenger, binder, callingPackageName,
3643 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003644 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003645 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003646 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3647 callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003648 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003649 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003650 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003651 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003652 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003653 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003654 } catch (RemoteException e) {
3655 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003656 } catch (ServiceSpecificException e) {
3657 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003658 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003659 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003660 }
3661
3662 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003663 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003664 *
markchienfac84a22020-03-18 21:16:15 +08003665 * This API is only for use in internal system code that requests networks with legacy type and
3666 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003667 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003668 *
markchiend6eeffd2020-01-14 00:55:21 +08003669 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003670 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3671 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3672 * be a positive value (i.e. >0).
3673 * @param legacyType to specify the network type(#TYPE_*).
3674 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003675 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3676 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003677 *
3678 * @hide
3679 */
markchiend6eeffd2020-01-14 00:55:21 +08003680 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003681 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003682 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003683 int timeoutMs, int legacyType, @NonNull Handler handler,
3684 @NonNull NetworkCallback networkCallback) {
3685 if (legacyType == TYPE_NONE) {
3686 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3687 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003688 CallbackHandler cbHandler = new CallbackHandler(handler);
3689 NetworkCapabilities nc = request.networkCapabilities;
3690 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003691 }
3692
3693 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003694 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003695 *
Chalard Jean01378b62019-08-30 16:27:28 +09003696 * <p>This method will attempt to find the best network that matches the passed
3697 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3698 * criteria. The platform will evaluate which network is the best at its own discretion.
3699 * Throughput, latency, cost per byte, policy, user preference and other considerations
3700 * may be factored in the decision of what is considered the best network.
3701 *
3702 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3703 * matching this request, while always attempting to match the request to a better network if
3704 * possible. If a better match is found, the platform will switch this request to the now-best
3705 * network and inform the app of the newly best network by invoking
3706 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3707 * will not try to maintain any other network than the best one currently matching the request:
3708 * a network not matching any network request may be disconnected at any time.
3709 *
3710 * <p>For example, an application could use this method to obtain a connected cellular network
3711 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3712 * radio to consume additional power. Or, an application could inform the system that it wants
3713 * a network supporting sending MMSes and have the system let it know about the currently best
3714 * MMS-supporting network through the provided {@link NetworkCallback}.
3715 *
3716 * <p>The status of the request can be followed by listening to the various callbacks described
3717 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3718 * used to direct traffic to the network (although accessing some networks may be subject to
3719 * holding specific permissions). Callers will learn about the specific characteristics of the
3720 * network through
3721 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3722 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3723 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3724 * matching the request at any given time; therefore when a better network matching the request
3725 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3726 * with the new network after which no further updates are given about the previously-best
3727 * network, unless it becomes the best again at some later time. All callbacks are invoked
3728 * in order on the same thread, which by default is a thread created by the framework running
3729 * in the app.
3730 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3731 * callbacks are invoked.
3732 *
3733 * <p>This{@link NetworkRequest} will live until released via
3734 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3735 * which point the system may let go of the network at any time.
3736 *
3737 * <p>A version of this method which takes a timeout is
3738 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3739 * wait for a limited amount of time for the network to become unavailable.
3740 *
Paul Jensenee52d232015-06-16 15:11:58 -04003741 * <p>It is presently unsupported to request a network with mutable
3742 * {@link NetworkCapabilities} such as
3743 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3744 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3745 * as these {@code NetworkCapabilities} represent states that a particular
3746 * network may never attain, and whether a network will attain these states
3747 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003748 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003749 *
3750 * <p>This method requires the caller to hold either the
3751 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3752 * or the ability to modify system settings as determined by
3753 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003754 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003755 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3756 * number of outstanding requests to 100 per app (identified by their UID), shared with
3757 * all variants of this method, of {@link #registerNetworkCallback} as well as
3758 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3759 * Requesting a network with this method will count toward this limit. If this limit is
3760 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3761 * make sure to unregister the callbacks with
3762 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3763 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003764 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003765 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3766 * the callback must not be shared - it uniquely specifies this request.
3767 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003768 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3769 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003770 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003771 */
Chalard Jean158702d2019-01-07 19:26:34 +09003772 public void requestNetwork(@NonNull NetworkRequest request,
3773 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003774 requestNetwork(request, networkCallback, getDefaultHandler());
3775 }
3776
3777 /**
3778 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3779 *
Chalard Jean01378b62019-08-30 16:27:28 +09003780 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3781 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003782 *
Chalard Jean01378b62019-08-30 16:27:28 +09003783 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003784 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3785 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003786 *
3787 * @param request {@link NetworkRequest} describing this request.
3788 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3789 * the callback must not be shared - it uniquely specifies this request.
3790 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003791 */
Chalard Jean158702d2019-01-07 19:26:34 +09003792 public void requestNetwork(@NonNull NetworkRequest request,
3793 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003794 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003795 NetworkCapabilities nc = request.networkCapabilities;
3796 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003797 }
3798
3799 /**
Etan Cohenf67bde92017-03-01 12:47:28 -08003800 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3801 * by a timeout.
3802 *
3803 * This function behaves identically to the non-timed-out version
3804 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3805 * is not found within the given time (in milliseconds) the
3806 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3807 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3808 * not have to be released if timed-out (it is automatically released). Unregistering a
3809 * request that timed out is not an error.
3810 *
3811 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3812 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3813 * for that purpose. Calling this method will attempt to bring up the requested network.
3814 *
Chalard Jean01378b62019-08-30 16:27:28 +09003815 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003816 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3817 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003818 *
3819 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003820 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3821 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003822 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3823 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3824 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003825 */
Chalard Jean158702d2019-01-07 19:26:34 +09003826 public void requestNetwork(@NonNull NetworkRequest request,
3827 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003828 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003829 NetworkCapabilities nc = request.networkCapabilities;
3830 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3831 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003832 }
3833
Hugo Benichifd44e912017-02-02 17:02:36 +09003834 /**
3835 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3836 * by a timeout.
3837 *
Chalard Jean01378b62019-08-30 16:27:28 +09003838 * This method behaves identically to
3839 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3840 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003841 *
Chalard Jean01378b62019-08-30 16:27:28 +09003842 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003843 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3844 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003845 *
3846 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003847 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3848 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003849 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003850 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3851 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003852 */
Chalard Jean158702d2019-01-07 19:26:34 +09003853 public void requestNetwork(@NonNull NetworkRequest request,
3854 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003855 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003856 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003857 NetworkCapabilities nc = request.networkCapabilities;
3858 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003859 }
3860
3861 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003862 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003863 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003864 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003865 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003866 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3867 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003868 */
Erik Kline8a826212014-11-19 12:12:24 +09003869 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003870
3871 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003872 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003873 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003874 * {@link android.content.Intent#getParcelableExtra(String)}.
3875 */
Erik Kline8a826212014-11-19 12:12:24 +09003876 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003877
3878
3879 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003880 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003881 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003882 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003883 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003884 * the request may outlive the calling application and get called back when a suitable
3885 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003886 * <p>
3887 * The operation is an Intent broadcast that goes to a broadcast receiver that
3888 * you registered with {@link Context#registerReceiver} or through the
3889 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3890 * <p>
3891 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003892 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3893 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003894 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003895 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003896 * Intent to reserve the network or it will be released shortly after the Intent
3897 * is processed.
3898 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003899 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003900 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003901 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003902 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003903 * The request may be released normally by calling
3904 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003905 * <p>It is presently unsupported to request a network with either
3906 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3907 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3908 * as these {@code NetworkCapabilities} represent states that a particular
3909 * network may never attain, and whether a network will attain these states
3910 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003911 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003912 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003913 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3914 * number of outstanding requests to 100 per app (identified by their UID), shared with
3915 * all variants of this method, of {@link #registerNetworkCallback} as well as
3916 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3917 * Requesting a network with this method will count toward this limit. If this limit is
3918 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3919 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3920 * or {@link #releaseNetworkRequest(PendingIntent)}.
3921 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003922 * <p>This method requires the caller to hold either the
3923 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3924 * or the ability to modify system settings as determined by
3925 * {@link android.provider.Settings.System#canWrite}.</p>
3926 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003927 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003928 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003929 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003930 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09003931 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3932 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003933 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003934 */
Chalard Jean158702d2019-01-07 19:26:34 +09003935 public void requestNetwork(@NonNull NetworkRequest request,
3936 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003937 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003938 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003939 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003940 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003941 request.networkCapabilities, operation, mContext.getOpPackageName(),
3942 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003943 } catch (RemoteException e) {
3944 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003945 } catch (ServiceSpecificException e) {
3946 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003947 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003948 }
3949
3950 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003951 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3952 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09003953 * This method has the same behavior as
3954 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003955 * releasing network resources and disconnecting.
3956 *
3957 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3958 * PendingIntent passed to
3959 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3960 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3961 */
Chalard Jean158702d2019-01-07 19:26:34 +09003962 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003963 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003964 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003965 try {
3966 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003967 } catch (RemoteException e) {
3968 throw e.rethrowFromSystemServer();
3969 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003970 }
3971
Hugo Benichibc1104b2017-05-09 15:19:01 +09003972 private static void checkPendingIntentNotNull(PendingIntent intent) {
3973 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3974 }
3975
3976 private static void checkCallbackNotNull(NetworkCallback callback) {
3977 Preconditions.checkNotNull(callback, "null NetworkCallback");
3978 }
3979
3980 private static void checkTimeout(int timeoutMs) {
3981 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003982 }
3983
3984 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003985 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003986 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08003987 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3988 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003989 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003990 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3991 * number of outstanding requests to 100 per app (identified by their UID), shared with
3992 * all variants of this method, of {@link #requestNetwork} as well as
3993 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3994 * Requesting a network with this method will count toward this limit. If this limit is
3995 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3996 * make sure to unregister the callbacks with
3997 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3998 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003999 * @param request {@link NetworkRequest} describing this request.
4000 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4001 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004002 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004003 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004004 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004005 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004006 public void registerNetworkCallback(@NonNull NetworkRequest request,
4007 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004008 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4009 }
4010
4011 /**
4012 * Registers to receive notifications about all networks which satisfy the given
4013 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004014 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4015 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004016 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004017 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4018 * number of outstanding requests to 100 per app (identified by their UID), shared with
4019 * all variants of this method, of {@link #requestNetwork} as well as
4020 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4021 * Requesting a network with this method will count toward this limit. If this limit is
4022 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4023 * make sure to unregister the callbacks with
4024 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4025 *
4026 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004027 * @param request {@link NetworkRequest} describing this request.
4028 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4029 * networks change state.
4030 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004031 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004032 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004033 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004034 public void registerNetworkCallback(@NonNull NetworkRequest request,
4035 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004036 CallbackHandler cbHandler = new CallbackHandler(handler);
4037 NetworkCapabilities nc = request.networkCapabilities;
4038 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004039 }
4040
4041 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004042 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4043 * {@link NetworkRequest}.
4044 *
4045 * This function behaves identically to the version that takes a NetworkCallback, but instead
4046 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4047 * the request may outlive the calling application and get called back when a suitable
4048 * network is found.
4049 * <p>
4050 * The operation is an Intent broadcast that goes to a broadcast receiver that
4051 * you registered with {@link Context#registerReceiver} or through the
4052 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4053 * <p>
4054 * The operation Intent is delivered with two extras, a {@link Network} typed
4055 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4056 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4057 * the original requests parameters.
4058 * <p>
4059 * If there is already a request for this Intent registered (with the equality of
4060 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4061 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4062 * <p>
4063 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004064 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004065 *
4066 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4067 * number of outstanding requests to 100 per app (identified by their UID), shared with
4068 * all variants of this method, of {@link #requestNetwork} as well as
4069 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4070 * Requesting a network with this method will count toward this limit. If this limit is
4071 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4072 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4073 * or {@link #releaseNetworkRequest(PendingIntent)}.
4074 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004075 * @param request {@link NetworkRequest} describing this request.
4076 * @param operation Action to perform when the network is available (corresponds
4077 * to the {@link NetworkCallback#onAvailable} call. Typically
4078 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004079 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004080 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004081 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004082 public void registerNetworkCallback(@NonNull NetworkRequest request,
4083 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004084 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004085 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004086 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004087 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004088 request.networkCapabilities, operation, mContext.getOpPackageName(),
4089 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004090 } catch (RemoteException e) {
4091 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004092 } catch (ServiceSpecificException e) {
4093 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004094 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004095 }
4096
4097 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004098 * Registers to receive notifications about changes in the application's default network. This
4099 * may be a physical network or a virtual network, such as a VPN that applies to the
4100 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004101 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004102 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004103 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4104 * number of outstanding requests to 100 per app (identified by their UID), shared with
4105 * all variants of this method, of {@link #requestNetwork} as well as
4106 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4107 * Requesting a network with this method will count toward this limit. If this limit is
4108 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4109 * make sure to unregister the callbacks with
4110 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4111 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004112 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004113 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004114 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004115 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004116 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004117 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004118 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004119 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4120 }
4121
4122 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004123 * Registers to receive notifications about changes in the application's default network. This
4124 * may be a physical network or a virtual network, such as a VPN that applies to the
4125 * application. The callbacks will continue to be called until either the application exits or
4126 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4127 *
4128 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4129 * number of outstanding requests to 100 per app (identified by their UID), shared with
4130 * all variants of this method, of {@link #requestNetwork} as well as
4131 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4132 * Requesting a network with this method will count toward this limit. If this limit is
4133 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4134 * make sure to unregister the callbacks with
4135 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4136 *
4137 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4138 * application's default network changes.
4139 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4140 * @throws RuntimeException if the app already has too many callbacks registered.
4141 */
4142 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4143 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4144 @NonNull Handler handler) {
4145 CallbackHandler cbHandler = new CallbackHandler(handler);
4146 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4147 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4148 }
4149
4150 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004151 * Registers to receive notifications about changes in the system default network. The callbacks
4152 * will continue to be called until either the application exits or
4153 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004154 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004155 * This method should not be used to determine networking state seen by applications, because in
4156 * many cases, most or even all application traffic may not use the default network directly,
4157 * and traffic from different applications may go on different networks by default. As an
4158 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4159 * and not onto the system default network. Applications or system components desiring to do
4160 * determine network state as seen by applications should use other methods such as
4161 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4162 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004163 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4164 * number of outstanding requests to 100 per app (identified by their UID), shared with
4165 * all variants of this method, of {@link #requestNetwork} as well as
4166 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4167 * Requesting a network with this method will count toward this limit. If this limit is
4168 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4169 * make sure to unregister the callbacks with
4170 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4171 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004172 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4173 * system default network changes.
4174 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004175 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004176 *
4177 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004178 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004179 @SystemApi(client = MODULE_LIBRARIES)
4180 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4181 @RequiresPermission(anyOf = {
4182 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4183 android.Manifest.permission.NETWORK_SETTINGS})
4184 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004185 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004186 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004187 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004188 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004189 }
4190
4191 /**
fenglub00f4882015-04-21 17:12:05 -07004192 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4193 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4194 * network connection for updated bandwidth information. The caller will be notified via
4195 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004196 * method assumes that the caller has previously called
4197 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4198 * changes.
fenglu3f357402015-03-20 11:29:56 -07004199 *
fengluea2d9282015-04-27 14:28:04 -07004200 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004201 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004202 */
Chalard Jean158702d2019-01-07 19:26:34 +09004203 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004204 try {
fenglub00f4882015-04-21 17:12:05 -07004205 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004206 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004207 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004208 }
4209 }
4210
4211 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004212 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004213 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4214 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4215 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004216 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4217 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004218 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004219 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4220 * triggering it as soon as this call returns.
4221 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004222 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004223 */
Chalard Jean158702d2019-01-07 19:26:34 +09004224 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004225 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004226 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004227 final List<NetworkRequest> reqs = new ArrayList<>();
4228 // Find all requests associated to this callback and stop callback triggers immediately.
4229 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4230 synchronized (sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09004231 Preconditions.checkArgument(networkCallback.networkRequest != null,
4232 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004233 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4234 Log.d(TAG, "NetworkCallback was already unregistered");
4235 return;
4236 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004237 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4238 if (e.getValue() == networkCallback) {
4239 reqs.add(e.getKey());
4240 }
4241 }
4242 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4243 for (NetworkRequest r : reqs) {
4244 try {
4245 mService.releaseNetworkRequest(r);
4246 } catch (RemoteException e) {
4247 throw e.rethrowFromSystemServer();
4248 }
4249 // Only remove mapping if rpc was successful.
4250 sCallbacks.remove(r);
4251 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004252 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004253 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004254 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004255
4256 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004257 * Unregisters a callback previously registered via
4258 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4259 *
4260 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4261 * PendingIntent passed to
4262 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4263 * Cannot be null.
4264 */
Chalard Jean158702d2019-01-07 19:26:34 +09004265 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004266 releaseNetworkRequest(operation);
4267 }
4268
4269 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004270 * Informs the system whether it should switch to {@code network} regardless of whether it is
4271 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4272 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4273 * the system default network regardless of any other network that's currently connected. If
4274 * {@code always} is true, then the choice is remembered, so that the next time the user
4275 * connects to this network, the system will switch to it.
4276 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004277 * @param network The network to accept.
4278 * @param accept Whether to accept the network even if unvalidated.
4279 * @param always Whether to remember this choice in the future.
4280 *
4281 * @hide
4282 */
lucaslin2240ef62019-03-12 13:08:03 +08004283 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004284 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4285 try {
4286 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004287 } catch (RemoteException e) {
4288 throw e.rethrowFromSystemServer();
4289 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004290 }
4291
4292 /**
lucaslin2240ef62019-03-12 13:08:03 +08004293 * Informs the system whether it should consider the network as validated even if it only has
4294 * partial connectivity. If {@code accept} is true, then the network will be considered as
4295 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4296 * is remembered, so that the next time the user connects to this network, the system will
4297 * switch to it.
4298 *
4299 * @param network The network to accept.
4300 * @param accept Whether to consider the network as validated even if it has partial
4301 * connectivity.
4302 * @param always Whether to remember this choice in the future.
4303 *
4304 * @hide
4305 */
4306 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4307 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4308 try {
4309 mService.setAcceptPartialConnectivity(network, accept, always);
4310 } catch (RemoteException e) {
4311 throw e.rethrowFromSystemServer();
4312 }
4313 }
4314
4315 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004316 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4317 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4318 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4319 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4320 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004321 * @param network The network to accept.
4322 *
4323 * @hide
4324 */
lucaslin2240ef62019-03-12 13:08:03 +08004325 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004326 public void setAvoidUnvalidated(Network network) {
4327 try {
4328 mService.setAvoidUnvalidated(network);
4329 } catch (RemoteException e) {
4330 throw e.rethrowFromSystemServer();
4331 }
4332 }
4333
4334 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004335 * Requests that the system open the captive portal app on the specified network.
4336 *
4337 * @param network The network to log into.
4338 *
4339 * @hide
4340 */
paulhu8e96a752019-08-12 16:25:11 +08004341 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004342 public void startCaptivePortalApp(Network network) {
4343 try {
4344 mService.startCaptivePortalApp(network);
4345 } catch (RemoteException e) {
4346 throw e.rethrowFromSystemServer();
4347 }
4348 }
4349
4350 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004351 * Requests that the system open the captive portal app with the specified extras.
4352 *
4353 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4354 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004355 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004356 * @param appExtras Extras to include in the app start intent.
4357 * @hide
4358 */
4359 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004360 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004361 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004362 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004363 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004364 } catch (RemoteException e) {
4365 throw e.rethrowFromSystemServer();
4366 }
4367 }
4368
4369 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004370 * Determine whether the device is configured to avoid bad wifi.
4371 * @hide
4372 */
4373 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004374 @RequiresPermission(anyOf = {
4375 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4376 android.Manifest.permission.NETWORK_STACK})
4377 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004378 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004379 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004380 } catch (RemoteException e) {
4381 throw e.rethrowFromSystemServer();
4382 }
4383 }
4384
4385 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004386 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4387 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004388 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4389 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004390 *
4391 * An example of such an operation might be a time-sensitive foreground activity, such as a
4392 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4393 */
4394 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4395
4396 /**
4397 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4398 * a backup channel for traffic that is primarily going over another network.
4399 *
4400 * An example might be maintaining backup connections to peers or servers for the purpose of
4401 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4402 * on backup paths should be negligible compared to the traffic on the main path.
4403 */
4404 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4405
4406 /**
4407 * It is acceptable to use metered data to improve network latency and performance.
4408 */
4409 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4410
4411 /**
4412 * Return value to use for unmetered networks. On such networks we currently set all the flags
4413 * to true.
4414 * @hide
4415 */
4416 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4417 MULTIPATH_PREFERENCE_HANDOVER |
4418 MULTIPATH_PREFERENCE_RELIABILITY |
4419 MULTIPATH_PREFERENCE_PERFORMANCE;
4420
4421 /** @hide */
4422 @Retention(RetentionPolicy.SOURCE)
4423 @IntDef(flag = true, value = {
4424 MULTIPATH_PREFERENCE_HANDOVER,
4425 MULTIPATH_PREFERENCE_RELIABILITY,
4426 MULTIPATH_PREFERENCE_PERFORMANCE,
4427 })
4428 public @interface MultipathPreference {
4429 }
4430
4431 /**
4432 * Provides a hint to the calling application on whether it is desirable to use the
4433 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4434 * for multipath data transfer on this network when it is not the system default network.
4435 * Applications desiring to use multipath network protocols should call this method before
4436 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004437 *
4438 * @param network The network on which the application desires to use multipath data.
4439 * If {@code null}, this method will return the a preference that will generally
4440 * apply to metered networks.
4441 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4442 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004443 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004444 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004445 try {
4446 return mService.getMultipathPreference(network);
4447 } catch (RemoteException e) {
4448 throw e.rethrowFromSystemServer();
4449 }
4450 }
4451
4452 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004453 * Resets all connectivity manager settings back to factory defaults.
4454 * @hide
4455 */
paulhu8e96a752019-08-12 16:25:11 +08004456 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004457 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004458 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004459 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004460 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004461 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004462 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004463 }
4464 }
4465
4466 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004467 * Binds the current process to {@code network}. All Sockets created in the future
4468 * (and not explicitly bound via a bound SocketFactory from
4469 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4470 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4471 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4472 * work and all host name resolutions will fail. This is by design so an application doesn't
4473 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4474 * To clear binding pass {@code null} for {@code network}. Using individually bound
4475 * Sockets created by Network.getSocketFactory().createSocket() and
4476 * performing network-specific host name resolutions via
4477 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004478 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004479 *
4480 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4481 * the current binding.
4482 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4483 */
Chalard Jean158702d2019-01-07 19:26:34 +09004484 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004485 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004486 // instantiated.
4487 return setProcessDefaultNetwork(network);
4488 }
4489
4490 /**
4491 * Binds the current process to {@code network}. All Sockets created in the future
4492 * (and not explicitly bound via a bound SocketFactory from
4493 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4494 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4495 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4496 * work and all host name resolutions will fail. This is by design so an application doesn't
4497 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4498 * To clear binding pass {@code null} for {@code network}. Using individually bound
4499 * Sockets created by Network.getSocketFactory().createSocket() and
4500 * performing network-specific host name resolutions via
4501 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4502 * {@code setProcessDefaultNetwork}.
4503 *
4504 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4505 * the current binding.
4506 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4507 * @deprecated This function can throw {@link IllegalStateException}. Use
4508 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4509 * is a direct replacement.
4510 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004511 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004512 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004513 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004514 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4515
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004516 if (netId != NETID_UNSET) {
4517 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004518 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004519
4520 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4521 return false;
4522 }
4523
4524 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004525 // Set HTTP proxy system properties to match network.
4526 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004527 try {
Remi NGUYEN VANb33335c2021-02-03 10:18:20 +09004528 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004529 } catch (SecurityException e) {
4530 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4531 Log.e(TAG, "Can't set proxy properties", e);
4532 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004533 // Must flush DNS cache as new network may have different DNS resolutions.
4534 InetAddress.clearDnsCache();
4535 // Must flush socket pool as idle sockets will be bound to previous network and may
4536 // cause subsequent fetches to be performed on old network.
4537 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004538 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004539
4540 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004541 }
4542
4543 /**
4544 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004545 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004546 *
4547 * @return {@code Network} to which this process is bound, or {@code null}.
4548 */
Chalard Jean158702d2019-01-07 19:26:34 +09004549 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004550 public Network getBoundNetworkForProcess() {
4551 // Forcing callers to call thru non-static function ensures ConnectivityManager
4552 // instantiated.
4553 return getProcessDefaultNetwork();
4554 }
4555
4556 /**
4557 * Returns the {@link Network} currently bound to this process via
4558 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4559 *
4560 * @return {@code Network} to which this process is bound, or {@code null}.
4561 * @deprecated Using this function can lead to other functions throwing
4562 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4563 * {@code getBoundNetworkForProcess} is a direct replacement.
4564 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004565 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004566 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004567 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004568 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004569 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004570 return new Network(netId);
4571 }
4572
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004573 private void unsupportedStartingFrom(int version) {
4574 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004575 // The getApplicationInfo() call we make below is not supported in system context. Let
4576 // the call through here, and rely on the fact that ConnectivityService will refuse to
4577 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004578 return;
4579 }
4580
4581 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4582 throw new UnsupportedOperationException(
4583 "This method is not supported in target SDK version " + version + " and above");
4584 }
4585 }
4586
4587 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4588 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004589 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004590 // remove these exemptions. Note that this check is not secure, and apps can still access these
4591 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4592 // so is unsupported and may break in the future. http://b/22728205
4593 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004594 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004595 }
4596
Paul Jensen8cdda642014-05-29 10:12:39 -04004597 /**
4598 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004599 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004600 *
4601 * @param network The {@link Network} to bind host resolutions from the current process to, or
4602 * {@code null} to clear the current binding.
4603 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4604 * @hide
4605 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4606 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004607 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004608 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004609 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004610 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004611 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004612 }
Felipe Leme30511352016-01-22 09:44:57 -08004613
4614 /**
4615 * Device is not restricting metered network activity while application is running on
4616 * background.
4617 */
4618 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4619
4620 /**
4621 * Device is restricting metered network activity while application is running on background,
4622 * but application is allowed to bypass it.
4623 * <p>
4624 * In this state, application should take action to mitigate metered network access.
4625 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4626 */
4627 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4628
4629 /**
4630 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004631 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004632 * In this state, application should not try to use the network while running on background,
4633 * because it would be denied.
4634 */
4635 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4636
Felipe Lemed34c9af2016-01-27 14:46:39 -08004637 /**
4638 * A change in the background metered network activity restriction has occurred.
4639 * <p>
4640 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4641 * applies to them.
4642 * <p>
4643 * This is only sent to registered receivers, not manifest receivers.
4644 */
4645 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4646 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4647 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4648
Felipe Leme7e4c1852016-01-25 11:48:04 -08004649 /** @hide */
4650 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004651 @IntDef(flag = false, value = {
4652 RESTRICT_BACKGROUND_STATUS_DISABLED,
4653 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4654 RESTRICT_BACKGROUND_STATUS_ENABLED,
4655 })
Felipe Leme30511352016-01-22 09:44:57 -08004656 public @interface RestrictBackgroundStatus {
4657 }
4658
4659 private INetworkPolicyManager getNetworkPolicyManager() {
4660 synchronized (this) {
4661 if (mNPManager != null) {
4662 return mNPManager;
4663 }
4664 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4665 .getService(Context.NETWORK_POLICY_SERVICE));
4666 return mNPManager;
4667 }
4668 }
4669
4670 /**
4671 * Determines if the calling application is subject to metered network restrictions while
4672 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004673 *
4674 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4675 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4676 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004677 */
4678 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4679 try {
4680 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4681 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004682 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004683 }
4684 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004685
4686 /**
4687 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004688 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4689 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004690 *
4691 * @return Hash of network watchlist config file. Null if config does not exist.
4692 */
Chalard Jean158702d2019-01-07 19:26:34 +09004693 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004694 public byte[] getNetworkWatchlistConfigHash() {
4695 try {
4696 return mService.getNetworkWatchlistConfigHash();
4697 } catch (RemoteException e) {
4698 Log.e(TAG, "Unable to get watchlist config hash");
4699 throw e.rethrowFromSystemServer();
4700 }
4701 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004702
4703 /**
4704 * Returns the {@code uid} of the owner of a network connection.
4705 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004706 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4707 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004708 * @param local The local {@link InetSocketAddress} of a connection.
4709 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004710 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004711 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4712 * android.os.Process#INVALID_UID} if the connection is not found.
4713 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4714 * user.
4715 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004716 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004717 public int getConnectionOwnerUid(
4718 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004719 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4720 try {
4721 return mService.getConnectionOwnerUid(connectionInfo);
4722 } catch (RemoteException e) {
4723 throw e.rethrowFromSystemServer();
4724 }
4725 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004726
4727 private void printStackTrace() {
4728 if (DEBUG) {
4729 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4730 final StringBuffer sb = new StringBuffer();
4731 for (int i = 3; i < callStack.length; i++) {
4732 final String stackTrace = callStack[i].toString();
4733 if (stackTrace == null || stackTrace.contains("android.os")) {
4734 break;
4735 }
4736 sb.append(" [").append(stackTrace).append("]");
4737 }
4738 Log.d(TAG, "StackLog:" + sb.toString());
4739 }
4740 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004741
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004742 /** @hide */
4743 public TestNetworkManager startOrGetTestNetworkManager() {
4744 final IBinder tnBinder;
4745 try {
4746 tnBinder = mService.startOrGetTestNetworkService();
4747 } catch (RemoteException e) {
4748 throw e.rethrowFromSystemServer();
4749 }
4750
4751 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4752 }
4753
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004754 /** @hide */
4755 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4756 return new ConnectivityDiagnosticsManager(mContext, mService);
4757 }
4758
Cody Kestingf53a0752020-04-15 12:33:28 -07004759 /**
4760 * Simulates a Data Stall for the specified Network.
4761 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004762 * <p>This method should only be used for tests.
4763 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004764 * <p>The caller must be the owner of the specified Network.
4765 *
4766 * @param detectionMethod The detection method used to identify the Data Stall.
4767 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4768 * @param network The Network for which a Data Stall is being simluated.
4769 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4770 * @throws SecurityException if the caller is not the owner of the given network.
4771 * @hide
4772 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004773 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004774 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4775 android.Manifest.permission.NETWORK_STACK})
4776 public void simulateDataStall(int detectionMethod, long timestampMillis,
4777 @NonNull Network network, @NonNull PersistableBundle extras) {
4778 try {
4779 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4780 } catch (RemoteException e) {
4781 e.rethrowFromSystemServer();
4782 }
4783 }
James Mattis356a8792020-10-28 21:48:54 -07004784
Daniel Brightf9e945b2020-06-15 16:10:01 -07004785 @NonNull
4786 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4787
4788 /**
4789 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4790 * receive available QoS events related to the {@link Network} and local ip + port
4791 * specified within socketInfo.
4792 * <p/>
4793 * The same {@link QosCallback} must be unregistered before being registered a second time,
4794 * otherwise {@link QosCallbackRegistrationException} is thrown.
4795 * <p/>
4796 * This API does not, in itself, require any permission if called with a network that is not
4797 * restricted. However, the underlying implementation currently only supports the IMS network,
4798 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4799 * useful, because they'd never be called back on networks that they would have access to.
4800 *
4801 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4802 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4803 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4804 * @throws RuntimeException if the app already has too many callbacks registered.
4805 *
4806 * Exceptions after the time of registration is passed through
4807 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4808 *
4809 * @param socketInfo the socket information used to match QoS events
4810 * @param callback receives qos events that satisfy socketInfo
4811 * @param executor The executor on which the callback will be invoked. The provided
4812 * {@link Executor} must run callback sequentially, otherwise the order of
4813 * callbacks cannot be guaranteed.
4814 *
4815 * @hide
4816 */
4817 @SystemApi
4818 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4819 @NonNull final QosCallback callback,
4820 @CallbackExecutor @NonNull final Executor executor) {
4821 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4822 Objects.requireNonNull(callback, "callback must be non-null");
4823 Objects.requireNonNull(executor, "executor must be non-null");
4824
4825 try {
4826 synchronized (mQosCallbackConnections) {
4827 if (getQosCallbackConnection(callback) == null) {
4828 final QosCallbackConnection connection =
4829 new QosCallbackConnection(this, callback, executor);
4830 mQosCallbackConnections.add(connection);
4831 mService.registerQosSocketCallback(socketInfo, connection);
4832 } else {
4833 Log.e(TAG, "registerQosCallback: Callback already registered");
4834 throw new QosCallbackRegistrationException();
4835 }
4836 }
4837 } catch (final RemoteException e) {
4838 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4839
4840 // The same unregister method method is called for consistency even though nothing
4841 // will be sent to the ConnectivityService since the callback was never successfully
4842 // registered.
4843 unregisterQosCallback(callback);
4844 e.rethrowFromSystemServer();
4845 } catch (final ServiceSpecificException e) {
4846 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4847 unregisterQosCallback(callback);
4848 throw convertServiceException(e);
4849 }
4850 }
4851
4852 /**
4853 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4854 * events once unregistered and can be registered a second time.
4855 * <p/>
4856 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4857 *
4858 * @param callback the callback being unregistered
4859 *
4860 * @hide
4861 */
4862 @SystemApi
4863 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4864 Objects.requireNonNull(callback, "The callback must be non-null");
4865 try {
4866 synchronized (mQosCallbackConnections) {
4867 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4868 if (connection != null) {
4869 connection.stopReceivingMessages();
4870 mService.unregisterQosCallback(connection);
4871 mQosCallbackConnections.remove(connection);
4872 } else {
4873 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4874 }
4875 }
4876 } catch (final RemoteException e) {
4877 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4878 e.rethrowFromSystemServer();
4879 }
4880 }
4881
4882 /**
4883 * Gets the connection related to the callback.
4884 *
4885 * @param callback the callback to look up
4886 * @return the related connection
4887 */
4888 @Nullable
4889 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4890 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4891 // Checking by reference here is intentional
4892 if (connection.getCallback() == callback) {
4893 return connection;
4894 }
4895 }
4896 return null;
4897 }
Junyu Laia62493f2021-01-19 11:10:56 +00004898
4899 /**
4900 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4901 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4902 * be used to request that the system provide a network without causing the network to be
4903 * in the foreground.
4904 *
4905 * <p>This method will attempt to find the best network that matches the passed
4906 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4907 * criteria. The platform will evaluate which network is the best at its own discretion.
4908 * Throughput, latency, cost per byte, policy, user preference and other considerations
4909 * may be factored in the decision of what is considered the best network.
4910 *
4911 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4912 * matching this request, while always attempting to match the request to a better network if
4913 * possible. If a better match is found, the platform will switch this request to the now-best
4914 * network and inform the app of the newly best network by invoking
4915 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4916 * will not try to maintain any other network than the best one currently matching the request:
4917 * a network not matching any network request may be disconnected at any time.
4918 *
4919 * <p>For example, an application could use this method to obtain a connected cellular network
4920 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4921 * radio to consume additional power. Or, an application could inform the system that it wants
4922 * a network supporting sending MMSes and have the system let it know about the currently best
4923 * MMS-supporting network through the provided {@link NetworkCallback}.
4924 *
4925 * <p>The status of the request can be followed by listening to the various callbacks described
4926 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4927 * used to direct traffic to the network (although accessing some networks may be subject to
4928 * holding specific permissions). Callers will learn about the specific characteristics of the
4929 * network through
4930 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4931 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4932 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4933 * matching the request at any given time; therefore when a better network matching the request
4934 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4935 * with the new network after which no further updates are given about the previously-best
4936 * network, unless it becomes the best again at some later time. All callbacks are invoked
4937 * in order on the same thread, which by default is a thread created by the framework running
4938 * in the app.
4939 *
4940 * <p>This{@link NetworkRequest} will live until released via
4941 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4942 * which point the system may let go of the network at any time.
4943 *
4944 * <p>It is presently unsupported to request a network with mutable
4945 * {@link NetworkCapabilities} such as
4946 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4947 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4948 * as these {@code NetworkCapabilities} represent states that a particular
4949 * network may never attain, and whether a network will attain these states
4950 * is unknown prior to bringing up the network so the framework does not
4951 * know how to go about satisfying a request with these capabilities.
4952 *
4953 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4954 * number of outstanding requests to 100 per app (identified by their UID), shared with
4955 * all variants of this method, of {@link #registerNetworkCallback} as well as
4956 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4957 * Requesting a network with this method will count toward this limit. If this limit is
4958 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4959 * make sure to unregister the callbacks with
4960 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4961 *
4962 * @param request {@link NetworkRequest} describing this request.
4963 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4964 * If null, the callback is invoked on the default internal Handler.
4965 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4966 * the callback must not be shared - it uniquely specifies this request.
4967 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4968 * @throws SecurityException if missing the appropriate permissions.
4969 * @throws RuntimeException if the app already has too many callbacks registered.
4970 *
4971 * @hide
4972 */
4973 @SystemApi(client = MODULE_LIBRARIES)
4974 @SuppressLint("ExecutorRegistration")
4975 @RequiresPermission(anyOf = {
4976 android.Manifest.permission.NETWORK_SETTINGS,
4977 android.Manifest.permission.NETWORK_STACK,
4978 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
4979 })
4980 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
4981 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
4982 final NetworkCapabilities nc = request.networkCapabilities;
4983 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
4984 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
4985 }
James Mattis45d81842021-01-10 14:24:24 -08004986
4987 /**
4988 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
4989 * OnSetOemNetworkPreferenceListener)}.
James Mattisda32cfe2021-01-26 16:23:52 -08004990 * @hide
James Mattis45d81842021-01-10 14:24:24 -08004991 */
James Mattisda32cfe2021-01-26 16:23:52 -08004992 @SystemApi
4993 public interface OnSetOemNetworkPreferenceListener {
James Mattis45d81842021-01-10 14:24:24 -08004994 /**
4995 * Called when setOemNetworkPreference() successfully completes.
4996 */
4997 void onComplete();
4998 }
4999
5000 /**
5001 * Used by automotive devices to set the network preferences used to direct traffic at an
5002 * application level as per the given OemNetworkPreferences. An example use-case would be an
5003 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5004 * vehicle via a particular network.
5005 *
5006 * Calling this will overwrite the existing preference.
5007 *
5008 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5009 * @param executor the executor on which listener will be invoked.
5010 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5011 * communicate completion of setOemNetworkPreference(). This will only be
5012 * called once upon successful completion of setOemNetworkPreference().
5013 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5014 * @throws SecurityException if missing the appropriate permissions.
5015 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005016 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005017 */
James Mattisda32cfe2021-01-26 16:23:52 -08005018 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005019 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005020 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005021 @Nullable @CallbackExecutor final Executor executor,
5022 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5023 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5024 if (null != listener) {
5025 Objects.requireNonNull(executor, "Executor must be non-null");
5026 }
5027 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5028 new IOnSetOemNetworkPreferenceListener.Stub() {
5029 @Override
5030 public void onComplete() {
5031 executor.execute(listener::onComplete);
5032 }
5033 };
5034
5035 try {
5036 mService.setOemNetworkPreference(preference, listenerInternal);
5037 } catch (RemoteException e) {
5038 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5039 throw e.rethrowFromSystemServer();
5040 }
5041 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005042}