blob: adab6e3fbc8f3587a9796c1b28afcf3928421d88 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Project28527d22009-03-03 19:31:44 -080016package android.net;
17
Junyu Laia62493f2021-01-19 11:10:56 +000018import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
junyulaid05a1922019-01-15 11:32:44 +080019import static android.net.IpSecManager.INVALID_RESOURCE_ID;
Junyu Laia62493f2021-01-19 11:10:56 +000020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaiad010792021-01-11 16:53:38 +080021import static android.net.NetworkRequest.Type.LISTEN;
22import static android.net.NetworkRequest.Type.REQUEST;
23import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +090024import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Daniel Brightf9e945b2020-06-15 16:10:01 -070025import static android.net.QosCallback.QosCallbackRegistrationException;
junyulaid05a1922019-01-15 11:32:44 +080026
junyulai4c95b082018-12-27 17:25:29 +080027import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080028import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090029import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000030import android.annotation.Nullable;
Jeff Sharkey656584a2017-04-24 11:18:03 -060031import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080032import android.annotation.SdkConstant;
33import android.annotation.SdkConstant.SdkConstantType;
Junyu Laia62493f2021-01-19 11:10:56 +000034import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080035import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060036import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070037import android.app.PendingIntent;
Artur Satayev9c2add62019-12-10 17:47:52 +000038import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070039import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070040import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080041import android.net.IpSecManager.UdpEncapsulationSocket;
42import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080043import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080044import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080045import android.net.TetheringManager.TetheringRequest;
Robert Greenwalt2034b912009-08-12 16:08:25 -070046import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000047import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070048import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080049import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070050import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080051import android.os.IBinder;
52import android.os.INetworkActivityListener;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070053import android.os.Looper;
54import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070055import android.os.Messenger;
junyulai7e06ad42019-03-04 22:45:36 +080056import android.os.ParcelFileDescriptor;
Cody Kestingf53a0752020-04-15 12:33:28 -070057import android.os.PersistableBundle;
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +090058import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080059import android.os.RemoteException;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080060import android.os.ResultReceiver;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080061import android.os.ServiceManager;
Hugo Benichia590ab82017-05-11 13:16:17 +090062import android.os.ServiceSpecificException;
Jeff Sharkey971cd162011-08-29 16:02:57 -070063import android.provider.Settings;
Wink Saville689f7042014-12-05 11:10:30 -080064import android.telephony.SubscriptionManager;
Meng Wanged6f4412019-11-18 17:10:00 -080065import android.telephony.TelephonyManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080066import android.util.ArrayMap;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070067import android.util.Log;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090068import android.util.Range;
Erik Klinece55eb12017-01-26 18:08:28 +090069import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080070
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090071import com.android.connectivity.aidl.INetworkAgent;
markchien6ae63e52020-01-21 13:11:06 +080072import com.android.internal.annotations.GuardedBy;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090073import com.android.internal.util.Preconditions;
74import com.android.internal.util.Protocol;
Robert Greenwalt0c150c02014-05-21 20:04:36 -070075
Paul Jensen3e2917c2014-08-27 12:38:45 -040076import libcore.net.event.NetworkEventDispatcher;
77
junyulai7e06ad42019-03-04 22:45:36 +080078import java.io.IOException;
79import java.io.UncheckedIOException;
Felipe Leme30511352016-01-22 09:44:57 -080080import java.lang.annotation.Retention;
81import java.lang.annotation.RetentionPolicy;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090082import java.net.DatagramSocket;
Jeremy Klein434835a2015-12-28 15:11:58 -080083import java.net.InetAddress;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070084import java.net.InetSocketAddress;
junyulai0835a1e2019-01-08 20:04:33 +080085import java.net.Socket;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090086import java.util.ArrayList;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090087import java.util.Collection;
Jeremy Klein434835a2015-12-28 15:11:58 -080088import java.util.HashMap;
Hugo Benichi2aa65af2017-03-06 09:17:06 +090089import java.util.List;
90import java.util.Map;
markchien6ae63e52020-01-21 13:11:06 +080091import java.util.Objects;
junyulai4c95b082018-12-27 17:25:29 +080092import java.util.concurrent.Executor;
junyulai070f9ff2019-01-16 20:23:34 +080093import java.util.concurrent.ExecutorService;
94import java.util.concurrent.Executors;
95import java.util.concurrent.RejectedExecutionException;
Jeremy Klein434835a2015-12-28 15:11:58 -080096
The Android Open Source Project28527d22009-03-03 19:31:44 -080097/**
98 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060099 * notifies applications when network connectivity changes.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800100 * <p>
101 * The primary responsibilities of this class are to:
102 * <ol>
103 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
104 * <li>Send broadcast intents when network connectivity changes</li>
105 * <li>Attempt to "fail over" to another network when connectivity to a network
106 * is lost</li>
107 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
108 * state of the available networks</li>
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700109 * <li>Provide an API that allows applications to request and select networks for their data
110 * traffic</li>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800111 * </ol>
112 */
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -0600113@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700114public class ConnectivityManager {
115 private static final String TAG = "ConnectivityManager";
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +0900116 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700117
The Android Open Source Project28527d22009-03-03 19:31:44 -0800118 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700119 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project28527d22009-03-03 19:31:44 -0800120 * been established or lost. The NetworkInfo for the affected network is
121 * sent as an extra; it should be consulted to see what kind of
122 * connectivity event occurred.
123 * <p/>
Mark Lu3e422ac2016-12-05 10:57:55 -0800124 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
125 * broadcast if they declare the broadcast receiver in their manifest. Apps
126 * will still receive broadcasts if they register their
127 * {@link android.content.BroadcastReceiver} with
128 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
129 * and that context is still valid.
130 * <p/>
The Android Open Source Project28527d22009-03-03 19:31:44 -0800131 * If this is a connection that was the result of failing over from a
132 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
133 * set to true.
134 * <p/>
135 * For a loss of connectivity, if the connectivity manager is attempting
136 * to connect (or has already connected) to another network, the
137 * NetworkInfo for the new network is also passed as an extra. This lets
138 * any receivers of the broadcast know that they should not necessarily
139 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800140 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project28527d22009-03-03 19:31:44 -0800141 * the failover attempt succeeded (and so there is still overall data
142 * connectivity), or that the failover attempt failed, meaning that all
143 * connectivity has been lost.
144 * <p/>
145 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
146 * is set to {@code true} if there are no connected networks at all.
Chalard Jean52e23962018-02-10 05:33:50 +0900147 *
148 * @deprecated apps should use the more versatile {@link #requestNetwork},
149 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
150 * functions instead for faster and more detailed updates about the network
151 * changes they care about.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800152 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800153 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean52e23962018-02-10 05:33:50 +0900154 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700156
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157 /**
Paul Jensen60df4aa2015-02-27 22:55:47 -0500158 * The device has connected to a network that has presented a captive
159 * portal, which is blocking Internet connectivity. The user was presented
160 * with a notification that network sign in is required,
161 * and the user invoked the notification's action indicating they
Paul Jensen75e0adb2015-05-22 10:50:39 -0400162 * desire to sign in to the network. Apps handling this activity should
Paul Jensen60df4aa2015-02-27 22:55:47 -0500163 * facilitate signing in to the network. This action includes a
164 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
165 * the network presenting the captive portal; all communication with the
166 * captive portal must be done using this {@code Network} object.
167 * <p/>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400168 * This activity includes a {@link CaptivePortal} extra named
169 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
170 * outcomes of the captive portal sign in to the system:
171 * <ul>
172 * <li> When the app handling this action believes the user has signed in to
173 * the network and the captive portal has been dismissed, the app should
174 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
175 * reevaluate the network. If reevaluation finds the network no longer
176 * subject to a captive portal, the network may become the default active
Chalard Jean9dd11612018-06-04 16:52:49 +0900177 * data network.</li>
Paul Jensen75e0adb2015-05-22 10:50:39 -0400178 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen60df4aa2015-02-27 22:55:47 -0500179 * to ignore the captive portal and the network, the app should call
Paul Jensen75e0adb2015-05-22 10:50:39 -0400180 * {@link CaptivePortal#ignoreNetwork}. </li>
181 * </ul>
Paul Jensen60df4aa2015-02-27 22:55:47 -0500182 */
183 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
184 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
185
186 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800187 * The lookup key for a {@link NetworkInfo} object. Retrieve with
188 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700189 *
Chalard Jean97021a12019-01-11 16:47:53 +0900190 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
191 * can't accurately represent modern network characteristics.
192 * Please obtain information about networks from the {@link NetworkCapabilities}
193 * or {@link LinkProperties} objects instead.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800194 */
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700195 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800196 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700197
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198 /**
Jeff Sharkey47905d12012-08-06 11:41:50 -0700199 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700200 *
201 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jean97021a12019-01-11 16:47:53 +0900202 * @deprecated The network type is not rich enough to represent the characteristics
203 * of modern networks. Please use {@link NetworkCapabilities} instead,
204 * in particular the transports.
Jeff Sharkey47905d12012-08-06 11:41:50 -0700205 */
Chalard Jean97021a12019-01-11 16:47:53 +0900206 @Deprecated
Jeff Sharkey47905d12012-08-06 11:41:50 -0700207 public static final String EXTRA_NETWORK_TYPE = "networkType";
208
209 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800210 * The lookup key for a boolean that indicates whether a connect event
211 * is for a network to which the connectivity manager was failing over
212 * following a disconnect on another network.
213 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai9826e7f2018-12-13 12:47:51 +0800214 *
215 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800216 */
junyulai9826e7f2018-12-13 12:47:51 +0800217 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800218 public static final String EXTRA_IS_FAILOVER = "isFailover";
219 /**
220 * The lookup key for a {@link NetworkInfo} object. This is supplied when
221 * there is another network that it may be possible to connect to. Retrieve with
222 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800223 *
224 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800225 */
junyulai9826e7f2018-12-13 12:47:51 +0800226 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800227 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
228 /**
229 * The lookup key for a boolean that indicates whether there is a
230 * complete lack of connectivity, i.e., no network is available.
231 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
232 */
233 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
234 /**
235 * The lookup key for a string that indicates why an attempt to connect
236 * to a network failed. The string has no particular structure. It is
237 * intended to be used in notifications presented to users. Retrieve
238 * it with {@link android.content.Intent#getStringExtra(String)}.
239 */
240 public static final String EXTRA_REASON = "reason";
241 /**
242 * The lookup key for a string that provides optionally supplied
243 * extra information about the network state. The information
244 * may be passed up from the lower networking layers, and its
245 * meaning may be specific to a particular network type. Retrieve
246 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai9826e7f2018-12-13 12:47:51 +0800247 *
248 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800249 */
junyulai9826e7f2018-12-13 12:47:51 +0800250 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800251 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwalt986c7412010-09-08 15:24:47 -0700252 /**
253 * The lookup key for an int that provides information about
254 * our connection to the internet at large. 0 indicates no connection,
255 * 100 indicates a great connection. Retrieve it with
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700256 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwalt986c7412010-09-08 15:24:47 -0700257 * {@hide}
258 */
259 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800260 /**
Paul Jensen75e0adb2015-05-22 10:50:39 -0400261 * The lookup key for a {@link CaptivePortal} object included with the
262 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
263 * object can be used to either indicate to the system that the captive
264 * portal has been dismissed or that the user does not want to pursue
265 * signing in to captive portal. Retrieve it with
266 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen60df4aa2015-02-27 22:55:47 -0500267 */
Paul Jensen75e0adb2015-05-22 10:50:39 -0400268 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist032e2672015-09-22 15:54:32 -0700269
270 /**
271 * Key for passing a URL to the captive portal login activity.
272 */
273 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
274
Paul Jensen60df4aa2015-02-27 22:55:47 -0500275 /**
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900276 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
277 * portal login activity.
278 * {@hide}
279 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900280 @SystemApi
Remi NGUYEN VANc2491572018-05-22 10:01:53 +0900281 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
282 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
283
284 /**
Hugo Benichi454e0662016-12-14 08:23:40 +0900285 * Key for passing a user agent string to the captive portal login activity.
286 * {@hide}
287 */
Remi NGUYEN VAN70ab67f2019-01-17 14:38:31 +0900288 @SystemApi
Hugo Benichi454e0662016-12-14 08:23:40 +0900289 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
290 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
291
292 /**
Haoyu Baib5da5752012-06-20 14:29:57 -0700293 * Broadcast action to indicate the change of data activity status
294 * (idle or active) on a network in a recent period.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800295 * The network becomes active when data transmission is started, or
296 * idle if there is no data transmission for a period of time.
Haoyu Baib5da5752012-06-20 14:29:57 -0700297 * {@hide}
298 */
299 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean9dd11612018-06-04 16:52:49 +0900300 public static final String ACTION_DATA_ACTIVITY_CHANGE =
301 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baib5da5752012-06-20 14:29:57 -0700302 /**
303 * The lookup key for an enum that indicates the network device type on which this data activity
304 * change happens.
305 * {@hide}
306 */
307 public static final String EXTRA_DEVICE_TYPE = "deviceType";
308 /**
309 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
310 * it is actively sending or receiving data and {@code false} means it is idle.
311 * {@hide}
312 */
313 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma29f7e0e2014-03-12 18:42:23 -0700314 /**
315 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
316 * {@hide}
317 */
318 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baib5da5752012-06-20 14:29:57 -0700319
320 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800321 * Broadcast Action: The setting for background data usage has changed
322 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
323 * <p>
324 * If an application uses the network in the background, it should listen
325 * for this broadcast and stop using the background data if the value is
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700326 * {@code false}.
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800327 * <p>
328 *
329 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
330 * of background data depends on several combined factors, and
331 * this broadcast is no longer sent. Instead, when background
332 * data is unavailable, {@link #getActiveNetworkInfo()} will now
333 * appear disconnected. During first boot after a platform
334 * upgrade, this broadcast will be sent once if
335 * {@link #getBackgroundDataSetting()} was {@code false} before
336 * the upgrade.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800337 */
338 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkeyc958c772012-01-30 16:29:24 -0800339 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800340 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
341 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
342
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700343 /**
344 * Broadcast Action: The network connection may not be good
345 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
346 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
347 * the network and it's condition.
348 * @hide
349 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800350 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100351 @UnsupportedAppUsage
Robert Greenwaltd3401f92010-09-15 17:36:33 -0700352 public static final String INET_CONDITION_ACTION =
353 "android.net.conn.INET_CONDITION_ACTION";
354
Robert Greenwalt2034b912009-08-12 16:08:25 -0700355 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800356 * Broadcast Action: A tetherable connection has come or gone.
357 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline762fa8e2017-04-17 16:47:23 +0900358 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
359 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800360 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
361 * the current state of tethering. Each include a list of
362 * interface names in that state (may be empty).
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800363 * @hide
364 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800365 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000366 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800367 public static final String ACTION_TETHER_STATE_CHANGED =
markchiena0f8fd92019-12-25 19:40:32 +0800368 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800369
370 /**
371 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800372 * gives a String[] listing all the interfaces configured for
373 * tethering and currently available for tethering.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800374 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000375 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800376 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800377
378 /**
379 * @hide
Erik Kline762fa8e2017-04-17 16:47:23 +0900380 * gives a String[] listing all the interfaces currently in local-only
381 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800382 */
markchiena0f8fd92019-12-25 19:40:32 +0800383 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline762fa8e2017-04-17 16:47:23 +0900384
385 /**
386 * @hide
387 * gives a String[] listing all the interfaces currently tethered
388 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
389 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000390 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800391 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800392
393 /**
394 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800395 * gives a String[] listing all the interfaces we tried to tether and
396 * failed. Use {@link #getLastTetherError} to find the error code
397 * for any interfaces listed here.
Robert Greenwalt8e87f122010-02-11 18:18:40 -0800398 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000399 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiena0f8fd92019-12-25 19:40:32 +0800400 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800401
402 /**
Russell Brenner30fe2642013-02-12 10:03:14 -0800403 * Broadcast Action: The captive portal tracker has finished its test.
404 * Sent only while running Setup Wizard, in lieu of showing a user
405 * notification.
406 * @hide
407 */
Jeff Sharkeyee9275b2013-02-20 18:21:19 -0800408 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner30fe2642013-02-12 10:03:14 -0800409 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
410 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
411 /**
412 * The lookup key for a boolean that indicates whether a captive portal was detected.
413 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
414 * @hide
415 */
416 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
417
418 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900419 * Action used to display a dialog that asks the user whether to connect to a network that is
420 * not validated. This intent is used to start the dialog in settings via startActivity.
421 *
422 * @hide
423 */
424 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
425
426 /**
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +0900427 * Action used to display a dialog that asks the user whether to avoid a network that is no
428 * longer validated. This intent is used to start the dialog in settings via startActivity.
429 *
430 * @hide
431 */
432 public static final String ACTION_PROMPT_LOST_VALIDATION =
433 "android.net.conn.PROMPT_LOST_VALIDATION";
434
435 /**
lucaslin2240ef62019-03-12 13:08:03 +0800436 * Action used to display a dialog that asks the user whether to stay connected to a network
437 * that has not validated. This intent is used to start the dialog in settings via
438 * startActivity.
439 *
440 * @hide
441 */
442 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
443 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
444
445 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800446 * Invalid tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900447 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800448 * @hide
449 */
markchiena0f8fd92019-12-25 19:40:32 +0800450 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800451
452 /**
453 * Wifi tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900454 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800455 * @hide
456 */
457 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900458 public static final int TETHERING_WIFI = 0;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800459
460 /**
461 * USB tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900462 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800463 * @hide
464 */
465 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900466 public static final int TETHERING_USB = 1;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800467
468 /**
469 * Bluetooth tethering type.
Chalard Jean9dd11612018-06-04 16:52:49 +0900470 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800471 * @hide
472 */
473 @SystemApi
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +0900474 public static final int TETHERING_BLUETOOTH = 2;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800475
476 /**
Jimmy Chendd31bc42019-07-15 18:03:23 +0800477 * Wifi P2p tethering type.
478 * Wifi P2p tethering is set through events automatically, and don't
479 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
480 * @hide
481 */
markchiena0f8fd92019-12-25 19:40:32 +0800482 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chendd31bc42019-07-15 18:03:23 +0800483
484 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800485 * Extra used for communicating with the TetherService. Includes the type of tethering to
486 * enable if any.
487 * @hide
488 */
markchien6ae63e52020-01-21 13:11:06 +0800489 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800490
491 /**
492 * Extra used for communicating with the TetherService. Includes the type of tethering for
493 * which to cancel provisioning.
494 * @hide
495 */
markchien6ae63e52020-01-21 13:11:06 +0800496 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800497
498 /**
499 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
500 * provisioning.
501 * @hide
502 */
markchien6ae63e52020-01-21 13:11:06 +0800503 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800504
505 /**
506 * Tells the TetherService to run a provision check now.
507 * @hide
508 */
markchien6ae63e52020-01-21 13:11:06 +0800509 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800510
511 /**
512 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
513 * which will receive provisioning results. Can be left empty.
514 * @hide
515 */
markchien6ae63e52020-01-21 13:11:06 +0800516 public static final String EXTRA_PROVISION_CALLBACK =
517 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein3dabcb92016-01-22 14:11:45 -0800518
519 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800520 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700521 * @hide
522 */
paulhu74357e72020-01-13 16:46:45 +0800523 @SystemApi
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700524 public static final int TYPE_NONE = -1;
525
526 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900527 * A Mobile data connection. Devices may support more than one.
528 *
529 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
530 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
531 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700532 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900533 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700534 public static final int TYPE_MOBILE = 0;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900535
Robert Greenwalt2034b912009-08-12 16:08:25 -0700536 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900537 * A WIFI data connection. Devices may support more than one.
538 *
539 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
540 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
541 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700542 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900543 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700544 public static final int TYPE_WIFI = 1;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900545
Robert Greenwalt2034b912009-08-12 16:08:25 -0700546 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800547 * An MMS-specific Mobile data connection. This network type may use the
548 * same network interface as {@link #TYPE_MOBILE} or it may use a different
549 * one. This is used by applications needing to talk to the carrier's
550 * Multimedia Messaging Service servers.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900551 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900552 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900553 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900554 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700555 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700556 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700557 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900558
Robert Greenwalt2034b912009-08-12 16:08:25 -0700559 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800560 * A SUPL-specific Mobile data connection. This network type may use the
561 * same network interface as {@link #TYPE_MOBILE} or it may use a different
562 * one. This is used by applications needing to talk to the carrier's
563 * Secure User Plane Location servers for help locating the device.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900564 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900565 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +0900566 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900567 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700568 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700569 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700570 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900571
Robert Greenwalt2034b912009-08-12 16:08:25 -0700572 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800573 * A DUN-specific Mobile data connection. This network type may use the
574 * same network interface as {@link #TYPE_MOBILE} or it may use a different
575 * one. This is sometimes by the system when setting up an upstream connection
576 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900577 *
578 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
579 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
580 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700581 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900582 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700583 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900584
Robert Greenwalt2034b912009-08-12 16:08:25 -0700585 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800586 * A High Priority Mobile data connection. This network type uses the
587 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900588 * is different.
589 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900590 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
591 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
592 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700593 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700594 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700595 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900596
jshbfa81722010-03-11 15:04:43 -0800597 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900598 * A WiMAX data connection.
599 *
600 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
601 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
602 * appropriate network. {@see NetworkCapabilities} for supported transports.
jshbfa81722010-03-11 15:04:43 -0800603 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900604 @Deprecated
jshbfa81722010-03-11 15:04:43 -0800605 public static final int TYPE_WIMAX = 6;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800606
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800607 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900608 * A Bluetooth data connection.
609 *
610 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
611 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
612 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800613 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900614 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800615 public static final int TYPE_BLUETOOTH = 7;
616
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700617 /**
Chiachang Wang3b9549f2020-07-28 13:53:09 +0800618 * Fake data connection. This should not be used on shipping devices.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900619 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700620 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900621 @Deprecated
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800622 public static final int TYPE_DUMMY = 8;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800623
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700624 /**
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900625 * An Ethernet data connection.
626 *
627 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
628 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
629 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700630 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900631 @Deprecated
Robert Greenwalt9d077812011-01-28 14:48:37 -0800632 public static final int TYPE_ETHERNET = 9;
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700633
Wink Savilleb7c92c72011-03-12 14:52:01 -0800634 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800635 * Over the air Administration.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900636 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800637 * {@hide}
638 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900639 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900640 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800641 public static final int TYPE_MOBILE_FOTA = 10;
642
643 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800644 * IP Multimedia Subsystem.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900645 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800646 * {@hide}
647 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900648 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100649 @UnsupportedAppUsage
Wink Savilleb7c92c72011-03-12 14:52:01 -0800650 public static final int TYPE_MOBILE_IMS = 11;
651
652 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800653 * Carrier Branded Services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900654 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800655 * {@hide}
656 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900657 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900658 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Savilleb7c92c72011-03-12 14:52:01 -0800659 public static final int TYPE_MOBILE_CBS = 12;
660
repo syncf5de5572011-07-29 23:55:49 -0700661 /**
662 * A Wi-Fi p2p connection. Only requesting processes will have access to
663 * the peers connected.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900664 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncf5de5572011-07-29 23:55:49 -0700665 * {@hide}
666 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900667 @Deprecated
paulhue102b0b2020-01-15 15:38:23 +0800668 @SystemApi
repo syncf5de5572011-07-29 23:55:49 -0700669 public static final int TYPE_WIFI_P2P = 13;
Wink Savilleb7c92c72011-03-12 14:52:01 -0800670
Wink Saville512c2202013-07-29 15:00:57 -0700671 /**
672 * The network to use for initially attaching to the network
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900673 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville512c2202013-07-29 15:00:57 -0700674 * {@hide}
675 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900676 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +0100677 @UnsupportedAppUsage
Wink Saville512c2202013-07-29 15:00:57 -0700678 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700679
Lorenzo Colitti21e9a152015-04-23 15:32:42 +0900680 /**
Robert Greenwaltb1f7f752015-07-09 14:49:35 -0700681 * Emergency PDN connection for emergency services. This
682 * may include IMS and MMS in emergency situations.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900683 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram693d07a2014-06-26 11:03:44 -0700684 * {@hide}
685 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900686 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900687 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram693d07a2014-06-26 11:03:44 -0700688 public static final int TYPE_MOBILE_EMERGENCY = 15;
689
Hui Lu865b70d2014-01-15 11:05:36 -0500690 /**
691 * The network that uses proxy to achieve connectivity.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900692 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu865b70d2014-01-15 11:05:36 -0500693 * {@hide}
694 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900695 @Deprecated
Remi NGUYEN VANee660cf2020-11-30 19:23:45 +0900696 @SystemApi
Hui Lu865b70d2014-01-15 11:05:36 -0500697 public static final int TYPE_PROXY = 16;
Wink Saville512c2202013-07-29 15:00:57 -0700698
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700699 /**
700 * A virtual network using one or more native bearers.
701 * It may or may not be providing security services.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900702 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700703 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900704 @Deprecated
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700705 public static final int TYPE_VPN = 17;
Hui Lu865b70d2014-01-15 11:05:36 -0500706
Benedict Wongbdfaa482018-11-14 17:40:55 -0800707 /**
708 * A network that is exclusively meant to be used for testing
709 *
710 * @deprecated Use {@link NetworkCapabilities} instead.
711 * @hide
712 */
713 @Deprecated
714 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700715
Chalard Jeanaea539a2020-03-25 01:24:04 +0900716 /**
717 * @deprecated Use {@link NetworkCapabilities} instead.
718 * @hide
719 */
720 @Deprecated
721 @Retention(RetentionPolicy.SOURCE)
722 @IntDef(prefix = { "TYPE_" }, value = {
723 TYPE_NONE,
724 TYPE_MOBILE,
725 TYPE_WIFI,
726 TYPE_MOBILE_MMS,
727 TYPE_MOBILE_SUPL,
728 TYPE_MOBILE_DUN,
729 TYPE_MOBILE_HIPRI,
730 TYPE_WIMAX,
731 TYPE_BLUETOOTH,
732 TYPE_DUMMY,
733 TYPE_ETHERNET,
734 TYPE_MOBILE_FOTA,
735 TYPE_MOBILE_IMS,
736 TYPE_MOBILE_CBS,
737 TYPE_WIFI_P2P,
738 TYPE_MOBILE_IA,
739 TYPE_MOBILE_EMERGENCY,
740 TYPE_PROXY,
741 TYPE_VPN,
742 TYPE_TEST
743 })
744 public @interface LegacyNetworkType {}
745
Chalard Jeanafaed1a2019-11-21 14:48:00 +0900746 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
747 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
748 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
749 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
750 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
751
Robert Greenwaltce7a1442014-07-07 17:09:01 -0700752 /** {@hide} */
Benedict Wongbdfaa482018-11-14 17:40:55 -0800753 public static final int MAX_RADIO_TYPE = TYPE_TEST;
754
755 /** {@hide} */
756 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800757
Hugo Benichiad353f42017-06-20 14:07:59 +0900758 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
759
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800760 /**
761 * If you want to set the default network preference,you can directly
762 * change the networkAttributes array in framework's config.xml.
763 *
764 * @deprecated Since we support so many more networks now, the single
765 * network default network preference can't really express
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800766 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800767 * networkAttributes in config.xml. You can determine
Robert Greenwaltf909cb12012-12-07 09:56:50 -0800768 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800769 * from an App.
770 */
771 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800772 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
773
Jeff Sharkey8c870452012-09-26 22:03:49 -0700774 /**
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700775 * @hide
776 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900777 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltbfd1f4c2014-06-08 16:42:59 -0700778
Paul Jensen5dea4352014-07-11 12:28:19 -0400779 /**
Hugo Benichibee30fe2017-06-17 13:14:12 +0900780 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
781 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean9dd11612018-06-04 16:52:49 +0900782 * registered from those that were already unregistered.
Hugo Benichibee30fe2017-06-17 13:14:12 +0900783 * @hide
784 */
Hugo Benichi7ab07a32017-06-20 14:10:14 +0900785 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichibee30fe2017-06-17 13:14:12 +0900786 new NetworkRequest.Builder().clearCapabilities().build();
787
788 /**
Paul Jensen5dea4352014-07-11 12:28:19 -0400789 * A NetID indicating no Network is selected.
790 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
791 * @hide
792 */
793 public static final int NETID_UNSET = 0;
794
Erik Klineb0be3e62017-10-30 15:29:44 +0900795 /**
796 * Private DNS Mode values.
797 *
798 * The "private_dns_mode" global setting stores a String value which is
799 * expected to be one of the following.
800 */
801
802 /**
803 * @hide
804 */
805 public static final String PRIVATE_DNS_MODE_OFF = "off";
806 /**
807 * @hide
808 */
809 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
810 /**
811 * @hide
812 */
813 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
814 /**
815 * The default Private DNS mode.
816 *
817 * This may change from release to release or may become dependent upon
818 * the capabilities of the underlying platform.
819 *
820 * @hide
821 */
Erik Klinea7edf6f2018-05-16 16:41:57 +0900822 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Klineb0be3e62017-10-30 15:29:44 +0900823
Chalard Jeana3b77512019-04-09 15:46:21 +0900824 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700825 private final IConnectivityManager mService;
Lorenzo Colitticd675292021-02-04 17:32:07 +0900826
Paul Jensenc0618a62014-12-10 15:12:18 -0500827 /**
828 * A kludge to facilitate static access where a Context pointer isn't available, like in the
829 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
830 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
831 * methods that take a Context argument.
832 */
833 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800834
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900835 private final Context mContext;
836
Felipe Leme30511352016-01-22 09:44:57 -0800837 private INetworkPolicyManager mNPManager;
Amos Bianchia9b415a2020-03-04 11:07:38 -0800838 private final TetheringManager mTetheringManager;
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800839
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800840 /**
841 * Tests if a given integer represents a valid network type.
842 * @param networkType the type to be tested
843 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensenbbb61092015-05-06 10:42:25 -0400844 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
845 * validate a network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800846 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700847 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700848 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900849 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800850 }
851
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800852 /**
853 * Returns a non-localized string representing a given network type.
854 * ONLY used for debugging output.
855 * @param type the type needing naming
856 * @return a String for the given type, or a string version of the type ("87")
857 * if no name is known.
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900858 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800859 * {@hide}
860 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900861 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +0000862 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700863 public static String getNetworkTypeName(int type) {
864 switch (type) {
Hugo Benichiad353f42017-06-20 14:07:59 +0900865 case TYPE_NONE:
866 return "NONE";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700867 case TYPE_MOBILE:
868 return "MOBILE";
869 case TYPE_WIFI:
870 return "WIFI";
871 case TYPE_MOBILE_MMS:
872 return "MOBILE_MMS";
873 case TYPE_MOBILE_SUPL:
874 return "MOBILE_SUPL";
875 case TYPE_MOBILE_DUN:
876 return "MOBILE_DUN";
877 case TYPE_MOBILE_HIPRI:
878 return "MOBILE_HIPRI";
879 case TYPE_WIMAX:
880 return "WIMAX";
881 case TYPE_BLUETOOTH:
882 return "BLUETOOTH";
883 case TYPE_DUMMY:
884 return "DUMMY";
885 case TYPE_ETHERNET:
886 return "ETHERNET";
887 case TYPE_MOBILE_FOTA:
888 return "MOBILE_FOTA";
889 case TYPE_MOBILE_IMS:
890 return "MOBILE_IMS";
891 case TYPE_MOBILE_CBS:
892 return "MOBILE_CBS";
repo syncf5de5572011-07-29 23:55:49 -0700893 case TYPE_WIFI_P2P:
894 return "WIFI_P2P";
Wink Saville512c2202013-07-29 15:00:57 -0700895 case TYPE_MOBILE_IA:
896 return "MOBILE_IA";
Ram693d07a2014-06-26 11:03:44 -0700897 case TYPE_MOBILE_EMERGENCY:
898 return "MOBILE_EMERGENCY";
Hui Lu865b70d2014-01-15 11:05:36 -0500899 case TYPE_PROXY:
900 return "PROXY";
Erik Kline137fadc2014-11-19 17:23:41 +0900901 case TYPE_VPN:
902 return "VPN";
Jeff Sharkey21062e72011-05-28 20:56:34 -0700903 default:
904 return Integer.toString(type);
905 }
906 }
907
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800908 /**
Aaron Huang96011892020-06-27 07:18:23 +0800909 * @hide
910 * TODO: Expose for SystemServer when becomes a module.
911 */
912 public void systemReady() {
913 try {
914 mService.systemReady();
915 } catch (RemoteException e) {
916 throw e.rethrowFromSystemServer();
917 }
918 }
919
920 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800921 * Checks if a given type uses the cellular data connection.
922 * This should be replaced in the future by a network property.
923 * @param networkType the type to check
924 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900925 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800926 * {@hide}
927 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900928 @Deprecated
Chalard Jeana3b77512019-04-09 15:46:21 +0900929 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey21062e72011-05-28 20:56:34 -0700930 public static boolean isNetworkTypeMobile(int networkType) {
931 switch (networkType) {
932 case TYPE_MOBILE:
933 case TYPE_MOBILE_MMS:
934 case TYPE_MOBILE_SUPL:
935 case TYPE_MOBILE_DUN:
936 case TYPE_MOBILE_HIPRI:
937 case TYPE_MOBILE_FOTA:
938 case TYPE_MOBILE_IMS:
939 case TYPE_MOBILE_CBS:
Wink Saville512c2202013-07-29 15:00:57 -0700940 case TYPE_MOBILE_IA:
Ram693d07a2014-06-26 11:03:44 -0700941 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkey21062e72011-05-28 20:56:34 -0700942 return true;
943 default:
944 return false;
945 }
946 }
947
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800948 /**
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700949 * Checks if the given network type is backed by a Wi-Fi radio.
950 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900951 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700952 * @hide
953 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +0900954 @Deprecated
Jeff Sharkey79f3e022013-06-04 12:29:00 -0700955 public static boolean isNetworkTypeWifi(int networkType) {
956 switch (networkType) {
957 case TYPE_WIFI:
958 case TYPE_WIFI_P2P:
959 return true;
960 default:
961 return false;
962 }
963 }
964
965 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800966 * Specifies the preferred network type. When the device has more
967 * than one type available the preferred network type will be used.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800968 *
969 * @param preference the network type to prefer over all others. It is
970 * unspecified what happens to the old preferred network in the
971 * overall ordering.
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700972 * @deprecated Functionality has been removed as it no longer makes sense,
973 * with many more than two networks - we'd need an array to express
974 * preference. Instead we use dynamic network properties of
975 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800976 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700977 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -0800978 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800979 }
980
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800981 /**
982 * Retrieves the current preferred network type.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800983 *
984 * @return an integer representing the preferred network type
985 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700986 * @deprecated Functionality has been removed as it no longer makes sense,
987 * with many more than two networks - we'd need an array to express
988 * preference. Instead we use dynamic network properties of
989 * the networks to describe their precedence.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800990 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -0700991 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -0600992 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project28527d22009-03-03 19:31:44 -0800993 public int getNetworkPreference() {
Robert Greenwaltf3017f72014-05-18 23:07:25 -0700994 return TYPE_NONE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800995 }
996
Scott Mainf58b7d82011-10-06 19:02:28 -0700997 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -0800998 * Returns details about the currently active default data network. When
999 * connected, this network is the default route for outgoing connections.
1000 * You should always check {@link NetworkInfo#isConnected()} before initiating
1001 * network traffic. This may return {@code null} when there is no default
1002 * network.
Chalard Jean96d10a72018-03-29 17:45:24 +09001003 * Note that if the default network is a VPN, this method will return the
1004 * NetworkInfo for one of its underlying networks instead, or null if the
1005 * VPN agent did not specify any. Apps interested in learning about VPNs
1006 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001007 *
1008 * @return a {@link NetworkInfo} object for the current default network
Paul Jensenbd2d3782015-02-13 14:18:39 -05001009 * or {@code null} if no default network is currently active
junyulai9826e7f2018-12-13 12:47:51 +08001010 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001011 */
junyulai9826e7f2018-12-13 12:47:51 +08001012 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001013 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001014 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001015 public NetworkInfo getActiveNetworkInfo() {
1016 try {
1017 return mService.getActiveNetworkInfo();
1018 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001019 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001020 }
1021 }
1022
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001023 /**
Paul Jensen1f567382015-02-13 14:18:39 -05001024 * Returns a {@link Network} object corresponding to the currently active
1025 * default data network. In the event that the current active default data
1026 * network disconnects, the returned {@code Network} object will no longer
1027 * be usable. This will return {@code null} when there is no default
1028 * network.
1029 *
1030 * @return a {@link Network} object for the current default network or
1031 * {@code null} if no default network is currently active
Paul Jensen1f567382015-02-13 14:18:39 -05001032 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001033 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001034 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001035 public Network getActiveNetwork() {
1036 try {
1037 return mService.getActiveNetwork();
1038 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001039 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05001040 }
1041 }
1042
1043 /**
Robin Lee5b52bef2016-03-24 12:07:00 +00001044 * Returns a {@link Network} object corresponding to the currently active
1045 * default data network for a specific UID. In the event that the default data
1046 * network disconnects, the returned {@code Network} object will no longer
1047 * be usable. This will return {@code null} when there is no default
1048 * network for the UID.
Robin Lee5b52bef2016-03-24 12:07:00 +00001049 *
1050 * @return a {@link Network} object for the current default network for the
1051 * given UID or {@code null} if no default network is currently active
1052 *
1053 * @hide
1054 */
paulhu8e96a752019-08-12 16:25:11 +08001055 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09001056 @Nullable
Robin Lee5b52bef2016-03-24 12:07:00 +00001057 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001058 return getActiveNetworkForUid(uid, false);
1059 }
1060
1061 /** {@hide} */
1062 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Lee5b52bef2016-03-24 12:07:00 +00001063 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001064 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001065 } catch (RemoteException e) {
1066 throw e.rethrowFromSystemServer();
1067 }
1068 }
1069
1070 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001071 * Calls VpnManager#isAlwaysOnVpnPackageSupportedForUser.
1072 * @deprecated TODO: remove when callers have migrated to VpnManager.
Charles He9369e612017-05-15 17:07:18 +01001073 * @hide
1074 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09001075 @Deprecated
Charles He9369e612017-05-15 17:07:18 +01001076 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001077 return getVpnManager().isAlwaysOnVpnPackageSupportedForUser(userId, vpnPackage);
Charles He9369e612017-05-15 17:07:18 +01001078 }
1079
1080 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001081 * Calls VpnManager#setAlwaysOnVpnPackageForUser.
1082 * @deprecated TODO: remove when callers have migrated to VpnManager.
Robin Leee5d5ed52016-01-05 18:03:46 +00001083 * @hide
1084 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09001085 @Deprecated
Robin Lee94e69be2016-05-03 13:23:03 +01001086 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001087 boolean lockdownEnabled, @Nullable List<String> lockdownAllowlist) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001088 return getVpnManager().setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdownEnabled,
1089 lockdownAllowlist);
Robin Leee5d5ed52016-01-05 18:03:46 +00001090 }
1091
Lorenzo Colitticd675292021-02-04 17:32:07 +09001092 /**
1093 * Calls VpnManager#getAlwaysOnVpnPackageForUser.
1094 * @deprecated TODO: remove when callers have migrated to VpnManager.
Robin Leee5d5ed52016-01-05 18:03:46 +00001095 * @hide
1096 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09001097 @Deprecated
Robin Leee5d5ed52016-01-05 18:03:46 +00001098 public String getAlwaysOnVpnPackageForUser(int userId) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001099 return getVpnManager().getAlwaysOnVpnPackageForUser(userId);
Robin Leee5d5ed52016-01-05 18:03:46 +00001100 }
1101
1102 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001103 * Calls VpnManager#isVpnLockdownEnabled.
1104 * @deprecated TODO: remove when callers have migrated to VpnManager.
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001105 * @hide
Lorenzo Colitticd675292021-02-04 17:32:07 +09001106 */
1107 @Deprecated
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001108 public boolean isVpnLockdownEnabled(int userId) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001109 return getVpnManager().isVpnLockdownEnabled(userId);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001110 }
1111
1112 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09001113 * Calls VpnManager#getVpnLockdownAllowlist.
1114 * @deprecated TODO: remove when callers have migrated to VpnManager.
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001115 * @hide
Lorenzo Colitticd675292021-02-04 17:32:07 +09001116 */
1117 @Deprecated
Lorenzo Colittie7743b72021-02-08 16:25:42 +09001118 public List<String> getVpnLockdownAllowlist(int userId) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001119 return getVpnManager().getVpnLockdownAllowlist(userId);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001120 }
1121
1122 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001123 * Adds or removes a requirement for given UID ranges to use the VPN.
1124 *
1125 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1126 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1127 * otherwise have permission to bypass the VPN (e.g., because they have the
1128 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1129 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1130 * set to {@code false}, a previously-added restriction is removed.
1131 * <p>
1132 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1133 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1134 * remove a previously-added range, the exact range must be removed as is.
1135 * <p>
1136 * The changes are applied asynchronously and may not have been applied by the time the method
1137 * returns. Apps will be notified about any changes that apply to them via
1138 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1139 * effect.
1140 * <p>
1141 * This method should be called only by the VPN code.
1142 *
1143 * @param ranges the UID ranges to restrict
1144 * @param requireVpn whether the specified UID ranges must use a VPN
1145 *
1146 * TODO: expose as @SystemApi.
1147 * @hide
1148 */
1149 @RequiresPermission(anyOf = {
1150 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1151 android.Manifest.permission.NETWORK_STACK})
1152 public void setRequireVpnForUids(boolean requireVpn,
1153 @NonNull Collection<Range<Integer>> ranges) {
1154 Objects.requireNonNull(ranges);
1155 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1156 // This method is not necessarily expected to be used outside the system server, so
1157 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1158 // stack process, or by tests.
1159 UidRange[] rangesArray = new UidRange[ranges.size()];
1160 int index = 0;
1161 for (Range<Integer> range : ranges) {
1162 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1163 }
1164 try {
1165 mService.setRequireVpnForUids(requireVpn, rangesArray);
1166 } catch (RemoteException e) {
1167 throw e.rethrowFromSystemServer();
1168 }
1169 }
1170
1171 /**
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001172 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1173 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1174 * but is still supported for backwards compatibility.
1175 * <p>
1176 * This type of VPN is assumed always to use the system default network, and must always declare
1177 * exactly one underlying network, which is the network that was the default when the VPN
1178 * connected.
1179 * <p>
1180 * Calling this method with {@code true} enables legacy behaviour, specifically:
1181 * <ul>
1182 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1183 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1184 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1185 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1186 * underlying the VPN.</li>
1187 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1188 * similarly replaced by the VPN network state.</li>
1189 * <li>Information on current network interfaces passed to NetworkStatsService will not
1190 * include any VPN interfaces.</li>
1191 * </ul>
1192 *
1193 * @param enabled whether legacy lockdown VPN is enabled or disabled
1194 *
1195 * TODO: @SystemApi(client = MODULE_LIBRARIES)
1196 *
1197 * @hide
1198 */
1199 @RequiresPermission(anyOf = {
1200 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1201 android.Manifest.permission.NETWORK_SETTINGS})
1202 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1203 try {
1204 mService.setLegacyLockdownVpnEnabled(enabled);
1205 } catch (RemoteException e) {
1206 throw e.rethrowFromSystemServer();
1207 }
1208 }
1209
1210 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001211 * Returns details about the currently active default data network
1212 * for a given uid. This is for internal use only to avoid spying
1213 * other apps.
1214 *
1215 * @return a {@link NetworkInfo} object for the current default network
1216 * for the given uid or {@code null} if no default network is
1217 * available for the specified uid.
1218 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001219 * {@hide}
1220 */
paulhu8e96a752019-08-12 16:25:11 +08001221 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001222 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001223 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001224 return getActiveNetworkInfoForUid(uid, false);
1225 }
1226
1227 /** {@hide} */
1228 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001229 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001230 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001231 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001232 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001233 }
1234 }
1235
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001236 /**
1237 * Returns connection status information about a particular
1238 * network type.
1239 *
1240 * @param networkType integer specifying which networkType in
1241 * which you're interested.
1242 * @return a {@link NetworkInfo} object for the requested
1243 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001244 * supported by the device. If {@code networkType} is
1245 * TYPE_VPN and a VPN is active for the calling app,
1246 * then this method will try to return one of the
1247 * underlying networks for the VPN or null if the
1248 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001249 *
Paul Jensendda8e592015-03-18 12:23:02 -04001250 * @deprecated This method does not support multiple connected networks
1251 * of the same type. Use {@link #getAllNetworks} and
1252 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001253 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001254 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001255 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001256 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001257 public NetworkInfo getNetworkInfo(int networkType) {
1258 try {
1259 return mService.getNetworkInfo(networkType);
1260 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001261 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001262 }
1263 }
1264
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001265 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001266 * Returns connection status information about a particular
1267 * Network.
1268 *
1269 * @param network {@link Network} specifying which network
1270 * in which you're interested.
1271 * @return a {@link NetworkInfo} object for the requested
1272 * network or {@code null} if the {@code Network}
1273 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001274 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001275 */
junyulai9826e7f2018-12-13 12:47:51 +08001276 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001277 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001278 @Nullable
1279 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001280 return getNetworkInfoForUid(network, Process.myUid(), false);
1281 }
1282
1283 /** {@hide} */
1284 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001285 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001286 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001287 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001288 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001289 }
1290 }
1291
1292 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001293 * Returns connection status information about all network
1294 * types supported by the device.
1295 *
1296 * @return an array of {@link NetworkInfo} objects. Check each
1297 * {@link NetworkInfo#getType} for which type each applies.
1298 *
Paul Jensendda8e592015-03-18 12:23:02 -04001299 * @deprecated This method does not support multiple connected networks
1300 * of the same type. Use {@link #getAllNetworks} and
1301 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001302 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001303 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001304 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001305 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001306 public NetworkInfo[] getAllNetworkInfo() {
1307 try {
1308 return mService.getAllNetworkInfo();
1309 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001310 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001311 }
1312 }
1313
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001314 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001315 * Returns the {@link Network} object currently serving a given type, or
1316 * null if the given type is not connected.
1317 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001318 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001319 * @deprecated This method does not support multiple connected networks
1320 * of the same type. Use {@link #getAllNetworks} and
1321 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001322 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001323 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001324 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001325 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001326 public Network getNetworkForType(int networkType) {
1327 try {
1328 return mService.getNetworkForType(networkType);
1329 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001330 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001331 }
1332 }
1333
1334 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001335 * Returns an array of all {@link Network} currently tracked by the
1336 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001337 *
1338 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001339 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001340 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001341 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001342 public Network[] getAllNetworks() {
1343 try {
1344 return mService.getAllNetworks();
1345 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001346 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001347 }
1348 }
1349
1350 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001351 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001352 * the Networks that applications run by the given user will use by default.
1353 * @hide
1354 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001355 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001356 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1357 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001358 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001359 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001360 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001361 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001362 }
1363 }
1364
1365 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001366 * Returns the IP information for the current default network.
1367 *
1368 * @return a {@link LinkProperties} object describing the IP info
1369 * for the current default network, or {@code null} if there
1370 * is no current default network.
1371 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001372 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001373 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1374 * value of {@link #getActiveNetwork()} instead. In particular,
1375 * this method will return non-null LinkProperties even if the
1376 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001377 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001378 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001379 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001380 public LinkProperties getActiveLinkProperties() {
1381 try {
1382 return mService.getActiveLinkProperties();
1383 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001384 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001385 }
1386 }
1387
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001388 /**
1389 * Returns the IP information for a given network type.
1390 *
1391 * @param networkType the network type of interest.
1392 * @return a {@link LinkProperties} object describing the IP info
1393 * for the given networkType, or {@code null} if there is
1394 * no current default network.
1395 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001396 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001397 * @deprecated This method does not support multiple connected networks
1398 * of the same type. Use {@link #getAllNetworks},
1399 * {@link #getNetworkInfo(android.net.Network)}, and
1400 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001401 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001402 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001403 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001405 public LinkProperties getLinkProperties(int networkType) {
1406 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001407 return mService.getLinkPropertiesForType(networkType);
1408 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001409 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001410 }
1411 }
1412
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001413 /**
1414 * Get the {@link LinkProperties} for the given {@link Network}. This
1415 * will return {@code null} if the network is unknown.
1416 *
1417 * @param network The {@link Network} object identifying the network in question.
1418 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001419 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001420 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001421 @Nullable
1422 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001423 try {
1424 return mService.getLinkProperties(network);
1425 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001426 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001427 }
1428 }
1429
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001430 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001431 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001432 * will return {@code null} if the network is unknown.
1433 *
1434 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001435 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001436 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001437 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001438 @Nullable
1439 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001440 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001441 return mService.getNetworkCapabilities(
1442 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001443 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001444 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001445 }
1446 }
1447
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001448 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001449 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001450 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1451 * portal is present.
1452 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1453 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1454 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001455 * The system network validation may be using different strategies to detect captive portals,
1456 * so this method does not necessarily return a URL used by the system. It only returns a URL
1457 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001458 *
Udam Sainicd645462016-01-04 12:16:14 -08001459 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001460 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1461 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001462 */
paulhu8e96a752019-08-12 16:25:11 +08001463 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001464 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001465 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001466 public String getCaptivePortalServerUrl() {
1467 try {
1468 return mService.getCaptivePortalServerUrl();
1469 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001470 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001471 }
1472 }
1473
1474 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001475 * Tells the underlying networking system that the caller wants to
1476 * begin using the named feature. The interpretation of {@code feature}
1477 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001478 *
1479 * <p>This method requires the caller to hold either the
1480 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1481 * or the ability to modify system settings as determined by
1482 * {@link android.provider.Settings.System#canWrite}.</p>
1483 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001484 * @param networkType specifies which network the request pertains to
1485 * @param feature the name of the feature to be used
1486 * @return an integer value representing the outcome of the request.
1487 * The interpretation of this value is specific to each networking
1488 * implementation+feature combination, except that the value {@code -1}
1489 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001490 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001491 * @deprecated Deprecated in favor of the cleaner
1492 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001493 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001494 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001495 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001496 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001497 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001498 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001499 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001500 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1501 if (netCap == null) {
1502 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1503 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001504 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001505 }
1506
1507 NetworkRequest request = null;
1508 synchronized (sLegacyRequests) {
1509 LegacyRequest l = sLegacyRequests.get(netCap);
1510 if (l != null) {
1511 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1512 renewRequestLocked(l);
1513 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001514 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001515 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001516 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001517 }
1518 }
1519
1520 request = requestNetworkForFeatureLocked(netCap);
1521 }
1522 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001523 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001524 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001525 } else {
1526 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001527 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001528 }
1529 }
1530
1531 /**
1532 * Tells the underlying networking system that the caller is finished
1533 * using the named feature. The interpretation of {@code feature}
1534 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001535 *
1536 * <p>This method requires the caller to hold either the
1537 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1538 * or the ability to modify system settings as determined by
1539 * {@link android.provider.Settings.System#canWrite}.</p>
1540 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001541 * @param networkType specifies which network the request pertains to
1542 * @param feature the name of the feature that is no longer needed
1543 * @return an integer value representing the outcome of the request.
1544 * The interpretation of this value is specific to each networking
1545 * implementation+feature combination, except that the value {@code -1}
1546 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001547 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001548 * @deprecated Deprecated in favor of the cleaner
1549 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001550 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001551 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001552 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001553 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001554 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001555 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001556 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001557 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1558 if (netCap == null) {
1559 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1560 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001561 return -1;
1562 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001563
Paul Jensen49f74a32014-12-17 10:39:34 -05001564 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001565 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001566 }
1567 return 1;
1568 }
1569
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001570 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001571 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1572 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001573 switch (feature) {
1574 case "enableCBS":
1575 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1576 case "enableDUN":
1577 case "enableDUNAlways":
1578 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1579 case "enableFOTA":
1580 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1581 case "enableHIPRI":
1582 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1583 case "enableIMS":
1584 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1585 case "enableMMS":
1586 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1587 case "enableSUPL":
1588 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1589 default:
1590 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001591 }
Erik Klinece55eb12017-01-26 18:08:28 +09001592 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1593 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001594 }
1595 return null;
1596 }
1597
Robert Greenwalt802c1102014-06-02 15:32:02 -07001598 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001599 if (netCap == null) return TYPE_NONE;
1600 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1601 return TYPE_MOBILE_CBS;
1602 }
1603 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1604 return TYPE_MOBILE_IMS;
1605 }
1606 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1607 return TYPE_MOBILE_FOTA;
1608 }
1609 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1610 return TYPE_MOBILE_DUN;
1611 }
1612 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1613 return TYPE_MOBILE_SUPL;
1614 }
1615 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1616 return TYPE_MOBILE_MMS;
1617 }
1618 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1619 return TYPE_MOBILE_HIPRI;
1620 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001621 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1622 return TYPE_WIFI_P2P;
1623 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001624 return TYPE_NONE;
1625 }
1626
1627 private static class LegacyRequest {
1628 NetworkCapabilities networkCapabilities;
1629 NetworkRequest networkRequest;
1630 int expireSequenceNumber;
1631 Network currentNetwork;
1632 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001633
1634 private void clearDnsBinding() {
1635 if (currentNetwork != null) {
1636 currentNetwork = null;
1637 setProcessDefaultNetworkForHostResolution(null);
1638 }
1639 }
1640
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001641 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001642 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001643 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001644 currentNetwork = network;
1645 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001646 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001647 }
1648 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001649 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001650 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001651 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1652 }
1653 };
1654 }
1655
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001656 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001657 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1658 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001659
1660 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1661 synchronized (sLegacyRequests) {
1662 LegacyRequest l = sLegacyRequests.get(netCap);
1663 if (l != null) return l.networkRequest;
1664 }
1665 return null;
1666 }
1667
1668 private void renewRequestLocked(LegacyRequest l) {
1669 l.expireSequenceNumber++;
1670 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1671 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1672 }
1673
1674 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1675 int ourSeqNum = -1;
1676 synchronized (sLegacyRequests) {
1677 LegacyRequest l = sLegacyRequests.get(netCap);
1678 if (l == null) return;
1679 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001680 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001681 }
1682 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1683 }
1684
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001685 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001686 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1687 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001688 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001689 try {
1690 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001691 } catch (RemoteException e) {
1692 throw e.rethrowFromSystemServer();
1693 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001694 LegacyRequest l = new LegacyRequest();
1695 l.networkCapabilities = netCap;
1696 l.delay = delay;
1697 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001698 l.networkRequest = sendRequestForNetwork(
1699 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001700 if (l.networkRequest == null) return null;
1701 sLegacyRequests.put(netCap, l);
1702 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1703 return l.networkRequest;
1704 }
1705
1706 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1707 if (delay >= 0) {
1708 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001709 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001710 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1711 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001712 }
1713 }
1714
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001715 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001716 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1717 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001718 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001719 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001720 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001721 if (l == null) return false;
1722 unregisterNetworkCallback(l.networkCallback);
1723 l.clearDnsBinding();
1724 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001725 }
1726
Erik Klinece55eb12017-01-26 18:08:28 +09001727 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1728 static {
1729 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1730 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1731 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1732 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1733 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1734 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1735 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1736 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1737 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1738 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1739 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1740 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1741 }
1742
1743 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1744 static {
1745 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1746 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1747 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1748 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1749 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1750 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1751 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1752 }
1753
1754 /**
1755 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1756 * instance suitable for registering a request or callback. Throws an
1757 * IllegalArgumentException if no mapping from the legacy type to
1758 * NetworkCapabilities is known.
1759 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001760 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1761 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001762 * @hide
1763 */
1764 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1765 final NetworkCapabilities nc = new NetworkCapabilities();
1766
1767 // Map from type to transports.
1768 final int NOT_FOUND = -1;
1769 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichibc1104b2017-05-09 15:19:01 +09001770 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001771 nc.addTransportType(transport);
1772
1773 // Map from type to capabilities.
1774 nc.addCapability(sLegacyTypeToCapability.get(
1775 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1776 nc.maybeMarkCapabilitiesRestricted();
1777 return nc;
1778 }
1779
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001780 /** @hide */
1781 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001782 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001783 public PacketKeepaliveCallback() {
1784 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001785 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001786 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001787 public void onStarted() {}
1788 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001789 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001790 public void onStopped() {}
1791 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001792 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001793 public void onError(int error) {}
1794 }
1795
1796 /**
1797 * Allows applications to request that the system periodically send specific packets on their
1798 * behalf, using hardware offload to save battery power.
1799 *
1800 * To request that the system send keepalives, call one of the methods that return a
1801 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1802 * passing in a non-null callback. If the callback is successfully started, the callback's
1803 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1804 * specifying one of the {@code ERROR_*} constants in this class.
1805 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001806 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1807 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1808 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001809 *
junyulai4c95b082018-12-27 17:25:29 +08001810 * @deprecated Use {@link SocketKeepalive} instead.
1811 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001812 * @hide
1813 */
1814 public class PacketKeepalive {
1815
1816 private static final String TAG = "PacketKeepalive";
1817
1818 /** @hide */
1819 public static final int SUCCESS = 0;
1820
1821 /** @hide */
1822 public static final int NO_KEEPALIVE = -1;
1823
1824 /** @hide */
1825 public static final int BINDER_DIED = -10;
1826
1827 /** The specified {@code Network} is not connected. */
1828 public static final int ERROR_INVALID_NETWORK = -20;
1829 /** The specified IP addresses are invalid. For example, the specified source IP address is
1830 * not configured on the specified {@code Network}. */
1831 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1832 /** The requested port is invalid. */
1833 public static final int ERROR_INVALID_PORT = -22;
1834 /** The packet length is invalid (e.g., too long). */
1835 public static final int ERROR_INVALID_LENGTH = -23;
1836 /** The packet transmission interval is invalid (e.g., too short). */
1837 public static final int ERROR_INVALID_INTERVAL = -24;
1838
1839 /** The hardware does not support this request. */
1840 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001841 /** The hardware returned an error. */
1842 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001843
Nathan Harold0990bc82018-02-14 13:09:45 -08001844 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001845 public static final int NATT_PORT = 4500;
1846
Nathan Harold0990bc82018-02-14 13:09:45 -08001847 /** The minimum interval in seconds between keepalive packet transmissions */
1848 public static final int MIN_INTERVAL = 10;
1849
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001850 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001851 private final ISocketKeepaliveCallback mCallback;
1852 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001853
1854 private volatile Integer mSlot;
1855
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001856 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001857 public void stop() {
1858 try {
junyulai070f9ff2019-01-16 20:23:34 +08001859 mExecutor.execute(() -> {
1860 try {
1861 if (mSlot != null) {
1862 mService.stopKeepalive(mNetwork, mSlot);
1863 }
1864 } catch (RemoteException e) {
1865 Log.e(TAG, "Error stopping packet keepalive: ", e);
1866 throw e.rethrowFromSystemServer();
1867 }
1868 });
1869 } catch (RejectedExecutionException e) {
1870 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001871 }
1872 }
1873
1874 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09001875 Preconditions.checkNotNull(network, "network cannot be null");
1876 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001877 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001878 mExecutor = Executors.newSingleThreadExecutor();
1879 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001880 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001881 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001882 final long token = Binder.clearCallingIdentity();
1883 try {
1884 mExecutor.execute(() -> {
1885 mSlot = slot;
1886 callback.onStarted();
1887 });
1888 } finally {
1889 Binder.restoreCallingIdentity(token);
1890 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001891 }
junyulai070f9ff2019-01-16 20:23:34 +08001892
1893 @Override
1894 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001895 final long token = Binder.clearCallingIdentity();
1896 try {
1897 mExecutor.execute(() -> {
1898 mSlot = null;
1899 callback.onStopped();
1900 });
1901 } finally {
1902 Binder.restoreCallingIdentity(token);
1903 }
junyulai070f9ff2019-01-16 20:23:34 +08001904 mExecutor.shutdown();
1905 }
1906
1907 @Override
1908 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001909 final long token = Binder.clearCallingIdentity();
1910 try {
1911 mExecutor.execute(() -> {
1912 mSlot = null;
1913 callback.onError(error);
1914 });
1915 } finally {
1916 Binder.restoreCallingIdentity(token);
1917 }
junyulai070f9ff2019-01-16 20:23:34 +08001918 mExecutor.shutdown();
1919 }
1920
1921 @Override
1922 public void onDataReceived() {
1923 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1924 // this callback when data is received.
1925 }
1926 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001927 }
1928 }
1929
1930 /**
1931 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1932 *
junyulai4c95b082018-12-27 17:25:29 +08001933 * @deprecated Use {@link #createSocketKeepalive} instead.
1934 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001935 * @hide
1936 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001937 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001938 public PacketKeepalive startNattKeepalive(
1939 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1940 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1941 final PacketKeepalive k = new PacketKeepalive(network, callback);
1942 try {
junyulai070f9ff2019-01-16 20:23:34 +08001943 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001944 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1945 } catch (RemoteException e) {
1946 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001947 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001948 }
1949 return k;
1950 }
1951
Chiachang Wang619319a2021-01-15 11:06:21 +08001952 // Construct an invalid fd.
1953 private ParcelFileDescriptor createInvalidFd() {
1954 final int invalidFd = -1;
1955 return ParcelFileDescriptor.adoptFd(invalidFd);
1956 }
1957
The Android Open Source Project28527d22009-03-03 19:31:44 -08001958 /**
junyulai4c95b082018-12-27 17:25:29 +08001959 * Request that keepalives be started on a IPsec NAT-T socket.
1960 *
1961 * @param network The {@link Network} the socket is on.
1962 * @param socket The socket that needs to be kept alive.
1963 * @param source The source address of the {@link UdpEncapsulationSocket}.
1964 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1965 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1966 * must run callback sequentially, otherwise the order of callbacks cannot be
1967 * guaranteed.
1968 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1969 * changes. Must be extended by applications that use this API.
1970 *
junyulai0835a1e2019-01-08 20:04:33 +08001971 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1972 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001973 **/
junyulai7e06ad42019-03-04 22:45:36 +08001974 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001975 @NonNull UdpEncapsulationSocket socket,
1976 @NonNull InetAddress source,
1977 @NonNull InetAddress destination,
1978 @NonNull @CallbackExecutor Executor executor,
1979 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001980 ParcelFileDescriptor dup;
1981 try {
junyulai828dad12019-03-27 11:00:37 +08001982 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1983 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001984 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1985 } catch (IOException ignored) {
1986 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1987 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08001988 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08001989 }
1990 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1991 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08001992 }
1993
1994 /**
1995 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1996 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1997 *
1998 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08001999 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2000 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2001 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002002 * @param source The source address of the {@link UdpEncapsulationSocket}.
2003 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2004 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2005 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2006 * must run callback sequentially, otherwise the order of callbacks cannot be
2007 * guaranteed.
2008 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2009 * changes. Must be extended by applications that use this API.
2010 *
junyulai0835a1e2019-01-08 20:04:33 +08002011 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2012 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002013 * @hide
2014 */
2015 @SystemApi
2016 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002017 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2018 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002019 @NonNull InetAddress source,
2020 @NonNull InetAddress destination,
2021 @NonNull @CallbackExecutor Executor executor,
2022 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002023 ParcelFileDescriptor dup;
2024 try {
junyulai828dad12019-03-27 11:00:37 +08002025 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002026 dup = pfd.dup();
2027 } catch (IOException ignored) {
2028 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2029 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002030 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002031 }
2032 return new NattSocketKeepalive(mService, network, dup,
2033 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002034 }
2035
2036 /**
junyulai0835a1e2019-01-08 20:04:33 +08002037 * Request that keepalives be started on a TCP socket.
2038 * The socket must be established.
2039 *
2040 * @param network The {@link Network} the socket is on.
2041 * @param socket The socket that needs to be kept alive.
2042 * @param executor The executor on which callback will be invoked. This implementation assumes
2043 * the provided {@link Executor} runs the callbacks in sequence with no
2044 * concurrency. Failing this, no guarantee of correctness can be made. It is
2045 * the responsibility of the caller to ensure the executor provides this
2046 * guarantee. A simple way of creating such an executor is with the standard
2047 * tool {@code Executors.newSingleThreadExecutor}.
2048 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2049 * changes. Must be extended by applications that use this API.
2050 *
2051 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2052 * given socket.
2053 * @hide
2054 */
2055 @SystemApi
2056 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002057 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002058 @NonNull Socket socket,
2059 @NonNull Executor executor,
2060 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002061 ParcelFileDescriptor dup;
2062 try {
2063 dup = ParcelFileDescriptor.fromSocket(socket);
2064 } catch (UncheckedIOException ignored) {
2065 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2066 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002067 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002068 }
2069 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002070 }
2071
2072 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002073 * Ensure that a network route exists to deliver traffic to the specified
2074 * host via the specified network interface. An attempt to add a route that
2075 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002076 *
2077 * <p>This method requires the caller to hold either the
2078 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2079 * or the ability to modify system settings as determined by
2080 * {@link android.provider.Settings.System#canWrite}.</p>
2081 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002082 * @param networkType the type of the network over which traffic to the specified
2083 * host is to be routed
2084 * @param hostAddress the IP address of the host to which the route is desired
2085 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002086 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002087 * @deprecated Deprecated in favor of the
2088 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2089 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002090 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002091 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002092 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002093 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002094 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002095 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002096 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002097 }
2098
2099 /**
2100 * Ensure that a network route exists to deliver traffic to the specified
2101 * host via the specified network interface. An attempt to add a route that
2102 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002103 *
2104 * <p>This method requires the caller to hold either the
2105 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2106 * or the ability to modify system settings as determined by
2107 * {@link android.provider.Settings.System#canWrite}.</p>
2108 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002109 * @param networkType the type of the network over which traffic to the specified
2110 * host is to be routed
2111 * @param hostAddress the IP address of the host to which the route is desired
2112 * @return {@code true} on success, {@code false} on failure
2113 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002114 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002115 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002116 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002117 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002118 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002119 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002120 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002121 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002122 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2123 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002124 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002125 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002126 }
2127 }
2128
2129 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002130 * @return the context's attribution tag
2131 */
2132 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2133 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002134 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002135 }
2136
2137 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002138 * Returns the value of the setting for background data usage. If false,
2139 * applications should not use the network if the application is not in the
2140 * foreground. Developers should respect this setting, and check the value
2141 * of this before performing any background data operations.
2142 * <p>
2143 * All applications that have background services that use the network
2144 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002145 * <p>
Scott Main50589142011-10-06 18:32:43 -07002146 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002147 * background data depends on several combined factors, and this method will
2148 * always return {@code true}. Instead, when background data is unavailable,
2149 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002150 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002151 * @return Whether background data usage is allowed.
2152 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002153 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002154 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002155 // assume that background data is allowed; final authority is
2156 // NetworkInfo which may be blocked.
2157 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002158 }
2159
2160 /**
2161 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002162 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002163 * @param allowBackgroundData Whether an application should use data while
2164 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002165 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002166 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2167 * @see #getBackgroundDataSetting()
2168 * @hide
2169 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002170 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002171 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002172 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002173 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002175
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002176 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002177 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002178 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002179 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002180 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002181 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002182 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002183 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2184 if (tm != null) {
2185 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2186 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2187 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2188 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2189 + " retVal=" + retVal);
2190 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002191 }
Wink Saville689f7042014-12-05 11:10:30 -08002192 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002193 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002194 }
2195
The Android Open Source Project28527d22009-03-03 19:31:44 -08002196 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002197 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002198 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002199 */
2200 public interface OnNetworkActiveListener {
2201 /**
2202 * Called on the main thread of the process to report that the current data network
2203 * has become active, and it is now a good time to perform any pending network
2204 * operations. Note that this listener only tells you when the network becomes
2205 * active; if at any other time you want to know whether it is active (and thus okay
2206 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002207 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002208 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002209 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002210 }
2211
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002212 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002213 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002214
2215 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002216 * Start listening to reports when the system's default data network is active, meaning it is
2217 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2218 * to determine the current state of the system's default network after registering the
2219 * listener.
2220 * <p>
2221 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002222 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002223 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002224 *
2225 * @param l The listener to be told when the network is active.
2226 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002227 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002228 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2229 @Override
2230 public void onNetworkActive() throws RemoteException {
2231 l.onNetworkActive();
2232 }
2233 };
2234
2235 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002236 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002237 mNetworkActivityListeners.put(l, rl);
2238 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002239 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002240 }
2241 }
2242
2243 /**
2244 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002245 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002246 *
2247 * @param l Previously registered listener.
2248 */
Chalard Jean158702d2019-01-07 19:26:34 +09002249 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002250 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichibc1104b2017-05-09 15:19:01 +09002251 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002252 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002253 mService.registerNetworkActivityListener(rl);
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002254 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002255 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002256 }
2257 }
2258
2259 /**
2260 * Return whether the data network is currently active. An active network means that
2261 * it is currently in a high power state for performing data transmission. On some
2262 * types of networks, it may be expensive to move and stay in such a state, so it is
2263 * more power efficient to batch network traffic together when the radio is already in
2264 * this state. This method tells you whether right now is currently a good time to
2265 * initiate network traffic, as the network is already active.
2266 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002267 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002268 try {
lucaslin1193a5d2021-01-21 02:04:15 +08002269 return mService.isDefaultNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002270 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002271 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002272 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002273 }
2274
2275 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002276 * {@hide}
2277 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002278 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002279 mContext = Preconditions.checkNotNull(context, "missing context");
2280 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002281 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002282 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002283 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002284
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002285 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002286 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002287 public static ConnectivityManager from(Context context) {
2288 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2289 }
2290
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002291 /** @hide */
2292 public NetworkRequest getDefaultRequest() {
2293 try {
2294 // This is not racy as the default request is final in ConnectivityService.
2295 return mService.getDefaultRequest();
2296 } catch (RemoteException e) {
2297 throw e.rethrowFromSystemServer();
2298 }
2299 }
2300
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09002301 /* TODO: These permissions checks don't belong in client-side code. Move them to
2302 * services.jar, possibly in com.android.server.net. */
2303
2304 /** {@hide} */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002305 public static final void enforceChangePermission(Context context,
2306 String callingPkg, String callingAttributionTag) {
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002307 int uid = Binder.getCallingUid();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002308 checkAndNoteChangeNetworkStateOperation(context, uid, callingPkg,
2309 callingAttributionTag, true /* throwException */);
2310 }
2311
2312 /**
2313 * Check if the package is a allowed to change the network state. This also accounts that such
2314 * an access happened.
2315 *
2316 * @return {@code true} iff the package is allowed to change the network state.
2317 */
2318 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2319 private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context,
2320 int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag,
2321 boolean throwException) {
2322 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, callingPackage,
2323 throwException);
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002324 }
2325
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002326 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002327 * Check if the package is a allowed to write settings. This also accounts that such an access
2328 * happened.
2329 *
2330 * @return {@code true} iff the package is allowed to write settings.
2331 */
2332 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2333 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2334 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2335 boolean throwException) {
2336 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2337 throwException);
2338 }
2339
2340 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002341 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2342 * situations where a Context pointer is unavailable.
2343 * @hide
2344 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002345 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002346 static ConnectivityManager getInstanceOrNull() {
2347 return sInstance;
2348 }
2349
2350 /**
2351 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2352 * situations where a Context pointer is unavailable.
2353 * @hide
2354 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002355 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002356 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002357 private static ConnectivityManager getInstance() {
2358 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002359 throw new IllegalStateException("No ConnectivityManager yet constructed");
2360 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002361 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002362 }
2363
2364 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002365 * Get the set of tetherable, available interfaces. This list is limited by
2366 * device configuration and current interface existence.
2367 *
2368 * @return an array of 0 or more Strings of tetherable interface names.
2369 *
markchien6ae63e52020-01-21 13:11:06 +08002370 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002371 * {@hide}
2372 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002373 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002374 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002375 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002376 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002377 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002378 }
2379
2380 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002381 * Get the set of tethered interfaces.
2382 *
2383 * @return an array of 0 or more String of currently tethered interface names.
2384 *
markchien6ae63e52020-01-21 13:11:06 +08002385 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002386 * {@hide}
2387 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002388 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002389 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002390 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002391 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002392 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002393 }
2394
2395 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002396 * Get the set of interface names which attempted to tether but
2397 * failed. Re-attempting to tether may cause them to reset to the Tethered
2398 * state. Alternatively, causing the interface to be destroyed and recreated
2399 * may cause them to reset to the available state.
2400 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2401 * information on the cause of the errors.
2402 *
2403 * @return an array of 0 or more String indicating the interface names
2404 * which failed to tether.
2405 *
markchien6ae63e52020-01-21 13:11:06 +08002406 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002407 * {@hide}
2408 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002409 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002410 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002411 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002412 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002413 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002414 }
2415
2416 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002417 * Get the set of tethered dhcp ranges.
2418 *
markchien2e6ba522020-02-14 11:55:48 +08002419 * @deprecated This method is not supported.
2420 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002421 * {@hide}
2422 */
paulhu8e96a752019-08-12 16:25:11 +08002423 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002424 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002425 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002426 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002427 }
2428
2429 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002430 * Attempt to tether the named interface. This will setup a dhcp server
2431 * on the interface, forward and NAT IP packets and forward DNS requests
2432 * to the best active upstream network interface. Note that if no upstream
2433 * IP network interface is available, dhcp will still run and traffic will be
2434 * allowed between the tethered devices and this device, though upstream net
2435 * access will of course fail until an upstream network interface becomes
2436 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002437 *
2438 * <p>This method requires the caller to hold either the
2439 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2440 * or the ability to modify system settings as determined by
2441 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002442 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002443 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2444 * and WifiStateMachine which need direct access. All other clients should use
2445 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2446 * logic.</p>
2447 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002448 * @param iface the interface name to tether.
2449 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002450 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002451 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002452 * {@hide}
2453 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002454 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002455 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002456 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002457 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002458 }
2459
2460 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002461 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002462 *
2463 * <p>This method requires the caller to hold either the
2464 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2465 * or the ability to modify system settings as determined by
2466 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002467 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002468 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2469 * and WifiStateMachine which need direct access. All other clients should use
2470 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2471 * logic.</p>
2472 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002473 * @param iface the interface name to untether.
2474 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2475 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002476 * {@hide}
2477 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002478 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002479 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002480 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002481 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002482 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002483
2484 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002485 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002486 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002487 * due to device configuration.
2488 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002489 * <p>If this app does not have permission to use this API, it will always
2490 * return false rather than throw an exception.</p>
2491 *
2492 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2493 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2494 *
2495 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2496 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2497 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002498 * @return a boolean - {@code true} indicating Tethering is supported.
2499 *
markchien6ae63e52020-01-21 13:11:06 +08002500 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002501 * {@hide}
2502 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002503 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002504 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2505 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002506 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002507 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002508 }
2509
2510 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002511 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002512 *
2513 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002514 * @hide
2515 */
2516 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002517 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002518 public static abstract class OnStartTetheringCallback {
2519 /**
2520 * Called when tethering has been successfully started.
2521 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002522 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002523
2524 /**
2525 * Called when starting tethering failed.
2526 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002527 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002528 }
2529
2530 /**
2531 * Convenient overload for
2532 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2533 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002534 *
2535 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002536 * @hide
2537 */
2538 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002539 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002540 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002541 public void startTethering(int type, boolean showProvisioningUi,
2542 final OnStartTetheringCallback callback) {
2543 startTethering(type, showProvisioningUi, callback, null);
2544 }
2545
2546 /**
2547 * Runs tether provisioning for the given type if needed and then starts tethering if
2548 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2549 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2550 * schedules tether provisioning re-checks if appropriate.
2551 *
2552 * @param type The type of tethering to start. Must be one of
2553 * {@link ConnectivityManager.TETHERING_WIFI},
2554 * {@link ConnectivityManager.TETHERING_USB}, or
2555 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2556 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2557 * is one. This should be true the first time this function is called and also any time
2558 * the user can see this UI. It gives users information from their carrier about the
2559 * check failing and how they can sign up for tethering if possible.
2560 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2561 * of the result of trying to tether.
2562 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002563 *
2564 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002565 * @hide
2566 */
2567 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002568 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002569 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002570 public void startTethering(int type, boolean showProvisioningUi,
2571 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002572 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002573
markchien91c78e52020-01-20 19:31:56 +08002574 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002575 @Override
markchien91c78e52020-01-20 19:31:56 +08002576 public void execute(Runnable command) {
2577 if (handler == null) {
2578 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002579 } else {
markchien91c78e52020-01-20 19:31:56 +08002580 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002581 }
2582 }
2583 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002584
markchien91c78e52020-01-20 19:31:56 +08002585 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2586 @Override
2587 public void onTetheringStarted() {
2588 callback.onTetheringStarted();
2589 }
2590
2591 @Override
markchienf47d8342020-03-19 13:37:43 +08002592 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002593 callback.onTetheringFailed();
2594 }
2595 };
2596
2597 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002598 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002599
Amos Bianchia9b415a2020-03-04 11:07:38 -08002600 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002601 }
2602
2603 /**
2604 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2605 * applicable.
2606 *
2607 * @param type The type of tethering to stop. Must be one of
2608 * {@link ConnectivityManager.TETHERING_WIFI},
2609 * {@link ConnectivityManager.TETHERING_USB}, or
2610 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002611 *
2612 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002613 * @hide
2614 */
2615 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002616 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002617 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002618 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002619 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002620 }
2621
2622 /**
markchien4ef53e82019-02-27 14:56:11 +08002623 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2624 * upstream status.
2625 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002626 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002627 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002628 */
2629 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002630 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002631 public abstract static class OnTetheringEventCallback {
2632
2633 /**
2634 * Called when tethering upstream changed. This can be called multiple times and can be
2635 * called any time.
2636 *
2637 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2638 * have any upstream.
2639 */
2640 public void onUpstreamChanged(@Nullable Network network) {}
2641 }
2642
markchien6ae63e52020-01-21 13:11:06 +08002643 @GuardedBy("mTetheringEventCallbacks")
2644 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2645 mTetheringEventCallbacks = new ArrayMap<>();
2646
markchien4ef53e82019-02-27 14:56:11 +08002647 /**
2648 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002649 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002650 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2651 * with a null argument. The same callback object cannot be registered twice.
2652 *
2653 * @param executor the executor on which callback will be invoked.
2654 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002655 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002656 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002657 * @hide
2658 */
2659 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002660 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002661 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2662 public void registerTetheringEventCallback(
2663 @NonNull @CallbackExecutor Executor executor,
2664 @NonNull final OnTetheringEventCallback callback) {
2665 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2666
markchien6ae63e52020-01-21 13:11:06 +08002667 final TetheringEventCallback tetherCallback =
2668 new TetheringEventCallback() {
2669 @Override
2670 public void onUpstreamChanged(@Nullable Network network) {
2671 callback.onUpstreamChanged(network);
2672 }
2673 };
2674
2675 synchronized (mTetheringEventCallbacks) {
2676 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002677 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002678 }
markchien4ef53e82019-02-27 14:56:11 +08002679 }
2680
2681 /**
2682 * Remove tethering event callback previously registered with
2683 * {@link #registerTetheringEventCallback}.
2684 *
2685 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002686 *
2687 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002688 * @hide
2689 */
2690 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002691 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002692 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2693 public void unregisterTetheringEventCallback(
2694 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002695 Objects.requireNonNull(callback, "The callback must be non-null");
2696 synchronized (mTetheringEventCallbacks) {
2697 final TetheringEventCallback tetherCallback =
2698 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002699 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002700 }
markchien4ef53e82019-02-27 14:56:11 +08002701 }
2702
2703
2704 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002705 * Get the list of regular expressions that define any tetherable
2706 * USB network interfaces. If USB tethering is not supported by the
2707 * device, this list should be empty.
2708 *
2709 * @return an array of 0 or more regular expression Strings defining
2710 * what interfaces are considered tetherable usb interfaces.
2711 *
markchien6ae63e52020-01-21 13:11:06 +08002712 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002713 * {@hide}
2714 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002715 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002716 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002717 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002718 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002719 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002720 }
2721
2722 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002723 * Get the list of regular expressions that define any tetherable
2724 * Wifi network interfaces. If Wifi tethering is not supported by the
2725 * device, this list should be empty.
2726 *
2727 * @return an array of 0 or more regular expression Strings defining
2728 * what interfaces are considered tetherable wifi interfaces.
2729 *
markchien6ae63e52020-01-21 13:11:06 +08002730 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002731 * {@hide}
2732 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002733 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002734 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002735 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002736 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002737 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002738 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002739
Danica Chang96567052010-08-11 14:54:43 -07002740 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002741 * Get the list of regular expressions that define any tetherable
2742 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2743 * device, this list should be empty.
2744 *
2745 * @return an array of 0 or more regular expression Strings defining
2746 * what interfaces are considered tetherable bluetooth interfaces.
2747 *
markchien6ae63e52020-01-21 13:11:06 +08002748 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2749 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002750 * {@hide}
2751 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002752 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002753 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002754 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002755 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002756 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002757 }
2758
Mike Lockwooded4a1742011-07-19 13:04:47 -07002759 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002760 * Attempt to both alter the mode of USB and Tethering of USB. A
2761 * utility method to deal with some of the complexity of USB - will
2762 * attempt to switch to Rndis and subsequently tether the resulting
2763 * interface on {@code true} or turn off tethering and switch off
2764 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002765 *
2766 * <p>This method requires the caller to hold either the
2767 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2768 * or the ability to modify system settings as determined by
2769 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002770 *
2771 * @param enable a boolean - {@code true} to enable tethering
2772 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002773 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002774 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002775 * {@hide}
2776 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002777 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002778 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002779 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002780 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002781 }
2782
markchien6ae63e52020-01-21 13:11:06 +08002783 /**
2784 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2785 * {@hide}
2786 */
markchien0f45bb92019-01-16 17:44:13 +08002787 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002788 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002789 public static final int TETHER_ERROR_NO_ERROR = 0;
markchien6ae63e52020-01-21 13:11:06 +08002790 /**
2791 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2792 * {@hide}
2793 */
2794 @Deprecated
2795 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2796 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2797 /**
2798 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2799 * {@hide}
2800 */
2801 @Deprecated
2802 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2803 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2804 /**
2805 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2806 * {@hide}
2807 */
2808 @Deprecated
2809 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2810 /**
2811 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2812 * {@hide}
2813 */
2814 @Deprecated
2815 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2816 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2817 /**
markchienf47d8342020-03-19 13:37:43 +08002818 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002819 * {@hide}
2820 */
2821 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002822 public static final int TETHER_ERROR_MASTER_ERROR =
2823 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002824 /**
2825 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2826 * {@hide}
2827 */
2828 @Deprecated
2829 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2830 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2831 /**
2832 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2833 * {@hide}
2834 */
2835 @Deprecated
2836 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2837 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2838 /**
markchienf47d8342020-03-19 13:37:43 +08002839 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002840 * {@hide}
2841 */
2842 @Deprecated
2843 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002844 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002845 /**
markchienf47d8342020-03-19 13:37:43 +08002846 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002847 * {@hide}
2848 */
2849 @Deprecated
2850 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002851 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002852 /**
2853 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2854 * {@hide}
2855 */
2856 @Deprecated
2857 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2858 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2859 /**
markchienf47d8342020-03-19 13:37:43 +08002860 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002861 * {@hide}
2862 */
markchien0f45bb92019-01-16 17:44:13 +08002863 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002864 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002865 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
markchien6ae63e52020-01-21 13:11:06 +08002866 /**
2867 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2868 * {@hide}
2869 */
2870 @Deprecated
2871 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2872 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2873 /**
2874 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2875 * {@hide}
2876 */
markchien0f45bb92019-01-16 17:44:13 +08002877 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002878 @Deprecated
Remi NGUYEN VAN09f8ed22021-02-15 18:52:06 +09002879 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002880
2881 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002882 * Get a more detailed error code after a Tethering or Untethering
2883 * request asynchronously failed.
2884 *
2885 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002886 * @return error The error code of the last error tethering or untethering the named
2887 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002888 *
markchien6ae63e52020-01-21 13:11:06 +08002889 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002890 * {@hide}
2891 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002892 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002893 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002894 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002895 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002896 int error = mTetheringManager.getLastTetherError(iface);
2897 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2898 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2899 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2900 // instead.
2901 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2902 }
2903 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002904 }
2905
markchienbf5ab012019-03-06 16:25:00 +08002906 /** @hide */
2907 @Retention(RetentionPolicy.SOURCE)
2908 @IntDef(value = {
2909 TETHER_ERROR_NO_ERROR,
2910 TETHER_ERROR_PROVISION_FAILED,
2911 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2912 })
2913 public @interface EntitlementResultCode {
2914 }
2915
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002916 /**
markchienbf5ab012019-03-06 16:25:00 +08002917 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002918 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002919 *
2920 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002921 * @hide
2922 */
2923 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002924 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002925 public interface OnTetheringEntitlementResultListener {
2926 /**
2927 * Called to notify entitlement result.
2928 *
2929 * @param resultCode an int value of entitlement result. It may be one of
2930 * {@link #TETHER_ERROR_NO_ERROR},
2931 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2932 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2933 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002934 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002935 }
2936
2937 /**
markchien0f45bb92019-01-16 17:44:13 +08002938 * Get the last value of the entitlement check on this downstream. If the cached value is
2939 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2940 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2941 * guaranteed that the UI-based entitlement check will complete in any specific time period
2942 * and may in fact never complete. Any successful entitlement check the platform performs for
2943 * any reason will update the cached value.
2944 *
2945 * @param type the downstream type of tethering. Must be one of
2946 * {@link #TETHERING_WIFI},
2947 * {@link #TETHERING_USB}, or
2948 * {@link #TETHERING_BLUETOOTH}.
2949 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002950 * @param executor the executor on which callback will be invoked.
2951 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2952 * notify the caller of the result of entitlement check. The listener may be called zero
2953 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002954 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002955 * {@hide}
2956 */
2957 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002958 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002959 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002960 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2961 @NonNull @CallbackExecutor Executor executor,
2962 @NonNull final OnTetheringEntitlementResultListener listener) {
2963 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2964 ResultReceiver wrappedListener = new ResultReceiver(null) {
2965 @Override
2966 protected void onReceiveResult(int resultCode, Bundle resultData) {
2967 Binder.withCleanCallingIdentity(() ->
2968 executor.execute(() -> {
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002969 listener.onTetheringEntitlementResult(resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002970 }));
2971 }
2972 };
2973
Amos Bianchia9b415a2020-03-04 11:07:38 -08002974 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08002975 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08002976 }
2977
2978 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002979 * Report network connectivity status. This is currently used only
2980 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04002981 * <p>This method requires the caller to hold the permission
2982 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002983 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07002984 * @param networkType The type of network you want to report on
2985 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09002986 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07002987 * {@hide}
2988 */
2989 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09002990 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002991 try {
2992 mService.reportInetCondition(networkType, percentage);
2993 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002994 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002995 }
2996 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002997
2998 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002999 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003000 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003001 * the framework to re-evaluate network connectivity and/or switch to another
3002 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003003 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003004 * @param network The {@link Network} the application was attempting to use
3005 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003006 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3007 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003008 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003009 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003010 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003011 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003012 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003013 // One of these will be ignored because it matches system's current state.
3014 // The other will trigger the necessary reevaluation.
3015 mService.reportNetworkConnectivity(network, true);
3016 mService.reportNetworkConnectivity(network, false);
3017 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003018 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003019 }
3020 }
3021
3022 /**
3023 * Report to the framework whether a network has working connectivity.
3024 * This provides a hint to the system that a particular network is providing
3025 * working connectivity or not. In response the framework may re-evaluate
3026 * the network's connectivity and might take further action thereafter.
3027 *
3028 * @param network The {@link Network} the application was attempting to use
3029 * or {@code null} to indicate the current default network.
3030 * @param hasConnectivity {@code true} if the application was able to successfully access the
3031 * Internet using {@code network} or {@code false} if not.
3032 */
Chalard Jean158702d2019-01-07 19:26:34 +09003033 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003034 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003035 try {
3036 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003037 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003038 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003039 }
3040 }
3041
3042 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003043 * Set a network-independent global http proxy. This is not normally what you want
3044 * for typical HTTP proxies - they are general network dependent. However if you're
3045 * doing something unusual like general internal filtering this may be useful. On
3046 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003047 *
3048 * @param p A {@link ProxyInfo} object defining the new global
3049 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003050 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003051 */
paulhu8e96a752019-08-12 16:25:11 +08003052 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04003053 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003054 try {
3055 mService.setGlobalProxy(p);
3056 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003057 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003058 }
3059 }
3060
3061 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003062 * Retrieve any network-independent global HTTP proxy.
3063 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003064 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003065 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003066 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003067 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003068 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003069 try {
3070 return mService.getGlobalProxy();
3071 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003072 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003073 }
3074 }
3075
3076 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003077 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3078 * network-specific HTTP proxy. If {@code network} is null, the
3079 * network-specific proxy returned is the proxy of the default active
3080 * network.
3081 *
3082 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3083 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3084 * or when {@code network} is {@code null},
3085 * the {@code ProxyInfo} for the default active network. Returns
3086 * {@code null} when no proxy applies or the caller doesn't have
3087 * permission to use {@code network}.
3088 * @hide
3089 */
3090 public ProxyInfo getProxyForNetwork(Network network) {
3091 try {
3092 return mService.getProxyForNetwork(network);
3093 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003094 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003095 }
3096 }
3097
3098 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003099 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3100 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003101 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003102 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003103 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003104 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003105 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003106 */
Chalard Jean158702d2019-01-07 19:26:34 +09003107 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003108 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003109 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003110 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003111
3112 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003113 * Returns true if the hardware supports the given network type
3114 * else it returns false. This doesn't indicate we have coverage
3115 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003116 * hardware supports it. For example a GSM phone without a SIM
3117 * should still return {@code true} for mobile data, but a wifi only
3118 * tablet would return {@code false}.
3119 *
3120 * @param networkType The network type we'd like to check
3121 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003122 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003123 * @hide
3124 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003125 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003126 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003127 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003128 public boolean isNetworkSupported(int networkType) {
3129 try {
3130 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003131 } catch (RemoteException e) {
3132 throw e.rethrowFromSystemServer();
3133 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003134 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003135
3136 /**
3137 * Returns if the currently active data network is metered. A network is
3138 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003139 * that connection due to monetary costs, data limitations or
3140 * battery/performance issues. You should check this before doing large
3141 * data transfers, and warn the user or delay the operation until another
3142 * network is available.
3143 *
3144 * @return {@code true} if large transfers should be avoided, otherwise
3145 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003146 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003147 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003148 public boolean isActiveNetworkMetered() {
3149 try {
3150 return mService.isActiveNetworkMetered();
3151 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003152 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003153 }
3154 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003155
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003156 /**
Lorenzo Colitticd675292021-02-04 17:32:07 +09003157 * Calls VpnManager#updateLockdownVpn.
3158 * @deprecated TODO: remove when callers have migrated to VpnManager.
3159 * @hide
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003160 */
Lorenzo Colitticd675292021-02-04 17:32:07 +09003161 @Deprecated
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003162 public boolean updateLockdownVpn() {
Lorenzo Colitticd675292021-02-04 17:32:07 +09003163 return getVpnManager().updateLockdownVpn();
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003164 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07003165
3166 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003167 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003168 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003169 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003170 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003171 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003172 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003173 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003174 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003175 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003176 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003177 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003178 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003179 }
3180 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003181
3182 /**
3183 * Set the value for enabling/disabling airplane mode
3184 *
3185 * @param enable whether to enable airplane mode or not
3186 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003187 * @hide
3188 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003189 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003190 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003191 android.Manifest.permission.NETWORK_SETTINGS,
3192 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3193 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003194 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003195 public void setAirplaneMode(boolean enable) {
3196 try {
3197 mService.setAirplaneMode(enable);
3198 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003199 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003200 }
3201 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003202
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003203 /**
3204 * Registers the specified {@link NetworkProvider}.
3205 * Each listener must only be registered once. The listener can be unregistered with
3206 * {@link #unregisterNetworkProvider}.
3207 *
3208 * @param provider the provider to register
3209 * @return the ID of the provider. This ID must be used by the provider when registering
3210 * {@link android.net.NetworkAgent}s.
3211 * @hide
3212 */
3213 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003214 @RequiresPermission(anyOf = {
3215 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3216 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003217 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3218 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003219 throw new IllegalStateException("NetworkProviders can only be registered once");
3220 }
3221
3222 try {
3223 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3224 provider.getName());
3225 provider.setProviderId(providerId);
3226 } catch (RemoteException e) {
3227 throw e.rethrowFromSystemServer();
3228 }
3229 return provider.getProviderId();
3230 }
3231
3232 /**
3233 * Unregisters the specified NetworkProvider.
3234 *
3235 * @param provider the provider to unregister
3236 * @hide
3237 */
3238 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003239 @RequiresPermission(anyOf = {
3240 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3241 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003242 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3243 try {
3244 mService.unregisterNetworkProvider(provider.getMessenger());
3245 } catch (RemoteException e) {
3246 throw e.rethrowFromSystemServer();
3247 }
3248 provider.setProviderId(NetworkProvider.ID_NONE);
3249 }
3250
3251
3252 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003253 @RequiresPermission(anyOf = {
3254 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3255 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003256 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3257 try {
3258 mService.declareNetworkRequestUnfulfillable(request);
3259 } catch (RemoteException e) {
3260 throw e.rethrowFromSystemServer();
3261 }
3262 }
3263
Chalard Jean29d06db2018-05-02 21:14:54 +09003264 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3265 // of dependent changes that would conflict throughout the automerger graph. Having this
3266 // temporarily helps with the process of going through with all these dependent changes across
3267 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003268 /**
3269 * @hide
3270 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003271 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003272 */
paulhub6ba8e82020-03-04 09:43:41 +08003273 @RequiresPermission(anyOf = {
3274 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3275 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003276 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003277 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003278 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003279 }
3280
3281 /**
3282 * @hide
3283 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003284 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003285 */
paulhub6ba8e82020-03-04 09:43:41 +08003286 @RequiresPermission(anyOf = {
3287 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3288 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003289 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003290 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003291 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003292 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003293 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003294 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003295 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003296 }
3297
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003298 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003299 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3300 * changes. Should be extended by applications wanting notifications.
3301 *
3302 * A {@code NetworkCallback} is registered by calling
3303 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3304 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003305 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003306 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3307 * A {@code NetworkCallback} should be registered at most once at any time.
3308 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003309 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003310 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003311 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003312 * Called when the framework connects to a new network to evaluate whether it satisfies this
3313 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3314 * callback. There is no guarantee that this new network will satisfy any requests, or that
3315 * the network will stay connected for longer than the time necessary to evaluate it.
3316 * <p>
3317 * Most applications <b>should not</b> act on this callback, and should instead use
3318 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3319 * the framework in properly evaluating the network &mdash; for example, an application that
3320 * can automatically log in to a captive portal without user intervention.
3321 *
3322 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003323 *
3324 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003325 */
paulhu1a407652019-03-22 16:35:06 +08003326 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003327
3328 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003329 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003330 * This callback may be called more than once if the {@link Network} that is
3331 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003332 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003333 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003334 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3335 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003336 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003337 * @hide
3338 */
paulhu1a407652019-03-22 16:35:06 +08003339 public void onAvailable(@NonNull Network network,
3340 @NonNull NetworkCapabilities networkCapabilities,
3341 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003342 // Internally only this method is called when a new network is available, and
3343 // it calls the callback in the same way and order that older versions used
3344 // to call so as not to change the behavior.
3345 onAvailable(network);
3346 if (!networkCapabilities.hasCapability(
3347 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3348 onNetworkSuspended(network);
3349 }
3350 onCapabilitiesChanged(network, networkCapabilities);
3351 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003352 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003353 }
3354
3355 /**
3356 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003357 *
3358 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3359 * be available at the same time, and onAvailable will be called for each of these as they
3360 * appear.
3361 *
3362 * <p>For callbacks registered with {@link #requestNetwork} and
3363 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3364 * is the new best network for this request and is now tracked by this callback ; this
3365 * callback will no longer receive method calls about other networks that may have been
3366 * passed to this method previously. The previously-best network may have disconnected, or
3367 * it may still be around and the newly-best network may simply be better.
3368 *
3369 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3370 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3371 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3372 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3373 *
3374 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3375 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3376 * this callback as this is prone to race conditions (there is no guarantee the objects
3377 * returned by these methods will be current). Instead, wait for a call to
3378 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3379 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3380 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003381 *
3382 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003383 */
paulhu1a407652019-03-22 16:35:06 +08003384 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003385
3386 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003387 * Called when the network is about to be lost, typically because there are no outstanding
3388 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3389 * with the new replacement network for graceful handover. This method is not guaranteed
3390 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3391 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003392 *
Chalard Jean01378b62019-08-30 16:27:28 +09003393 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3394 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3395 * this callback as this is prone to race conditions ; calling these methods while in a
3396 * callback may return an outdated or even a null object.
3397 *
3398 * @param network The {@link Network} that is about to be lost.
3399 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3400 * connected for graceful handover; note that the network may still
3401 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003402 */
paulhu1a407652019-03-22 16:35:06 +08003403 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003404
3405 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003406 * Called when a network disconnects or otherwise no longer satisfies this request or
3407 * callback.
3408 *
3409 * <p>If the callback was registered with requestNetwork() or
3410 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3411 * returned by onAvailable() when that network is lost and no other network satisfies
3412 * the criteria of the request.
3413 *
3414 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3415 * each network which no longer satisfies the criteria of the callback.
3416 *
3417 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3418 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3419 * this callback as this is prone to race conditions ; calling these methods while in a
3420 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003421 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003422 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003423 */
paulhu1a407652019-03-22 16:35:06 +08003424 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003425
3426 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003427 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003428 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3429 * requested network request cannot be fulfilled (whether or not a timeout was
3430 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003431 * {@link NetworkRequest} will have already been removed and released, as if
3432 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003433 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003434 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003435
3436 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003437 * Called when the network corresponding to this request changes capabilities but still
3438 * satisfies the requested criteria.
3439 *
3440 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3441 * to be called immediately after {@link #onAvailable}.
3442 *
3443 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3444 * ConnectivityManager methods in this callback as this is prone to race conditions :
3445 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003446 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003447 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003448 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3449 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003450 */
paulhu1a407652019-03-22 16:35:06 +08003451 public void onCapabilitiesChanged(@NonNull Network network,
3452 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003453
3454 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003455 * Called when the network corresponding to this request changes {@link LinkProperties}.
3456 *
3457 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3458 * to be called immediately after {@link #onAvailable}.
3459 *
3460 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3461 * ConnectivityManager methods in this callback as this is prone to race conditions :
3462 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003463 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003464 * @param network The {@link Network} whose link properties have changed.
3465 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003466 */
paulhu1a407652019-03-22 16:35:06 +08003467 public void onLinkPropertiesChanged(@NonNull Network network,
3468 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003469
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003470 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003471 * Called when the network the framework connected to for this request suspends data
3472 * transmission temporarily.
3473 *
3474 * <p>This generally means that while the TCP connections are still live temporarily
3475 * network data fails to transfer. To give a specific example, this is used on cellular
3476 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3477 * means read operations on sockets on this network will block once the buffers are
3478 * drained, and write operations will block once the buffers are full.
3479 *
3480 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3481 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3482 * this callback as this is prone to race conditions (there is no guarantee the objects
3483 * returned by these methods will be current).
3484 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003485 * @hide
3486 */
paulhu1a407652019-03-22 16:35:06 +08003487 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003488
3489 /**
3490 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003491 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3492 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003493
3494 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3495 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3496 * this callback as this is prone to race conditions : calling these methods while in a
3497 * callback may return an outdated or even a null object.
3498 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003499 * @hide
3500 */
paulhu1a407652019-03-22 16:35:06 +08003501 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003502
junyulaif2c67e42018-08-07 19:50:45 +08003503 /**
3504 * Called when access to the specified network is blocked or unblocked.
3505 *
Chalard Jean01378b62019-08-30 16:27:28 +09003506 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3507 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3508 * this callback as this is prone to race conditions : calling these methods while in a
3509 * callback may return an outdated or even a null object.
3510 *
junyulaif2c67e42018-08-07 19:50:45 +08003511 * @param network The {@link Network} whose blocked status has changed.
3512 * @param blocked The blocked status of this {@link Network}.
3513 */
junyulai7e06ad42019-03-04 22:45:36 +08003514 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003515
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003516 private NetworkRequest networkRequest;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003517 }
3518
Hugo Benichia590ab82017-05-11 13:16:17 +09003519 /**
3520 * Constant error codes used by ConnectivityService to communicate about failures and errors
3521 * across a Binder boundary.
3522 * @hide
3523 */
3524 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003525 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003526 }
3527
3528 /** @hide */
3529 public static class TooManyRequestsException extends RuntimeException {}
3530
3531 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3532 switch (e.errorCode) {
3533 case Errors.TOO_MANY_REQUESTS:
3534 return new TooManyRequestsException();
3535 default:
3536 Log.w(TAG, "Unknown service error code " + e.errorCode);
3537 return new RuntimeException(e);
3538 }
3539 }
3540
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003541 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003542 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003543 public static final int CALLBACK_PRECHECK = BASE + 1;
3544 /** @hide */
3545 public static final int CALLBACK_AVAILABLE = BASE + 2;
3546 /** @hide arg1 = TTL */
3547 public static final int CALLBACK_LOSING = BASE + 3;
3548 /** @hide */
3549 public static final int CALLBACK_LOST = BASE + 4;
3550 /** @hide */
3551 public static final int CALLBACK_UNAVAIL = BASE + 5;
3552 /** @hide */
3553 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3554 /** @hide */
3555 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003556 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003557 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003558 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003559 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003560 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003561 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003562 /** @hide */
3563 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003564
Erik Kline155a59a2015-11-25 12:49:38 +09003565 /** @hide */
3566 public static String getCallbackName(int whichCallback) {
3567 switch (whichCallback) {
3568 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3569 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3570 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3571 case CALLBACK_LOST: return "CALLBACK_LOST";
3572 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3573 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3574 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003575 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3576 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3577 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003578 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003579 default:
3580 return Integer.toString(whichCallback);
3581 }
3582 }
3583
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003584 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003585 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003586 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003587
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003588 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003589 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003590 }
3591
Hugo Benichifd44e912017-02-02 17:02:36 +09003592 CallbackHandler(Handler handler) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003593 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003594 }
3595
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003596 @Override
3597 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003598 if (message.what == EXPIRE_LEGACY_REQUEST) {
3599 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3600 return;
3601 }
3602
3603 final NetworkRequest request = getObject(message, NetworkRequest.class);
3604 final Network network = getObject(message, Network.class);
3605 final NetworkCallback callback;
3606 synchronized (sCallbacks) {
3607 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003608 if (callback == null) {
3609 Log.w(TAG,
3610 "callback not found for " + getCallbackName(message.what) + " message");
3611 return;
3612 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003613 if (message.what == CALLBACK_UNAVAIL) {
3614 sCallbacks.remove(request);
3615 callback.networkRequest = ALREADY_UNREGISTERED;
3616 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003617 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003618 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003619 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003620 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003621
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003622 switch (message.what) {
3623 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003624 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003625 break;
3626 }
3627 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003628 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3629 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003630 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003631 break;
3632 }
3633 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003634 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003635 break;
3636 }
3637 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003638 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003639 break;
3640 }
3641 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003642 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003643 break;
3644 }
3645 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003646 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3647 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003648 break;
3649 }
3650 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003651 LinkProperties lp = getObject(message, LinkProperties.class);
3652 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003653 break;
3654 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003655 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003656 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003657 break;
3658 }
3659 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003660 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003661 break;
3662 }
junyulaif2c67e42018-08-07 19:50:45 +08003663 case CALLBACK_BLK_CHANGED: {
3664 boolean blocked = message.arg1 != 0;
3665 callback.onBlockedStatusChanged(network, blocked);
3666 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003667 }
3668 }
3669
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003670 private <T> T getObject(Message msg, Class<T> c) {
3671 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003672 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003673 }
3674
Hugo Benichifd44e912017-02-02 17:02:36 +09003675 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003676 synchronized (sCallbacks) {
3677 if (sCallbackHandler == null) {
3678 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003679 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003680 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003681 }
3682 }
3683
Hugo Benichibc4ac972017-02-03 14:18:44 +09003684 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3685 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003686
Hugo Benichibc4ac972017-02-03 14:18:44 +09003687 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003688 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003689 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003690 checkCallbackNotNull(callback);
junyulaiad010792021-01-11 16:53:38 +08003691 Preconditions.checkArgument(
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09003692 reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
3693 "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003694 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003695 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003696 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003697 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003698 if (callback.networkRequest != null
3699 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003700 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3701 // and requests (http://b/20701525).
3702 Log.e(TAG, "NetworkCallback was already registered");
3703 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003704 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003705 Binder binder = new Binder();
junyulaiad010792021-01-11 16:53:38 +08003706 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003707 request = mService.listenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003708 need, messenger, binder, callingPackageName,
3709 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003710 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003711 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003712 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3713 callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003714 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003715 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003716 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003717 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003718 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003719 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003720 } catch (RemoteException e) {
3721 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003722 } catch (ServiceSpecificException e) {
3723 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003724 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003725 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003726 }
3727
3728 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003729 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003730 *
markchienfac84a22020-03-18 21:16:15 +08003731 * This API is only for use in internal system code that requests networks with legacy type and
3732 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003733 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003734 *
markchiend6eeffd2020-01-14 00:55:21 +08003735 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003736 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3737 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3738 * be a positive value (i.e. >0).
3739 * @param legacyType to specify the network type(#TYPE_*).
3740 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003741 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3742 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003743 *
3744 * @hide
3745 */
markchiend6eeffd2020-01-14 00:55:21 +08003746 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003747 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003748 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003749 int timeoutMs, int legacyType, @NonNull Handler handler,
3750 @NonNull NetworkCallback networkCallback) {
3751 if (legacyType == TYPE_NONE) {
3752 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3753 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003754 CallbackHandler cbHandler = new CallbackHandler(handler);
3755 NetworkCapabilities nc = request.networkCapabilities;
3756 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003757 }
3758
3759 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003760 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003761 *
Chalard Jean01378b62019-08-30 16:27:28 +09003762 * <p>This method will attempt to find the best network that matches the passed
3763 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3764 * criteria. The platform will evaluate which network is the best at its own discretion.
3765 * Throughput, latency, cost per byte, policy, user preference and other considerations
3766 * may be factored in the decision of what is considered the best network.
3767 *
3768 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3769 * matching this request, while always attempting to match the request to a better network if
3770 * possible. If a better match is found, the platform will switch this request to the now-best
3771 * network and inform the app of the newly best network by invoking
3772 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3773 * will not try to maintain any other network than the best one currently matching the request:
3774 * a network not matching any network request may be disconnected at any time.
3775 *
3776 * <p>For example, an application could use this method to obtain a connected cellular network
3777 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3778 * radio to consume additional power. Or, an application could inform the system that it wants
3779 * a network supporting sending MMSes and have the system let it know about the currently best
3780 * MMS-supporting network through the provided {@link NetworkCallback}.
3781 *
3782 * <p>The status of the request can be followed by listening to the various callbacks described
3783 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3784 * used to direct traffic to the network (although accessing some networks may be subject to
3785 * holding specific permissions). Callers will learn about the specific characteristics of the
3786 * network through
3787 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3788 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3789 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3790 * matching the request at any given time; therefore when a better network matching the request
3791 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3792 * with the new network after which no further updates are given about the previously-best
3793 * network, unless it becomes the best again at some later time. All callbacks are invoked
3794 * in order on the same thread, which by default is a thread created by the framework running
3795 * in the app.
3796 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3797 * callbacks are invoked.
3798 *
3799 * <p>This{@link NetworkRequest} will live until released via
3800 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3801 * which point the system may let go of the network at any time.
3802 *
3803 * <p>A version of this method which takes a timeout is
3804 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3805 * wait for a limited amount of time for the network to become unavailable.
3806 *
Paul Jensenee52d232015-06-16 15:11:58 -04003807 * <p>It is presently unsupported to request a network with mutable
3808 * {@link NetworkCapabilities} such as
3809 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3810 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3811 * as these {@code NetworkCapabilities} represent states that a particular
3812 * network may never attain, and whether a network will attain these states
3813 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003814 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003815 *
3816 * <p>This method requires the caller to hold either the
3817 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3818 * or the ability to modify system settings as determined by
3819 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003820 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003821 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3822 * number of outstanding requests to 100 per app (identified by their UID), shared with
3823 * all variants of this method, of {@link #registerNetworkCallback} as well as
3824 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3825 * Requesting a network with this method will count toward this limit. If this limit is
3826 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3827 * make sure to unregister the callbacks with
3828 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3829 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003830 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003831 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3832 * the callback must not be shared - it uniquely specifies this request.
3833 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003834 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3835 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003836 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003837 */
Chalard Jean158702d2019-01-07 19:26:34 +09003838 public void requestNetwork(@NonNull NetworkRequest request,
3839 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003840 requestNetwork(request, networkCallback, getDefaultHandler());
3841 }
3842
3843 /**
3844 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3845 *
Chalard Jean01378b62019-08-30 16:27:28 +09003846 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3847 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003848 *
Chalard Jean01378b62019-08-30 16:27:28 +09003849 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003850 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3851 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003852 *
3853 * @param request {@link NetworkRequest} describing this request.
3854 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3855 * the callback must not be shared - it uniquely specifies this request.
3856 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003857 */
Chalard Jean158702d2019-01-07 19:26:34 +09003858 public void requestNetwork(@NonNull NetworkRequest request,
3859 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003860 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003861 NetworkCapabilities nc = request.networkCapabilities;
3862 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003863 }
3864
3865 /**
Etan Cohenf67bde92017-03-01 12:47:28 -08003866 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3867 * by a timeout.
3868 *
3869 * This function behaves identically to the non-timed-out version
3870 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3871 * is not found within the given time (in milliseconds) the
3872 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3873 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3874 * not have to be released if timed-out (it is automatically released). Unregistering a
3875 * request that timed out is not an error.
3876 *
3877 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3878 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3879 * for that purpose. Calling this method will attempt to bring up the requested network.
3880 *
Chalard Jean01378b62019-08-30 16:27:28 +09003881 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003882 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3883 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003884 *
3885 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003886 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3887 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003888 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3889 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3890 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003891 */
Chalard Jean158702d2019-01-07 19:26:34 +09003892 public void requestNetwork(@NonNull NetworkRequest request,
3893 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003894 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003895 NetworkCapabilities nc = request.networkCapabilities;
3896 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3897 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003898 }
3899
Hugo Benichifd44e912017-02-02 17:02:36 +09003900 /**
3901 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3902 * by a timeout.
3903 *
Chalard Jean01378b62019-08-30 16:27:28 +09003904 * This method behaves identically to
3905 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3906 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003907 *
Chalard Jean01378b62019-08-30 16:27:28 +09003908 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003909 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3910 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003911 *
3912 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003913 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3914 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003915 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003916 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3917 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003918 */
Chalard Jean158702d2019-01-07 19:26:34 +09003919 public void requestNetwork(@NonNull NetworkRequest request,
3920 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003921 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003922 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003923 NetworkCapabilities nc = request.networkCapabilities;
3924 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003925 }
3926
3927 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003928 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003929 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003930 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003931 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003932 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3933 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003934 */
Erik Kline8a826212014-11-19 12:12:24 +09003935 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003936
3937 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003938 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003939 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003940 * {@link android.content.Intent#getParcelableExtra(String)}.
3941 */
Erik Kline8a826212014-11-19 12:12:24 +09003942 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003943
3944
3945 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003946 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003947 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003948 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003949 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003950 * the request may outlive the calling application and get called back when a suitable
3951 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003952 * <p>
3953 * The operation is an Intent broadcast that goes to a broadcast receiver that
3954 * you registered with {@link Context#registerReceiver} or through the
3955 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3956 * <p>
3957 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003958 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3959 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003960 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003961 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003962 * Intent to reserve the network or it will be released shortly after the Intent
3963 * is processed.
3964 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003965 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003966 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003967 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003968 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003969 * The request may be released normally by calling
3970 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04003971 * <p>It is presently unsupported to request a network with either
3972 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3973 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3974 * as these {@code NetworkCapabilities} represent states that a particular
3975 * network may never attain, and whether a network will attain these states
3976 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09003977 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003978 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003979 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3980 * number of outstanding requests to 100 per app (identified by their UID), shared with
3981 * all variants of this method, of {@link #registerNetworkCallback} as well as
3982 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3983 * Requesting a network with this method will count toward this limit. If this limit is
3984 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3985 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
3986 * or {@link #releaseNetworkRequest(PendingIntent)}.
3987 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003988 * <p>This method requires the caller to hold either the
3989 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3990 * or the ability to modify system settings as determined by
3991 * {@link android.provider.Settings.System#canWrite}.</p>
3992 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003993 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003994 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003995 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003996 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09003997 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3998 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003999 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004000 */
Chalard Jean158702d2019-01-07 19:26:34 +09004001 public void requestNetwork(@NonNull NetworkRequest request,
4002 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004003 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004004 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004005 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004006 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004007 request.networkCapabilities, operation, mContext.getOpPackageName(),
4008 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004009 } catch (RemoteException e) {
4010 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004011 } catch (ServiceSpecificException e) {
4012 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004013 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004014 }
4015
4016 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004017 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4018 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004019 * This method has the same behavior as
4020 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004021 * releasing network resources and disconnecting.
4022 *
4023 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4024 * PendingIntent passed to
4025 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4026 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4027 */
Chalard Jean158702d2019-01-07 19:26:34 +09004028 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004029 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004030 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004031 try {
4032 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004033 } catch (RemoteException e) {
4034 throw e.rethrowFromSystemServer();
4035 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004036 }
4037
Hugo Benichibc1104b2017-05-09 15:19:01 +09004038 private static void checkPendingIntentNotNull(PendingIntent intent) {
4039 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4040 }
4041
4042 private static void checkCallbackNotNull(NetworkCallback callback) {
4043 Preconditions.checkNotNull(callback, "null NetworkCallback");
4044 }
4045
4046 private static void checkTimeout(int timeoutMs) {
4047 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004048 }
4049
4050 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004051 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004052 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004053 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4054 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004055 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004056 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4057 * number of outstanding requests to 100 per app (identified by their UID), shared with
4058 * all variants of this method, of {@link #requestNetwork} as well as
4059 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4060 * Requesting a network with this method will count toward this limit. If this limit is
4061 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4062 * make sure to unregister the callbacks with
4063 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4064 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004065 * @param request {@link NetworkRequest} describing this request.
4066 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4067 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004068 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004069 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004070 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004071 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004072 public void registerNetworkCallback(@NonNull NetworkRequest request,
4073 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004074 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4075 }
4076
4077 /**
4078 * Registers to receive notifications about all networks which satisfy the given
4079 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004080 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4081 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004082 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004083 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4084 * number of outstanding requests to 100 per app (identified by their UID), shared with
4085 * all variants of this method, of {@link #requestNetwork} as well as
4086 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4087 * Requesting a network with this method will count toward this limit. If this limit is
4088 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4089 * make sure to unregister the callbacks with
4090 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4091 *
4092 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004093 * @param request {@link NetworkRequest} describing this request.
4094 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4095 * networks change state.
4096 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004097 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004098 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004099 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004100 public void registerNetworkCallback(@NonNull NetworkRequest request,
4101 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004102 CallbackHandler cbHandler = new CallbackHandler(handler);
4103 NetworkCapabilities nc = request.networkCapabilities;
4104 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004105 }
4106
4107 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004108 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4109 * {@link NetworkRequest}.
4110 *
4111 * This function behaves identically to the version that takes a NetworkCallback, but instead
4112 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4113 * the request may outlive the calling application and get called back when a suitable
4114 * network is found.
4115 * <p>
4116 * The operation is an Intent broadcast that goes to a broadcast receiver that
4117 * you registered with {@link Context#registerReceiver} or through the
4118 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4119 * <p>
4120 * The operation Intent is delivered with two extras, a {@link Network} typed
4121 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4122 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4123 * the original requests parameters.
4124 * <p>
4125 * If there is already a request for this Intent registered (with the equality of
4126 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4127 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4128 * <p>
4129 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004130 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004131 *
4132 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4133 * number of outstanding requests to 100 per app (identified by their UID), shared with
4134 * all variants of this method, of {@link #requestNetwork} as well as
4135 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4136 * Requesting a network with this method will count toward this limit. If this limit is
4137 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4138 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4139 * or {@link #releaseNetworkRequest(PendingIntent)}.
4140 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004141 * @param request {@link NetworkRequest} describing this request.
4142 * @param operation Action to perform when the network is available (corresponds
4143 * to the {@link NetworkCallback#onAvailable} call. Typically
4144 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004145 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004146 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004147 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004148 public void registerNetworkCallback(@NonNull NetworkRequest request,
4149 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004150 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004151 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004152 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004153 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004154 request.networkCapabilities, operation, mContext.getOpPackageName(),
4155 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004156 } catch (RemoteException e) {
4157 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004158 } catch (ServiceSpecificException e) {
4159 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004160 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004161 }
4162
4163 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004164 * Registers to receive notifications about changes in the application's default network. This
4165 * may be a physical network or a virtual network, such as a VPN that applies to the
4166 * application. The callbacks will continue to be called until either the application exits or
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004167 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004168 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004169 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4170 * number of outstanding requests to 100 per app (identified by their UID), shared with
4171 * all variants of this method, of {@link #requestNetwork} as well as
4172 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4173 * Requesting a network with this method will count toward this limit. If this limit is
4174 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4175 * make sure to unregister the callbacks with
4176 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4177 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004178 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004179 * application's default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004180 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004181 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004182 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004183 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004184 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004185 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4186 }
4187
4188 /**
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004189 * Registers to receive notifications about changes in the application's default network. This
4190 * may be a physical network or a virtual network, such as a VPN that applies to the
4191 * application. The callbacks will continue to be called until either the application exits or
4192 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4193 *
4194 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4195 * number of outstanding requests to 100 per app (identified by their UID), shared with
4196 * all variants of this method, of {@link #requestNetwork} as well as
4197 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4198 * Requesting a network with this method will count toward this limit. If this limit is
4199 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4200 * make sure to unregister the callbacks with
4201 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4202 *
4203 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4204 * application's default network changes.
4205 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4206 * @throws RuntimeException if the app already has too many callbacks registered.
4207 */
4208 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4209 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4210 @NonNull Handler handler) {
4211 CallbackHandler cbHandler = new CallbackHandler(handler);
4212 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4213 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4214 }
4215
4216 /**
Hugo Benichifd44e912017-02-02 17:02:36 +09004217 * Registers to receive notifications about changes in the system default network. The callbacks
4218 * will continue to be called until either the application exits or
4219 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004220 *
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004221 * This method should not be used to determine networking state seen by applications, because in
4222 * many cases, most or even all application traffic may not use the default network directly,
4223 * and traffic from different applications may go on different networks by default. As an
4224 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4225 * and not onto the system default network. Applications or system components desiring to do
4226 * determine network state as seen by applications should use other methods such as
4227 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4228 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004229 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4230 * number of outstanding requests to 100 per app (identified by their UID), shared with
4231 * all variants of this method, of {@link #requestNetwork} as well as
4232 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4233 * Requesting a network with this method will count toward this limit. If this limit is
4234 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4235 * make sure to unregister the callbacks with
4236 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4237 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004238 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4239 * system default network changes.
4240 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004241 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004242 *
4243 * @hide
Hugo Benichifd44e912017-02-02 17:02:36 +09004244 */
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004245 @SystemApi(client = MODULE_LIBRARIES)
4246 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4247 @RequiresPermission(anyOf = {
4248 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4249 android.Manifest.permission.NETWORK_SETTINGS})
4250 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Chalard Jean158702d2019-01-07 19:26:34 +09004251 @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004252 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004253 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09004254 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004255 }
4256
4257 /**
fenglub00f4882015-04-21 17:12:05 -07004258 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4259 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4260 * network connection for updated bandwidth information. The caller will be notified via
4261 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004262 * method assumes that the caller has previously called
4263 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4264 * changes.
fenglu3f357402015-03-20 11:29:56 -07004265 *
fengluea2d9282015-04-27 14:28:04 -07004266 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004267 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004268 */
Chalard Jean158702d2019-01-07 19:26:34 +09004269 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004270 try {
fenglub00f4882015-04-21 17:12:05 -07004271 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004272 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004273 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004274 }
4275 }
4276
4277 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004278 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004279 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4280 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4281 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004282 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4283 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004284 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004285 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4286 * triggering it as soon as this call returns.
4287 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004288 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004289 */
Chalard Jean158702d2019-01-07 19:26:34 +09004290 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004291 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004292 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004293 final List<NetworkRequest> reqs = new ArrayList<>();
4294 // Find all requests associated to this callback and stop callback triggers immediately.
4295 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4296 synchronized (sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09004297 Preconditions.checkArgument(networkCallback.networkRequest != null,
4298 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004299 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4300 Log.d(TAG, "NetworkCallback was already unregistered");
4301 return;
4302 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004303 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4304 if (e.getValue() == networkCallback) {
4305 reqs.add(e.getKey());
4306 }
4307 }
4308 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4309 for (NetworkRequest r : reqs) {
4310 try {
4311 mService.releaseNetworkRequest(r);
4312 } catch (RemoteException e) {
4313 throw e.rethrowFromSystemServer();
4314 }
4315 // Only remove mapping if rpc was successful.
4316 sCallbacks.remove(r);
4317 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004318 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004319 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004320 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004321
4322 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004323 * Unregisters a callback previously registered via
4324 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4325 *
4326 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4327 * PendingIntent passed to
4328 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4329 * Cannot be null.
4330 */
Chalard Jean158702d2019-01-07 19:26:34 +09004331 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004332 releaseNetworkRequest(operation);
4333 }
4334
4335 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004336 * Informs the system whether it should switch to {@code network} regardless of whether it is
4337 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4338 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4339 * the system default network regardless of any other network that's currently connected. If
4340 * {@code always} is true, then the choice is remembered, so that the next time the user
4341 * connects to this network, the system will switch to it.
4342 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004343 * @param network The network to accept.
4344 * @param accept Whether to accept the network even if unvalidated.
4345 * @param always Whether to remember this choice in the future.
4346 *
4347 * @hide
4348 */
lucaslin2240ef62019-03-12 13:08:03 +08004349 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004350 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4351 try {
4352 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004353 } catch (RemoteException e) {
4354 throw e.rethrowFromSystemServer();
4355 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004356 }
4357
4358 /**
lucaslin2240ef62019-03-12 13:08:03 +08004359 * Informs the system whether it should consider the network as validated even if it only has
4360 * partial connectivity. If {@code accept} is true, then the network will be considered as
4361 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4362 * is remembered, so that the next time the user connects to this network, the system will
4363 * switch to it.
4364 *
4365 * @param network The network to accept.
4366 * @param accept Whether to consider the network as validated even if it has partial
4367 * connectivity.
4368 * @param always Whether to remember this choice in the future.
4369 *
4370 * @hide
4371 */
4372 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4373 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4374 try {
4375 mService.setAcceptPartialConnectivity(network, accept, always);
4376 } catch (RemoteException e) {
4377 throw e.rethrowFromSystemServer();
4378 }
4379 }
4380
4381 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004382 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4383 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4384 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4385 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4386 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004387 * @param network The network to accept.
4388 *
4389 * @hide
4390 */
lucaslin2240ef62019-03-12 13:08:03 +08004391 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004392 public void setAvoidUnvalidated(Network network) {
4393 try {
4394 mService.setAvoidUnvalidated(network);
4395 } catch (RemoteException e) {
4396 throw e.rethrowFromSystemServer();
4397 }
4398 }
4399
4400 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004401 * Requests that the system open the captive portal app on the specified network.
4402 *
4403 * @param network The network to log into.
4404 *
4405 * @hide
4406 */
paulhu8e96a752019-08-12 16:25:11 +08004407 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004408 public void startCaptivePortalApp(Network network) {
4409 try {
4410 mService.startCaptivePortalApp(network);
4411 } catch (RemoteException e) {
4412 throw e.rethrowFromSystemServer();
4413 }
4414 }
4415
4416 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004417 * Requests that the system open the captive portal app with the specified extras.
4418 *
4419 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4420 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004421 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004422 * @param appExtras Extras to include in the app start intent.
4423 * @hide
4424 */
4425 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004426 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004427 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004428 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004429 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004430 } catch (RemoteException e) {
4431 throw e.rethrowFromSystemServer();
4432 }
4433 }
4434
4435 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004436 * Determine whether the device is configured to avoid bad wifi.
4437 * @hide
4438 */
4439 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004440 @RequiresPermission(anyOf = {
4441 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4442 android.Manifest.permission.NETWORK_STACK})
4443 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004444 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004445 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004446 } catch (RemoteException e) {
4447 throw e.rethrowFromSystemServer();
4448 }
4449 }
4450
4451 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004452 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4453 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004454 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4455 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004456 *
4457 * An example of such an operation might be a time-sensitive foreground activity, such as a
4458 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4459 */
4460 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4461
4462 /**
4463 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4464 * a backup channel for traffic that is primarily going over another network.
4465 *
4466 * An example might be maintaining backup connections to peers or servers for the purpose of
4467 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4468 * on backup paths should be negligible compared to the traffic on the main path.
4469 */
4470 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4471
4472 /**
4473 * It is acceptable to use metered data to improve network latency and performance.
4474 */
4475 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4476
4477 /**
4478 * Return value to use for unmetered networks. On such networks we currently set all the flags
4479 * to true.
4480 * @hide
4481 */
4482 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4483 MULTIPATH_PREFERENCE_HANDOVER |
4484 MULTIPATH_PREFERENCE_RELIABILITY |
4485 MULTIPATH_PREFERENCE_PERFORMANCE;
4486
4487 /** @hide */
4488 @Retention(RetentionPolicy.SOURCE)
4489 @IntDef(flag = true, value = {
4490 MULTIPATH_PREFERENCE_HANDOVER,
4491 MULTIPATH_PREFERENCE_RELIABILITY,
4492 MULTIPATH_PREFERENCE_PERFORMANCE,
4493 })
4494 public @interface MultipathPreference {
4495 }
4496
4497 /**
4498 * Provides a hint to the calling application on whether it is desirable to use the
4499 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4500 * for multipath data transfer on this network when it is not the system default network.
4501 * Applications desiring to use multipath network protocols should call this method before
4502 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004503 *
4504 * @param network The network on which the application desires to use multipath data.
4505 * If {@code null}, this method will return the a preference that will generally
4506 * apply to metered networks.
4507 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4508 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004509 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004510 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004511 try {
4512 return mService.getMultipathPreference(network);
4513 } catch (RemoteException e) {
4514 throw e.rethrowFromSystemServer();
4515 }
4516 }
4517
4518 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004519 * Resets all connectivity manager settings back to factory defaults.
4520 * @hide
4521 */
paulhu8e96a752019-08-12 16:25:11 +08004522 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004523 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004524 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004525 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004526 mTetheringManager.stopAllTethering();
Lorenzo Colitticd675292021-02-04 17:32:07 +09004527 // TODO: Migrate callers to VpnManager#factoryReset.
4528 getVpnManager().factoryReset();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004529 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004530 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004531 }
4532 }
4533
4534 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004535 * Binds the current process to {@code network}. All Sockets created in the future
4536 * (and not explicitly bound via a bound SocketFactory from
4537 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4538 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4539 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4540 * work and all host name resolutions will fail. This is by design so an application doesn't
4541 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4542 * To clear binding pass {@code null} for {@code network}. Using individually bound
4543 * Sockets created by Network.getSocketFactory().createSocket() and
4544 * performing network-specific host name resolutions via
4545 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004546 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004547 *
4548 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4549 * the current binding.
4550 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4551 */
Chalard Jean158702d2019-01-07 19:26:34 +09004552 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004553 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004554 // instantiated.
4555 return setProcessDefaultNetwork(network);
4556 }
4557
4558 /**
4559 * Binds the current process to {@code network}. All Sockets created in the future
4560 * (and not explicitly bound via a bound SocketFactory from
4561 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4562 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4563 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4564 * work and all host name resolutions will fail. This is by design so an application doesn't
4565 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4566 * To clear binding pass {@code null} for {@code network}. Using individually bound
4567 * Sockets created by Network.getSocketFactory().createSocket() and
4568 * performing network-specific host name resolutions via
4569 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4570 * {@code setProcessDefaultNetwork}.
4571 *
4572 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4573 * the current binding.
4574 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4575 * @deprecated This function can throw {@link IllegalStateException}. Use
4576 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4577 * is a direct replacement.
4578 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004579 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004580 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004581 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004582 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4583
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004584 if (netId != NETID_UNSET) {
4585 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004586 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004587
4588 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4589 return false;
4590 }
4591
4592 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004593 // Set HTTP proxy system properties to match network.
4594 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004595 try {
4596 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4597 } catch (SecurityException e) {
4598 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4599 Log.e(TAG, "Can't set proxy properties", e);
4600 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004601 // Must flush DNS cache as new network may have different DNS resolutions.
4602 InetAddress.clearDnsCache();
4603 // Must flush socket pool as idle sockets will be bound to previous network and may
4604 // cause subsequent fetches to be performed on old network.
4605 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004606 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004607
4608 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004609 }
4610
4611 /**
4612 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004613 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004614 *
4615 * @return {@code Network} to which this process is bound, or {@code null}.
4616 */
Chalard Jean158702d2019-01-07 19:26:34 +09004617 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004618 public Network getBoundNetworkForProcess() {
4619 // Forcing callers to call thru non-static function ensures ConnectivityManager
4620 // instantiated.
4621 return getProcessDefaultNetwork();
4622 }
4623
4624 /**
4625 * Returns the {@link Network} currently bound to this process via
4626 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4627 *
4628 * @return {@code Network} to which this process is bound, or {@code null}.
4629 * @deprecated Using this function can lead to other functions throwing
4630 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4631 * {@code getBoundNetworkForProcess} is a direct replacement.
4632 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004633 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004634 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004635 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004636 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004637 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004638 return new Network(netId);
4639 }
4640
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004641 private void unsupportedStartingFrom(int version) {
4642 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004643 // The getApplicationInfo() call we make below is not supported in system context. Let
4644 // the call through here, and rely on the fact that ConnectivityService will refuse to
4645 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004646 return;
4647 }
4648
4649 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4650 throw new UnsupportedOperationException(
4651 "This method is not supported in target SDK version " + version + " and above");
4652 }
4653 }
4654
4655 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4656 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004657 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004658 // remove these exemptions. Note that this check is not secure, and apps can still access these
4659 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4660 // so is unsupported and may break in the future. http://b/22728205
4661 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004662 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004663 }
4664
Paul Jensen8cdda642014-05-29 10:12:39 -04004665 /**
4666 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004667 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004668 *
4669 * @param network The {@link Network} to bind host resolutions from the current process to, or
4670 * {@code null} to clear the current binding.
4671 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4672 * @hide
4673 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4674 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004675 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004676 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004677 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004678 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004679 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004680 }
Felipe Leme30511352016-01-22 09:44:57 -08004681
4682 /**
4683 * Device is not restricting metered network activity while application is running on
4684 * background.
4685 */
4686 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4687
4688 /**
4689 * Device is restricting metered network activity while application is running on background,
4690 * but application is allowed to bypass it.
4691 * <p>
4692 * In this state, application should take action to mitigate metered network access.
4693 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4694 */
4695 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4696
4697 /**
4698 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004699 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004700 * In this state, application should not try to use the network while running on background,
4701 * because it would be denied.
4702 */
4703 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4704
Felipe Lemed34c9af2016-01-27 14:46:39 -08004705 /**
4706 * A change in the background metered network activity restriction has occurred.
4707 * <p>
4708 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4709 * applies to them.
4710 * <p>
4711 * This is only sent to registered receivers, not manifest receivers.
4712 */
4713 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4714 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4715 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4716
Felipe Leme7e4c1852016-01-25 11:48:04 -08004717 /** @hide */
4718 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004719 @IntDef(flag = false, value = {
4720 RESTRICT_BACKGROUND_STATUS_DISABLED,
4721 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4722 RESTRICT_BACKGROUND_STATUS_ENABLED,
4723 })
Felipe Leme30511352016-01-22 09:44:57 -08004724 public @interface RestrictBackgroundStatus {
4725 }
4726
4727 private INetworkPolicyManager getNetworkPolicyManager() {
4728 synchronized (this) {
4729 if (mNPManager != null) {
4730 return mNPManager;
4731 }
4732 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4733 .getService(Context.NETWORK_POLICY_SERVICE));
4734 return mNPManager;
4735 }
4736 }
4737
4738 /**
4739 * Determines if the calling application is subject to metered network restrictions while
4740 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004741 *
4742 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4743 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4744 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004745 */
4746 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4747 try {
4748 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4749 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004750 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004751 }
4752 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004753
4754 /**
4755 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004756 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4757 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004758 *
4759 * @return Hash of network watchlist config file. Null if config does not exist.
4760 */
Chalard Jean158702d2019-01-07 19:26:34 +09004761 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004762 public byte[] getNetworkWatchlistConfigHash() {
4763 try {
4764 return mService.getNetworkWatchlistConfigHash();
4765 } catch (RemoteException e) {
4766 Log.e(TAG, "Unable to get watchlist config hash");
4767 throw e.rethrowFromSystemServer();
4768 }
4769 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004770
4771 /**
4772 * Returns the {@code uid} of the owner of a network connection.
4773 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004774 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4775 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004776 * @param local The local {@link InetSocketAddress} of a connection.
4777 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004778 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004779 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4780 * android.os.Process#INVALID_UID} if the connection is not found.
4781 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4782 * user.
4783 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004784 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004785 public int getConnectionOwnerUid(
4786 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004787 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4788 try {
4789 return mService.getConnectionOwnerUid(connectionInfo);
4790 } catch (RemoteException e) {
4791 throw e.rethrowFromSystemServer();
4792 }
4793 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004794
4795 private void printStackTrace() {
4796 if (DEBUG) {
4797 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4798 final StringBuffer sb = new StringBuffer();
4799 for (int i = 3; i < callStack.length; i++) {
4800 final String stackTrace = callStack[i].toString();
4801 if (stackTrace == null || stackTrace.contains("android.os")) {
4802 break;
4803 }
4804 sb.append(" [").append(stackTrace).append("]");
4805 }
4806 Log.d(TAG, "StackLog:" + sb.toString());
4807 }
4808 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004809
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004810 /** @hide */
4811 public TestNetworkManager startOrGetTestNetworkManager() {
4812 final IBinder tnBinder;
4813 try {
4814 tnBinder = mService.startOrGetTestNetworkService();
4815 } catch (RemoteException e) {
4816 throw e.rethrowFromSystemServer();
4817 }
4818
4819 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4820 }
4821
Lorenzo Colitticd675292021-02-04 17:32:07 +09004822 /**
4823 * Temporary hack to shim calls from ConnectivityManager to VpnManager. We cannot store a
4824 * private final mVpnManager because ConnectivityManager is initialized before VpnManager.
4825 * @hide TODO: remove.
4826 */
4827 public VpnManager getVpnManager() {
4828 return mContext.getSystemService(VpnManager.class);
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004829 }
4830
4831 /** @hide */
4832 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4833 return new ConnectivityDiagnosticsManager(mContext, mService);
4834 }
4835
Cody Kestingf53a0752020-04-15 12:33:28 -07004836 /**
4837 * Simulates a Data Stall for the specified Network.
4838 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004839 * <p>This method should only be used for tests.
4840 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004841 * <p>The caller must be the owner of the specified Network.
4842 *
4843 * @param detectionMethod The detection method used to identify the Data Stall.
4844 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4845 * @param network The Network for which a Data Stall is being simluated.
4846 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4847 * @throws SecurityException if the caller is not the owner of the given network.
4848 * @hide
4849 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004850 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004851 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4852 android.Manifest.permission.NETWORK_STACK})
4853 public void simulateDataStall(int detectionMethod, long timestampMillis,
4854 @NonNull Network network, @NonNull PersistableBundle extras) {
4855 try {
4856 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4857 } catch (RemoteException e) {
4858 e.rethrowFromSystemServer();
4859 }
4860 }
James Mattis356a8792020-10-28 21:48:54 -07004861
Daniel Brightf9e945b2020-06-15 16:10:01 -07004862 @NonNull
4863 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4864
4865 /**
4866 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4867 * receive available QoS events related to the {@link Network} and local ip + port
4868 * specified within socketInfo.
4869 * <p/>
4870 * The same {@link QosCallback} must be unregistered before being registered a second time,
4871 * otherwise {@link QosCallbackRegistrationException} is thrown.
4872 * <p/>
4873 * This API does not, in itself, require any permission if called with a network that is not
4874 * restricted. However, the underlying implementation currently only supports the IMS network,
4875 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4876 * useful, because they'd never be called back on networks that they would have access to.
4877 *
4878 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4879 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4880 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4881 * @throws RuntimeException if the app already has too many callbacks registered.
4882 *
4883 * Exceptions after the time of registration is passed through
4884 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4885 *
4886 * @param socketInfo the socket information used to match QoS events
4887 * @param callback receives qos events that satisfy socketInfo
4888 * @param executor The executor on which the callback will be invoked. The provided
4889 * {@link Executor} must run callback sequentially, otherwise the order of
4890 * callbacks cannot be guaranteed.
4891 *
4892 * @hide
4893 */
4894 @SystemApi
4895 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4896 @NonNull final QosCallback callback,
4897 @CallbackExecutor @NonNull final Executor executor) {
4898 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4899 Objects.requireNonNull(callback, "callback must be non-null");
4900 Objects.requireNonNull(executor, "executor must be non-null");
4901
4902 try {
4903 synchronized (mQosCallbackConnections) {
4904 if (getQosCallbackConnection(callback) == null) {
4905 final QosCallbackConnection connection =
4906 new QosCallbackConnection(this, callback, executor);
4907 mQosCallbackConnections.add(connection);
4908 mService.registerQosSocketCallback(socketInfo, connection);
4909 } else {
4910 Log.e(TAG, "registerQosCallback: Callback already registered");
4911 throw new QosCallbackRegistrationException();
4912 }
4913 }
4914 } catch (final RemoteException e) {
4915 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4916
4917 // The same unregister method method is called for consistency even though nothing
4918 // will be sent to the ConnectivityService since the callback was never successfully
4919 // registered.
4920 unregisterQosCallback(callback);
4921 e.rethrowFromSystemServer();
4922 } catch (final ServiceSpecificException e) {
4923 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4924 unregisterQosCallback(callback);
4925 throw convertServiceException(e);
4926 }
4927 }
4928
4929 /**
4930 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4931 * events once unregistered and can be registered a second time.
4932 * <p/>
4933 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4934 *
4935 * @param callback the callback being unregistered
4936 *
4937 * @hide
4938 */
4939 @SystemApi
4940 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4941 Objects.requireNonNull(callback, "The callback must be non-null");
4942 try {
4943 synchronized (mQosCallbackConnections) {
4944 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4945 if (connection != null) {
4946 connection.stopReceivingMessages();
4947 mService.unregisterQosCallback(connection);
4948 mQosCallbackConnections.remove(connection);
4949 } else {
4950 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4951 }
4952 }
4953 } catch (final RemoteException e) {
4954 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4955 e.rethrowFromSystemServer();
4956 }
4957 }
4958
4959 /**
4960 * Gets the connection related to the callback.
4961 *
4962 * @param callback the callback to look up
4963 * @return the related connection
4964 */
4965 @Nullable
4966 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4967 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4968 // Checking by reference here is intentional
4969 if (connection.getCallback() == callback) {
4970 return connection;
4971 }
4972 }
4973 return null;
4974 }
Junyu Laia62493f2021-01-19 11:10:56 +00004975
4976 /**
4977 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4978 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4979 * be used to request that the system provide a network without causing the network to be
4980 * in the foreground.
4981 *
4982 * <p>This method will attempt to find the best network that matches the passed
4983 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4984 * criteria. The platform will evaluate which network is the best at its own discretion.
4985 * Throughput, latency, cost per byte, policy, user preference and other considerations
4986 * may be factored in the decision of what is considered the best network.
4987 *
4988 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4989 * matching this request, while always attempting to match the request to a better network if
4990 * possible. If a better match is found, the platform will switch this request to the now-best
4991 * network and inform the app of the newly best network by invoking
4992 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4993 * will not try to maintain any other network than the best one currently matching the request:
4994 * a network not matching any network request may be disconnected at any time.
4995 *
4996 * <p>For example, an application could use this method to obtain a connected cellular network
4997 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4998 * radio to consume additional power. Or, an application could inform the system that it wants
4999 * a network supporting sending MMSes and have the system let it know about the currently best
5000 * MMS-supporting network through the provided {@link NetworkCallback}.
5001 *
5002 * <p>The status of the request can be followed by listening to the various callbacks described
5003 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5004 * used to direct traffic to the network (although accessing some networks may be subject to
5005 * holding specific permissions). Callers will learn about the specific characteristics of the
5006 * network through
5007 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5008 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5009 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5010 * matching the request at any given time; therefore when a better network matching the request
5011 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5012 * with the new network after which no further updates are given about the previously-best
5013 * network, unless it becomes the best again at some later time. All callbacks are invoked
5014 * in order on the same thread, which by default is a thread created by the framework running
5015 * in the app.
5016 *
5017 * <p>This{@link NetworkRequest} will live until released via
5018 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5019 * which point the system may let go of the network at any time.
5020 *
5021 * <p>It is presently unsupported to request a network with mutable
5022 * {@link NetworkCapabilities} such as
5023 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5024 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5025 * as these {@code NetworkCapabilities} represent states that a particular
5026 * network may never attain, and whether a network will attain these states
5027 * is unknown prior to bringing up the network so the framework does not
5028 * know how to go about satisfying a request with these capabilities.
5029 *
5030 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5031 * number of outstanding requests to 100 per app (identified by their UID), shared with
5032 * all variants of this method, of {@link #registerNetworkCallback} as well as
5033 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5034 * Requesting a network with this method will count toward this limit. If this limit is
5035 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5036 * make sure to unregister the callbacks with
5037 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5038 *
5039 * @param request {@link NetworkRequest} describing this request.
5040 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5041 * If null, the callback is invoked on the default internal Handler.
5042 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5043 * the callback must not be shared - it uniquely specifies this request.
5044 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5045 * @throws SecurityException if missing the appropriate permissions.
5046 * @throws RuntimeException if the app already has too many callbacks registered.
5047 *
5048 * @hide
5049 */
5050 @SystemApi(client = MODULE_LIBRARIES)
5051 @SuppressLint("ExecutorRegistration")
5052 @RequiresPermission(anyOf = {
5053 android.Manifest.permission.NETWORK_SETTINGS,
5054 android.Manifest.permission.NETWORK_STACK,
5055 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5056 })
5057 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
5058 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
5059 final NetworkCapabilities nc = request.networkCapabilities;
5060 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
5061 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
5062 }
James Mattis45d81842021-01-10 14:24:24 -08005063
5064 /**
5065 * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
5066 * OnSetOemNetworkPreferenceListener)}.
James Mattisda32cfe2021-01-26 16:23:52 -08005067 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005068 */
James Mattisda32cfe2021-01-26 16:23:52 -08005069 @SystemApi
5070 public interface OnSetOemNetworkPreferenceListener {
James Mattis45d81842021-01-10 14:24:24 -08005071 /**
5072 * Called when setOemNetworkPreference() successfully completes.
5073 */
5074 void onComplete();
5075 }
5076
5077 /**
5078 * Used by automotive devices to set the network preferences used to direct traffic at an
5079 * application level as per the given OemNetworkPreferences. An example use-case would be an
5080 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5081 * vehicle via a particular network.
5082 *
5083 * Calling this will overwrite the existing preference.
5084 *
5085 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5086 * @param executor the executor on which listener will be invoked.
5087 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5088 * communicate completion of setOemNetworkPreference(). This will only be
5089 * called once upon successful completion of setOemNetworkPreference().
5090 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5091 * @throws SecurityException if missing the appropriate permissions.
5092 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattisda32cfe2021-01-26 16:23:52 -08005093 * @hide
James Mattis45d81842021-01-10 14:24:24 -08005094 */
James Mattisda32cfe2021-01-26 16:23:52 -08005095 @SystemApi
James Mattis8378aec2021-01-26 14:05:36 -08005096 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattisda32cfe2021-01-26 16:23:52 -08005097 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis45d81842021-01-10 14:24:24 -08005098 @Nullable @CallbackExecutor final Executor executor,
5099 @Nullable final OnSetOemNetworkPreferenceListener listener) {
5100 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5101 if (null != listener) {
5102 Objects.requireNonNull(executor, "Executor must be non-null");
5103 }
5104 final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
5105 new IOnSetOemNetworkPreferenceListener.Stub() {
5106 @Override
5107 public void onComplete() {
5108 executor.execute(listener::onComplete);
5109 }
5110 };
5111
5112 try {
5113 mService.setOemNetworkPreference(preference, listenerInternal);
5114 } catch (RemoteException e) {
5115 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5116 throw e.rethrowFromSystemServer();
5117 }
5118 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005119}