blob: d04a5bee510555395f6681430fbbcf5fb12ab3f1 [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;
Daniel Brightf9e945b2020-06-15 16:10:01 -070024import static android.net.QosCallback.QosCallbackRegistrationException;
junyulaid05a1922019-01-15 11:32:44 +080025
junyulai4c95b082018-12-27 17:25:29 +080026import android.annotation.CallbackExecutor;
Felipe Leme30511352016-01-22 09:44:57 -080027import android.annotation.IntDef;
Chalard Jean158702d2019-01-07 19:26:34 +090028import android.annotation.NonNull;
Robin Leee5d5ed52016-01-05 18:03:46 +000029import android.annotation.Nullable;
Jeff Sharkey656584a2017-04-24 11:18:03 -060030import android.annotation.RequiresPermission;
The Android Open Source Project28527d22009-03-03 19:31:44 -080031import android.annotation.SdkConstant;
32import android.annotation.SdkConstant.SdkConstantType;
Junyu Laia62493f2021-01-19 11:10:56 +000033import android.annotation.SuppressLint;
Udam Sainicd645462016-01-04 12:16:14 -080034import android.annotation.SystemApi;
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -060035import android.annotation.SystemService;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070036import android.app.PendingIntent;
Artur Satayev9c2add62019-12-10 17:47:52 +000037import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070038import android.content.Context;
Robert Greenwaltf3017f72014-05-18 23:07:25 -070039import android.content.Intent;
junyulai4c95b082018-12-27 17:25:29 +080040import android.net.IpSecManager.UdpEncapsulationSocket;
41import android.net.SocketKeepalive.Callback;
markchien91c78e52020-01-20 19:31:56 +080042import android.net.TetheringManager.StartTetheringCallback;
markchien6ae63e52020-01-21 13:11:06 +080043import android.net.TetheringManager.TetheringEventCallback;
markchien91c78e52020-01-20 19:31:56 +080044import android.net.TetheringManager.TetheringRequest;
Robert Greenwalt2034b912009-08-12 16:08:25 -070045import android.os.Binder;
Mathew Inwoodbdfc1fc2018-12-20 15:30:45 +000046import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070047import android.os.Build.VERSION_CODES;
Jeremy Klein3dabcb92016-01-22 14:11:45 -080048import android.os.Bundle;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070049import android.os.Handler;
Dianne Hackborn5ac88162014-02-26 16:20:52 -080050import android.os.IBinder;
51import android.os.INetworkActivityListener;
52import android.os.INetworkManagementService;
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
markchiena0f8fd92019-12-25 19:40:32 +0800458 public static final int TETHERING_WIFI = TetheringManager.TETHERING_WIFI;
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
markchiena0f8fd92019-12-25 19:40:32 +0800466 public static final int TETHERING_USB = TetheringManager.TETHERING_USB;
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
markchiena0f8fd92019-12-25 19:40:32 +0800474 public static final int TETHERING_BLUETOOTH = TetheringManager.TETHERING_BLUETOOTH;
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;
Paul Jensenc0618a62014-12-10 15:12:18 -0500826 /**
827 * A kludge to facilitate static access where a Context pointer isn't available, like in the
828 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
829 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
830 * methods that take a Context argument.
831 */
832 private static ConnectivityManager sInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800833
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +0900834 private final Context mContext;
835
Dianne Hackborn5ac88162014-02-26 16:20:52 -0800836 private INetworkManagementService mNMService;
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 /**
Charles He9369e612017-05-15 17:07:18 +01001071 * Checks if a VPN app supports always-on mode.
1072 *
1073 * In order to support the always-on feature, an app has to
1074 * <ul>
1075 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hed6813632017-08-15 15:30:22 +01001076 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
1077 * meta-data field.
Charles He9369e612017-05-15 17:07:18 +01001078 * </ul>
1079 *
1080 * @param userId The identifier of the user for whom the VPN app is installed.
1081 * @param vpnPackage The canonical package name of the VPN app.
1082 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
1083 * @hide
1084 */
1085 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1086 try {
1087 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1088 } catch (RemoteException e) {
1089 throw e.rethrowFromSystemServer();
1090 }
1091 }
1092
1093 /**
Robin Leee5d5ed52016-01-05 18:03:46 +00001094 * Configures an always-on VPN connection through a specific application.
1095 * This connection is automatically granted and persisted after a reboot.
1096 *
1097 * <p>The designated package should declare a {@link VpnService} in its
1098 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1099 * otherwise the call will fail.
1100 *
1101 * @param userId The identifier of the user to set an always-on VPN for.
1102 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1103 * to remove an existing always-on VPN configuration.
Robin Lee94e69be2016-05-03 13:23:03 +01001104 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1105 * {@code false} otherwise.
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001106 * @param lockdownAllowlist The list of packages that are allowed to access network directly
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001107 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001108 * this method must be called when a package that should be allowed is installed or
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001109 * uninstalled.
Robin Leee5d5ed52016-01-05 18:03:46 +00001110 * @return {@code true} if the package is set as always-on VPN controller;
1111 * {@code false} otherwise.
1112 * @hide
1113 */
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001114 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee94e69be2016-05-03 13:23:03 +01001115 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001116 boolean lockdownEnabled, @Nullable List<String> lockdownAllowlist) {
Robin Leee5d5ed52016-01-05 18:03:46 +00001117 try {
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001118 return mService.setAlwaysOnVpnPackage(
Chiachang Wang3b9549f2020-07-28 13:53:09 +08001119 userId, vpnPackage, lockdownEnabled, lockdownAllowlist);
Robin Leee5d5ed52016-01-05 18:03:46 +00001120 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001121 throw e.rethrowFromSystemServer();
Robin Leee5d5ed52016-01-05 18:03:46 +00001122 }
1123 }
1124
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001125 /**
Robin Leee5d5ed52016-01-05 18:03:46 +00001126 * Returns the package name of the currently set always-on VPN application.
1127 * If there is no always-on VPN set, or the VPN is provided by the system instead
1128 * of by an app, {@code null} will be returned.
1129 *
1130 * @return Package name of VPN controller responsible for always-on VPN,
1131 * or {@code null} if none is set.
1132 * @hide
1133 */
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001134 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leee5d5ed52016-01-05 18:03:46 +00001135 public String getAlwaysOnVpnPackageForUser(int userId) {
1136 try {
1137 return mService.getAlwaysOnVpnPackage(userId);
1138 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001139 throw e.rethrowFromSystemServer();
Robin Leee5d5ed52016-01-05 18:03:46 +00001140 }
1141 }
1142
1143 /**
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00001144 * @return whether always-on VPN is in lockdown mode.
1145 *
1146 * @hide
1147 **/
1148 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1149 public boolean isVpnLockdownEnabled(int userId) {
1150 try {
1151 return mService.isVpnLockdownEnabled(userId);
1152 } catch (RemoteException e) {
1153 throw e.rethrowFromSystemServer();
1154 }
1155
1156 }
1157
1158 /**
1159 * @return the list of packages that are allowed to access network when always-on VPN is in
1160 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1161 *
1162 * @hide
1163 **/
1164 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1165 public List<String> getVpnLockdownWhitelist(int userId) {
1166 try {
1167 return mService.getVpnLockdownWhitelist(userId);
1168 } catch (RemoteException e) {
1169 throw e.rethrowFromSystemServer();
1170 }
1171 }
1172
1173 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001174 * Adds or removes a requirement for given UID ranges to use the VPN.
1175 *
1176 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1177 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1178 * otherwise have permission to bypass the VPN (e.g., because they have the
1179 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1180 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1181 * set to {@code false}, a previously-added restriction is removed.
1182 * <p>
1183 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1184 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1185 * remove a previously-added range, the exact range must be removed as is.
1186 * <p>
1187 * The changes are applied asynchronously and may not have been applied by the time the method
1188 * returns. Apps will be notified about any changes that apply to them via
1189 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1190 * effect.
1191 * <p>
1192 * This method should be called only by the VPN code.
1193 *
1194 * @param ranges the UID ranges to restrict
1195 * @param requireVpn whether the specified UID ranges must use a VPN
1196 *
1197 * TODO: expose as @SystemApi.
1198 * @hide
1199 */
1200 @RequiresPermission(anyOf = {
1201 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1202 android.Manifest.permission.NETWORK_STACK})
1203 public void setRequireVpnForUids(boolean requireVpn,
1204 @NonNull Collection<Range<Integer>> ranges) {
1205 Objects.requireNonNull(ranges);
1206 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1207 // This method is not necessarily expected to be used outside the system server, so
1208 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1209 // stack process, or by tests.
1210 UidRange[] rangesArray = new UidRange[ranges.size()];
1211 int index = 0;
1212 for (Range<Integer> range : ranges) {
1213 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1214 }
1215 try {
1216 mService.setRequireVpnForUids(requireVpn, rangesArray);
1217 } catch (RemoteException e) {
1218 throw e.rethrowFromSystemServer();
1219 }
1220 }
1221
1222 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001223 * Returns details about the currently active default data network
1224 * for a given uid. This is for internal use only to avoid spying
1225 * other apps.
1226 *
1227 * @return a {@link NetworkInfo} object for the current default network
1228 * for the given uid or {@code null} if no default network is
1229 * available for the specified uid.
1230 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001231 * {@hide}
1232 */
paulhu8e96a752019-08-12 16:25:11 +08001233 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001234 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001235 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001236 return getActiveNetworkInfoForUid(uid, false);
1237 }
1238
1239 /** {@hide} */
1240 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001241 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001242 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001243 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001244 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001245 }
1246 }
1247
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001248 /**
1249 * Returns connection status information about a particular
1250 * network type.
1251 *
1252 * @param networkType integer specifying which networkType in
1253 * which you're interested.
1254 * @return a {@link NetworkInfo} object for the requested
1255 * network type or {@code null} if the type is not
Chalard Jean96d10a72018-03-29 17:45:24 +09001256 * supported by the device. If {@code networkType} is
1257 * TYPE_VPN and a VPN is active for the calling app,
1258 * then this method will try to return one of the
1259 * underlying networks for the VPN or null if the
1260 * VPN agent didn't specify any.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001261 *
Paul Jensendda8e592015-03-18 12:23:02 -04001262 * @deprecated This method does not support multiple connected networks
1263 * of the same type. Use {@link #getAllNetworks} and
1264 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001265 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001266 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001267 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001268 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001269 public NetworkInfo getNetworkInfo(int networkType) {
1270 try {
1271 return mService.getNetworkInfo(networkType);
1272 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001273 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001274 }
1275 }
1276
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001277 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001278 * Returns connection status information about a particular
1279 * Network.
1280 *
1281 * @param network {@link Network} specifying which network
1282 * in which you're interested.
1283 * @return a {@link NetworkInfo} object for the requested
1284 * network or {@code null} if the {@code Network}
1285 * is not valid.
junyulai9826e7f2018-12-13 12:47:51 +08001286 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001287 */
junyulai9826e7f2018-12-13 12:47:51 +08001288 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001289 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001290 @Nullable
1291 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001292 return getNetworkInfoForUid(network, Process.myUid(), false);
1293 }
1294
1295 /** {@hide} */
1296 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001297 try {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001298 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001299 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001300 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001301 }
1302 }
1303
1304 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001305 * Returns connection status information about all network
1306 * types supported by the device.
1307 *
1308 * @return an array of {@link NetworkInfo} objects. Check each
1309 * {@link NetworkInfo#getType} for which type each applies.
1310 *
Paul Jensendda8e592015-03-18 12:23:02 -04001311 * @deprecated This method does not support multiple connected networks
1312 * of the same type. Use {@link #getAllNetworks} and
1313 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001314 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001315 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001316 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001317 @NonNull
The Android Open Source Project28527d22009-03-03 19:31:44 -08001318 public NetworkInfo[] getAllNetworkInfo() {
1319 try {
1320 return mService.getAllNetworkInfo();
1321 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001322 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001323 }
1324 }
1325
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001326 /**
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001327 * Returns the {@link Network} object currently serving a given type, or
1328 * null if the given type is not connected.
1329 *
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001330 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04001331 * @deprecated This method does not support multiple connected networks
1332 * of the same type. Use {@link #getAllNetworks} and
1333 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001334 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001335 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001336 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001337 @UnsupportedAppUsage
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001338 public Network getNetworkForType(int networkType) {
1339 try {
1340 return mService.getNetworkForType(networkType);
1341 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001342 throw e.rethrowFromSystemServer();
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001343 }
1344 }
1345
1346 /**
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001347 * Returns an array of all {@link Network} currently tracked by the
1348 * framework.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001349 *
1350 * @return an array of {@link Network} objects.
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001351 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001352 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001353 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001354 public Network[] getAllNetworks() {
1355 try {
1356 return mService.getAllNetworks();
1357 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001358 throw e.rethrowFromSystemServer();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001359 }
1360 }
1361
1362 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001363 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001364 * the Networks that applications run by the given user will use by default.
1365 * @hide
1366 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01001367 @UnsupportedAppUsage
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001368 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1369 try {
Qingxi Lib2748102020-01-08 12:51:49 -08001370 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001371 userId, mContext.getOpPackageName(), getAttributionTag());
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001372 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001373 throw e.rethrowFromSystemServer();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001374 }
1375 }
1376
1377 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001378 * Returns the IP information for the current default network.
1379 *
1380 * @return a {@link LinkProperties} object describing the IP info
1381 * for the current default network, or {@code null} if there
1382 * is no current default network.
1383 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001384 * {@hide}
Chalard Jean97021a12019-01-11 16:47:53 +09001385 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1386 * value of {@link #getActiveNetwork()} instead. In particular,
1387 * this method will return non-null LinkProperties even if the
1388 * app is blocked by policy from using this network.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001389 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001390 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean97021a12019-01-11 16:47:53 +09001391 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001392 public LinkProperties getActiveLinkProperties() {
1393 try {
1394 return mService.getActiveLinkProperties();
1395 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001396 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001397 }
1398 }
1399
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001400 /**
1401 * Returns the IP information for a given network type.
1402 *
1403 * @param networkType the network type of interest.
1404 * @return a {@link LinkProperties} object describing the IP info
1405 * for the given networkType, or {@code null} if there is
1406 * no current default network.
1407 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001408 * {@hide}
Paul Jensendda8e592015-03-18 12:23:02 -04001409 * @deprecated This method does not support multiple connected networks
1410 * of the same type. Use {@link #getAllNetworks},
1411 * {@link #getNetworkInfo(android.net.Network)}, and
1412 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001413 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001414 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06001415 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09001416 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001417 public LinkProperties getLinkProperties(int networkType) {
1418 try {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001419 return mService.getLinkPropertiesForType(networkType);
1420 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001421 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001422 }
1423 }
1424
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001425 /**
1426 * Get the {@link LinkProperties} for the given {@link Network}. This
1427 * will return {@code null} if the network is unknown.
1428 *
1429 * @param network The {@link Network} object identifying the network in question.
1430 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04001431 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001432 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001433 @Nullable
1434 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001435 try {
1436 return mService.getLinkProperties(network);
1437 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001438 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001439 }
1440 }
1441
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001442 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001443 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001444 * will return {@code null} if the network is unknown.
1445 *
1446 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09001447 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001448 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06001449 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09001450 @Nullable
1451 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001452 try {
Roshan Piusaa24fde2020-12-17 14:53:09 -08001453 return mService.getNetworkCapabilities(
1454 network, mContext.getOpPackageName(), getAttributionTag());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001455 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001456 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001457 }
1458 }
1459
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001460 /**
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001461 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainicd645462016-01-04 12:16:14 -08001462 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1463 * portal is present.
1464 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1465 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1466 *
Remi NGUYEN VAN035f6532019-03-20 14:22:49 +09001467 * The system network validation may be using different strategies to detect captive portals,
1468 * so this method does not necessarily return a URL used by the system. It only returns a URL
1469 * that may be relevant for other components trying to detect captive portals.
paulhu8e96a752019-08-12 16:25:11 +08001470 *
Udam Sainicd645462016-01-04 12:16:14 -08001471 * @hide
paulhu8e96a752019-08-12 16:25:11 +08001472 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1473 * system.
Udam Sainicd645462016-01-04 12:16:14 -08001474 */
paulhu8e96a752019-08-12 16:25:11 +08001475 @Deprecated
Udam Sainicd645462016-01-04 12:16:14 -08001476 @SystemApi
paulhu8e96a752019-08-12 16:25:11 +08001477 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainicd645462016-01-04 12:16:14 -08001478 public String getCaptivePortalServerUrl() {
1479 try {
1480 return mService.getCaptivePortalServerUrl();
1481 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001482 throw e.rethrowFromSystemServer();
Udam Sainicd645462016-01-04 12:16:14 -08001483 }
1484 }
1485
1486 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001487 * Tells the underlying networking system that the caller wants to
1488 * begin using the named feature. The interpretation of {@code feature}
1489 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001490 *
1491 * <p>This method requires the caller to hold either the
1492 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1493 * or the ability to modify system settings as determined by
1494 * {@link android.provider.Settings.System#canWrite}.</p>
1495 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001496 * @param networkType specifies which network the request pertains to
1497 * @param feature the name of the feature to be used
1498 * @return an integer value representing the outcome of the request.
1499 * The interpretation of this value is specific to each networking
1500 * implementation+feature combination, except that the value {@code -1}
1501 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001502 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09001503 * @deprecated Deprecated in favor of the cleaner
1504 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001505 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001506 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001507 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001508 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001509 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001510 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001511 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001512 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1513 if (netCap == null) {
1514 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1515 feature);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001516 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001517 }
1518
1519 NetworkRequest request = null;
1520 synchronized (sLegacyRequests) {
1521 LegacyRequest l = sLegacyRequests.get(netCap);
1522 if (l != null) {
1523 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1524 renewRequestLocked(l);
1525 if (l.currentNetwork != null) {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001526 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001527 } else {
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001528 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001529 }
1530 }
1531
1532 request = requestNetworkForFeatureLocked(netCap);
1533 }
1534 if (request != null) {
Robert Greenwaltb8401732014-06-20 10:58:45 -07001535 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001536 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001537 } else {
1538 Log.d(TAG, " request Failed");
Chalard Jeanafaed1a2019-11-21 14:48:00 +09001539 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001540 }
1541 }
1542
1543 /**
1544 * Tells the underlying networking system that the caller is finished
1545 * using the named feature. The interpretation of {@code feature}
1546 * is completely up to each networking implementation.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09001547 *
1548 * <p>This method requires the caller to hold either the
1549 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1550 * or the ability to modify system settings as determined by
1551 * {@link android.provider.Settings.System#canWrite}.</p>
1552 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001553 * @param networkType specifies which network the request pertains to
1554 * @param feature the name of the feature that is no longer needed
1555 * @return an integer value representing the outcome of the request.
1556 * The interpretation of this value is specific to each networking
1557 * implementation+feature combination, except that the value {@code -1}
1558 * always indicates failure.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07001559 *
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09001560 * @deprecated Deprecated in favor of the cleaner
1561 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07001562 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001563 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09001564 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001565 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07001566 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001567 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09001568 checkLegacyRoutingApiAccess();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001569 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1570 if (netCap == null) {
1571 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1572 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001573 return -1;
1574 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001575
Paul Jensen49f74a32014-12-17 10:39:34 -05001576 if (removeRequestForFeature(netCap)) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001577 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001578 }
1579 return 1;
1580 }
1581
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001582 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001583 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1584 if (networkType == TYPE_MOBILE) {
Erik Klinece55eb12017-01-26 18:08:28 +09001585 switch (feature) {
1586 case "enableCBS":
1587 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1588 case "enableDUN":
1589 case "enableDUNAlways":
1590 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1591 case "enableFOTA":
1592 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1593 case "enableHIPRI":
1594 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1595 case "enableIMS":
1596 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1597 case "enableMMS":
1598 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1599 case "enableSUPL":
1600 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1601 default:
1602 return null;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001603 }
Erik Klinece55eb12017-01-26 18:08:28 +09001604 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1605 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001606 }
1607 return null;
1608 }
1609
Robert Greenwalt802c1102014-06-02 15:32:02 -07001610 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001611 if (netCap == null) return TYPE_NONE;
1612 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1613 return TYPE_MOBILE_CBS;
1614 }
1615 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1616 return TYPE_MOBILE_IMS;
1617 }
1618 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1619 return TYPE_MOBILE_FOTA;
1620 }
1621 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1622 return TYPE_MOBILE_DUN;
1623 }
1624 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1625 return TYPE_MOBILE_SUPL;
1626 }
1627 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1628 return TYPE_MOBILE_MMS;
1629 }
1630 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1631 return TYPE_MOBILE_HIPRI;
1632 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001633 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1634 return TYPE_WIFI_P2P;
1635 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001636 return TYPE_NONE;
1637 }
1638
1639 private static class LegacyRequest {
1640 NetworkCapabilities networkCapabilities;
1641 NetworkRequest networkRequest;
1642 int expireSequenceNumber;
1643 Network currentNetwork;
1644 int delay = -1;
Paul Jensen49f74a32014-12-17 10:39:34 -05001645
1646 private void clearDnsBinding() {
1647 if (currentNetwork != null) {
1648 currentNetwork = null;
1649 setProcessDefaultNetworkForHostResolution(null);
1650 }
1651 }
1652
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001653 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001654 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001655 public void onAvailable(Network network) {
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001656 currentNetwork = network;
1657 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen8cdda642014-05-29 10:12:39 -04001658 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001659 }
1660 @Override
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07001661 public void onLost(Network network) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001662 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001663 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1664 }
1665 };
1666 }
1667
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001668 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean9dd11612018-06-04 16:52:49 +09001669 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1670 new HashMap<>();
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001671
1672 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1673 synchronized (sLegacyRequests) {
1674 LegacyRequest l = sLegacyRequests.get(netCap);
1675 if (l != null) return l.networkRequest;
1676 }
1677 return null;
1678 }
1679
1680 private void renewRequestLocked(LegacyRequest l) {
1681 l.expireSequenceNumber++;
1682 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1683 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1684 }
1685
1686 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1687 int ourSeqNum = -1;
1688 synchronized (sLegacyRequests) {
1689 LegacyRequest l = sLegacyRequests.get(netCap);
1690 if (l == null) return;
1691 ourSeqNum = l.expireSequenceNumber;
Paul Jensen49f74a32014-12-17 10:39:34 -05001692 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001693 }
1694 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1695 }
1696
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001697 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001698 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1699 int delay = -1;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001700 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001701 try {
1702 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07001703 } catch (RemoteException e) {
1704 throw e.rethrowFromSystemServer();
1705 }
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001706 LegacyRequest l = new LegacyRequest();
1707 l.networkCapabilities = netCap;
1708 l.delay = delay;
1709 l.expireSequenceNumber = 0;
Hugo Benichifd44e912017-02-02 17:02:36 +09001710 l.networkRequest = sendRequestForNetwork(
1711 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001712 if (l.networkRequest == null) return null;
1713 sLegacyRequests.put(netCap, l);
1714 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1715 return l.networkRequest;
1716 }
1717
1718 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1719 if (delay >= 0) {
1720 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichifd44e912017-02-02 17:02:36 +09001721 CallbackHandler handler = getDefaultHandler();
Hugo Benichibc4ac972017-02-03 14:18:44 +09001722 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1723 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001724 }
1725 }
1726
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001727 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen49f74a32014-12-17 10:39:34 -05001728 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1729 final LegacyRequest l;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001730 synchronized (sLegacyRequests) {
Paul Jensen49f74a32014-12-17 10:39:34 -05001731 l = sLegacyRequests.remove(netCap);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07001732 }
Paul Jensen49f74a32014-12-17 10:39:34 -05001733 if (l == null) return false;
1734 unregisterNetworkCallback(l.networkCallback);
1735 l.clearDnsBinding();
1736 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001737 }
1738
Erik Klinece55eb12017-01-26 18:08:28 +09001739 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1740 static {
1741 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1742 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1743 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1744 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1745 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1746 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1747 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1748 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1749 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1750 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1751 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1752 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1753 }
1754
1755 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1756 static {
1757 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1758 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1759 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1760 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1761 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1762 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1763 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1764 }
1765
1766 /**
1767 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1768 * instance suitable for registering a request or callback. Throws an
1769 * IllegalArgumentException if no mapping from the legacy type to
1770 * NetworkCapabilities is known.
1771 *
Chalard Jean7eaf3b12018-03-08 13:54:53 +09001772 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1773 * to find the network instead.
Erik Klinece55eb12017-01-26 18:08:28 +09001774 * @hide
1775 */
1776 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1777 final NetworkCapabilities nc = new NetworkCapabilities();
1778
1779 // Map from type to transports.
1780 final int NOT_FOUND = -1;
1781 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichibc1104b2017-05-09 15:19:01 +09001782 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Klinece55eb12017-01-26 18:08:28 +09001783 nc.addTransportType(transport);
1784
1785 // Map from type to capabilities.
1786 nc.addCapability(sLegacyTypeToCapability.get(
1787 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1788 nc.maybeMarkCapabilitiesRestricted();
1789 return nc;
1790 }
1791
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001792 /** @hide */
1793 public static class PacketKeepaliveCallback {
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001794 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev56cb6bb2019-11-04 17:50:59 +00001795 public PacketKeepaliveCallback() {
1796 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001797 /** The requested keepalive was successfully started. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001798 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001799 public void onStarted() {}
1800 /** The keepalive was successfully stopped. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001801 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001802 public void onStopped() {}
1803 /** An error occurred. */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001804 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001805 public void onError(int error) {}
1806 }
1807
1808 /**
1809 * Allows applications to request that the system periodically send specific packets on their
1810 * behalf, using hardware offload to save battery power.
1811 *
1812 * To request that the system send keepalives, call one of the methods that return a
1813 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1814 * passing in a non-null callback. If the callback is successfully started, the callback's
1815 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1816 * specifying one of the {@code ERROR_*} constants in this class.
1817 *
Chalard Jean9dd11612018-06-04 16:52:49 +09001818 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1819 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1820 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001821 *
junyulai4c95b082018-12-27 17:25:29 +08001822 * @deprecated Use {@link SocketKeepalive} instead.
1823 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001824 * @hide
1825 */
1826 public class PacketKeepalive {
1827
1828 private static final String TAG = "PacketKeepalive";
1829
1830 /** @hide */
1831 public static final int SUCCESS = 0;
1832
1833 /** @hide */
1834 public static final int NO_KEEPALIVE = -1;
1835
1836 /** @hide */
1837 public static final int BINDER_DIED = -10;
1838
1839 /** The specified {@code Network} is not connected. */
1840 public static final int ERROR_INVALID_NETWORK = -20;
1841 /** The specified IP addresses are invalid. For example, the specified source IP address is
1842 * not configured on the specified {@code Network}. */
1843 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1844 /** The requested port is invalid. */
1845 public static final int ERROR_INVALID_PORT = -22;
1846 /** The packet length is invalid (e.g., too long). */
1847 public static final int ERROR_INVALID_LENGTH = -23;
1848 /** The packet transmission interval is invalid (e.g., too short). */
1849 public static final int ERROR_INVALID_INTERVAL = -24;
1850
1851 /** The hardware does not support this request. */
1852 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti723f82f2015-09-08 16:46:36 +09001853 /** The hardware returned an error. */
1854 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001855
Nathan Harold0990bc82018-02-14 13:09:45 -08001856 /** The NAT-T destination port for IPsec */
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001857 public static final int NATT_PORT = 4500;
1858
Nathan Harold0990bc82018-02-14 13:09:45 -08001859 /** The minimum interval in seconds between keepalive packet transmissions */
1860 public static final int MIN_INTERVAL = 10;
1861
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001862 private final Network mNetwork;
junyulai070f9ff2019-01-16 20:23:34 +08001863 private final ISocketKeepaliveCallback mCallback;
1864 private final ExecutorService mExecutor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001865
1866 private volatile Integer mSlot;
1867
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001868 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001869 public void stop() {
1870 try {
junyulai070f9ff2019-01-16 20:23:34 +08001871 mExecutor.execute(() -> {
1872 try {
1873 if (mSlot != null) {
1874 mService.stopKeepalive(mNetwork, mSlot);
1875 }
1876 } catch (RemoteException e) {
1877 Log.e(TAG, "Error stopping packet keepalive: ", e);
1878 throw e.rethrowFromSystemServer();
1879 }
1880 });
1881 } catch (RejectedExecutionException e) {
1882 // The internal executor has already stopped due to previous event.
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001883 }
1884 }
1885
1886 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09001887 Preconditions.checkNotNull(network, "network cannot be null");
1888 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001889 mNetwork = network;
junyulai070f9ff2019-01-16 20:23:34 +08001890 mExecutor = Executors.newSingleThreadExecutor();
1891 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001892 @Override
junyulai070f9ff2019-01-16 20:23:34 +08001893 public void onStarted(int slot) {
lucaslinbe801382020-12-30 11:54:55 +08001894 final long token = Binder.clearCallingIdentity();
1895 try {
1896 mExecutor.execute(() -> {
1897 mSlot = slot;
1898 callback.onStarted();
1899 });
1900 } finally {
1901 Binder.restoreCallingIdentity(token);
1902 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001903 }
junyulai070f9ff2019-01-16 20:23:34 +08001904
1905 @Override
1906 public void onStopped() {
lucaslinbe801382020-12-30 11:54:55 +08001907 final long token = Binder.clearCallingIdentity();
1908 try {
1909 mExecutor.execute(() -> {
1910 mSlot = null;
1911 callback.onStopped();
1912 });
1913 } finally {
1914 Binder.restoreCallingIdentity(token);
1915 }
junyulai070f9ff2019-01-16 20:23:34 +08001916 mExecutor.shutdown();
1917 }
1918
1919 @Override
1920 public void onError(int error) {
lucaslinbe801382020-12-30 11:54:55 +08001921 final long token = Binder.clearCallingIdentity();
1922 try {
1923 mExecutor.execute(() -> {
1924 mSlot = null;
1925 callback.onError(error);
1926 });
1927 } finally {
1928 Binder.restoreCallingIdentity(token);
1929 }
junyulai070f9ff2019-01-16 20:23:34 +08001930 mExecutor.shutdown();
1931 }
1932
1933 @Override
1934 public void onDataReceived() {
1935 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1936 // this callback when data is received.
1937 }
1938 };
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001939 }
1940 }
1941
1942 /**
1943 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1944 *
junyulai4c95b082018-12-27 17:25:29 +08001945 * @deprecated Use {@link #createSocketKeepalive} instead.
1946 *
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001947 * @hide
1948 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00001949 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001950 public PacketKeepalive startNattKeepalive(
1951 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1952 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1953 final PacketKeepalive k = new PacketKeepalive(network, callback);
1954 try {
junyulai070f9ff2019-01-16 20:23:34 +08001955 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001956 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1957 } catch (RemoteException e) {
1958 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai070f9ff2019-01-16 20:23:34 +08001959 throw e.rethrowFromSystemServer();
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001960 }
1961 return k;
1962 }
1963
Chiachang Wang619319a2021-01-15 11:06:21 +08001964 // Construct an invalid fd.
1965 private ParcelFileDescriptor createInvalidFd() {
1966 final int invalidFd = -1;
1967 return ParcelFileDescriptor.adoptFd(invalidFd);
1968 }
1969
The Android Open Source Project28527d22009-03-03 19:31:44 -08001970 /**
junyulai4c95b082018-12-27 17:25:29 +08001971 * Request that keepalives be started on a IPsec NAT-T socket.
1972 *
1973 * @param network The {@link Network} the socket is on.
1974 * @param socket The socket that needs to be kept alive.
1975 * @param source The source address of the {@link UdpEncapsulationSocket}.
1976 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1977 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1978 * must run callback sequentially, otherwise the order of callbacks cannot be
1979 * guaranteed.
1980 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1981 * changes. Must be extended by applications that use this API.
1982 *
junyulai0835a1e2019-01-08 20:04:33 +08001983 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1984 * given socket.
junyulai4c95b082018-12-27 17:25:29 +08001985 **/
junyulai7e06ad42019-03-04 22:45:36 +08001986 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai4c95b082018-12-27 17:25:29 +08001987 @NonNull UdpEncapsulationSocket socket,
1988 @NonNull InetAddress source,
1989 @NonNull InetAddress destination,
1990 @NonNull @CallbackExecutor Executor executor,
1991 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08001992 ParcelFileDescriptor dup;
1993 try {
junyulai828dad12019-03-27 11:00:37 +08001994 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1995 // which cannot be obtained by the app process.
junyulai7e06ad42019-03-04 22:45:36 +08001996 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1997 } catch (IOException ignored) {
1998 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1999 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002000 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002001 }
2002 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2003 destination, executor, callback);
junyulaid05a1922019-01-15 11:32:44 +08002004 }
2005
2006 /**
2007 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2008 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2009 *
2010 * @param network The {@link Network} the socket is on.
junyulai7e06ad42019-03-04 22:45:36 +08002011 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2012 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2013 * from that port.
junyulaid05a1922019-01-15 11:32:44 +08002014 * @param source The source address of the {@link UdpEncapsulationSocket}.
2015 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2016 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2017 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2018 * must run callback sequentially, otherwise the order of callbacks cannot be
2019 * guaranteed.
2020 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2021 * changes. Must be extended by applications that use this API.
2022 *
junyulai0835a1e2019-01-08 20:04:33 +08002023 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2024 * given socket.
junyulaid05a1922019-01-15 11:32:44 +08002025 * @hide
2026 */
2027 @SystemApi
2028 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002029 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2030 @NonNull ParcelFileDescriptor pfd,
junyulaid05a1922019-01-15 11:32:44 +08002031 @NonNull InetAddress source,
2032 @NonNull InetAddress destination,
2033 @NonNull @CallbackExecutor Executor executor,
2034 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002035 ParcelFileDescriptor dup;
2036 try {
junyulai828dad12019-03-27 11:00:37 +08002037 // TODO: Consider remove unnecessary dup.
junyulai7e06ad42019-03-04 22:45:36 +08002038 dup = pfd.dup();
2039 } catch (IOException ignored) {
2040 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2041 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002042 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002043 }
2044 return new NattSocketKeepalive(mService, network, dup,
2045 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai4c95b082018-12-27 17:25:29 +08002046 }
2047
2048 /**
junyulai0835a1e2019-01-08 20:04:33 +08002049 * Request that keepalives be started on a TCP socket.
2050 * The socket must be established.
2051 *
2052 * @param network The {@link Network} the socket is on.
2053 * @param socket The socket that needs to be kept alive.
2054 * @param executor The executor on which callback will be invoked. This implementation assumes
2055 * the provided {@link Executor} runs the callbacks in sequence with no
2056 * concurrency. Failing this, no guarantee of correctness can be made. It is
2057 * the responsibility of the caller to ensure the executor provides this
2058 * guarantee. A simple way of creating such an executor is with the standard
2059 * tool {@code Executors.newSingleThreadExecutor}.
2060 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2061 * changes. Must be extended by applications that use this API.
2062 *
2063 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2064 * given socket.
2065 * @hide
2066 */
2067 @SystemApi
2068 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai7e06ad42019-03-04 22:45:36 +08002069 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai0835a1e2019-01-08 20:04:33 +08002070 @NonNull Socket socket,
2071 @NonNull Executor executor,
2072 @NonNull Callback callback) {
junyulai7e06ad42019-03-04 22:45:36 +08002073 ParcelFileDescriptor dup;
2074 try {
2075 dup = ParcelFileDescriptor.fromSocket(socket);
2076 } catch (UncheckedIOException ignored) {
2077 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2078 // ERROR_INVALID_SOCKET.
Chiachang Wang619319a2021-01-15 11:06:21 +08002079 dup = createInvalidFd();
junyulai7e06ad42019-03-04 22:45:36 +08002080 }
2081 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai0835a1e2019-01-08 20:04:33 +08002082 }
2083
2084 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002085 * Ensure that a network route exists to deliver traffic to the specified
2086 * host via the specified network interface. An attempt to add a route that
2087 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002088 *
2089 * <p>This method requires the caller to hold either the
2090 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2091 * or the ability to modify system settings as determined by
2092 * {@link android.provider.Settings.System#canWrite}.</p>
2093 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002094 * @param networkType the type of the network over which traffic to the specified
2095 * host is to be routed
2096 * @param hostAddress the IP address of the host to which the route is desired
2097 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002098 *
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002099 * @deprecated Deprecated in favor of the
2100 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2101 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn18c1d832015-07-31 10:35:34 -07002102 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002103 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti84d7f072016-12-09 18:39:30 +09002104 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002105 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002106 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002107 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002108 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002109 }
2110
2111 /**
2112 * Ensure that a network route exists to deliver traffic to the specified
2113 * host via the specified network interface. An attempt to add a route that
2114 * already exists is ignored, but treated as successful.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002115 *
2116 * <p>This method requires the caller to hold either the
2117 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2118 * or the ability to modify system settings as determined by
2119 * {@link android.provider.Settings.System#canWrite}.</p>
2120 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002121 * @param networkType the type of the network over which traffic to the specified
2122 * host is to be routed
2123 * @param hostAddress the IP address of the host to which the route is desired
2124 * @return {@code true} on success, {@code false} on failure
2125 * @hide
Robert Greenwaltf3017f72014-05-18 23:07:25 -07002126 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09002127 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002128 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002129 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002130 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002131 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002132 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002133 try {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002134 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2135 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002136 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002137 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002138 }
2139 }
2140
2141 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002142 * @return the context's attribution tag
2143 */
2144 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2145 private @Nullable String getAttributionTag() {
Roshan Piusaa24fde2020-12-17 14:53:09 -08002146 return mContext.getAttributionTag();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002147 }
2148
2149 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002150 * Returns the value of the setting for background data usage. If false,
2151 * applications should not use the network if the application is not in the
2152 * foreground. Developers should respect this setting, and check the value
2153 * of this before performing any background data operations.
2154 * <p>
2155 * All applications that have background services that use the network
2156 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002157 * <p>
Scott Main50589142011-10-06 18:32:43 -07002158 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002159 * background data depends on several combined factors, and this method will
2160 * always return {@code true}. Instead, when background data is unavailable,
2161 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002162 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002163 * @return Whether background data usage is allowed.
2164 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002165 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002166 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002167 // assume that background data is allowed; final authority is
2168 // NetworkInfo which may be blocked.
2169 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002170 }
2171
2172 /**
2173 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002174 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002175 * @param allowBackgroundData Whether an application should use data while
2176 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002177 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002178 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2179 * @see #getBackgroundDataSetting()
2180 * @hide
2181 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002182 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002183 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002184 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002185 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002186 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002187
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002188 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002189 * @hide
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002190 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002191 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002192 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002193 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002194 public boolean getMobileDataEnabled() {
Meng Wanged6f4412019-11-18 17:10:00 -08002195 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2196 if (tm != null) {
2197 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2198 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2199 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2200 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2201 + " retVal=" + retVal);
2202 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002203 }
Wink Saville689f7042014-12-05 11:10:30 -08002204 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt0c150c02014-05-21 20:04:36 -07002205 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002206 }
2207
The Android Open Source Project28527d22009-03-03 19:31:44 -08002208 /**
Robert Greenwaltad35b132014-09-04 16:44:35 -07002209 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002210 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002211 */
2212 public interface OnNetworkActiveListener {
2213 /**
2214 * Called on the main thread of the process to report that the current data network
2215 * has become active, and it is now a good time to perform any pending network
2216 * operations. Note that this listener only tells you when the network becomes
2217 * active; if at any other time you want to know whether it is active (and thus okay
2218 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002219 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002220 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002221 void onNetworkActive();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002222 }
2223
2224 private INetworkManagementService getNetworkManagementService() {
2225 synchronized (this) {
2226 if (mNMService != null) {
2227 return mNMService;
2228 }
2229 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2230 mNMService = INetworkManagementService.Stub.asInterface(b);
2231 return mNMService;
2232 }
2233 }
2234
2235 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean9dd11612018-06-04 16:52:49 +09002236 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002237
2238 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002239 * Start listening to reports when the system's default data network is active, meaning it is
2240 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2241 * to determine the current state of the system's default network after registering the
2242 * listener.
2243 * <p>
2244 * If the process default network has been set with
Paul Jensenee2f45d2015-03-10 10:54:12 -04002245 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002246 * reflect the process's default, but the system default.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002247 *
2248 * @param l The listener to be told when the network is active.
2249 */
Robert Greenwaltad35b132014-09-04 16:44:35 -07002250 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002251 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2252 @Override
2253 public void onNetworkActive() throws RemoteException {
2254 l.onNetworkActive();
2255 }
2256 };
2257
2258 try {
2259 getNetworkManagementService().registerNetworkActivityListener(rl);
2260 mNetworkActivityListeners.put(l, rl);
2261 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002262 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002263 }
2264 }
2265
2266 /**
2267 * Remove network active listener previously registered with
Robert Greenwaltad35b132014-09-04 16:44:35 -07002268 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002269 *
2270 * @param l Previously registered listener.
2271 */
Chalard Jean158702d2019-01-07 19:26:34 +09002272 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002273 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichibc1104b2017-05-09 15:19:01 +09002274 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002275 try {
2276 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2277 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002278 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002279 }
2280 }
2281
2282 /**
2283 * Return whether the data network is currently active. An active network means that
2284 * it is currently in a high power state for performing data transmission. On some
2285 * types of networks, it may be expensive to move and stay in such a state, so it is
2286 * more power efficient to batch network traffic together when the radio is already in
2287 * this state. This method tells you whether right now is currently a good time to
2288 * initiate network traffic, as the network is already active.
2289 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07002290 public boolean isDefaultNetworkActive() {
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002291 try {
2292 return getNetworkManagementService().isNetworkActive();
2293 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07002294 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002295 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002296 }
2297
2298 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002299 * {@hide}
2300 */
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09002301 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002302 mContext = Preconditions.checkNotNull(context, "missing context");
2303 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchia9b415a2020-03-04 11:07:38 -08002304 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensenc0618a62014-12-10 15:12:18 -05002305 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002306 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002307
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002308 /** {@hide} */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002309 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002310 public static ConnectivityManager from(Context context) {
2311 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2312 }
2313
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09002314 /** @hide */
2315 public NetworkRequest getDefaultRequest() {
2316 try {
2317 // This is not racy as the default request is final in ConnectivityService.
2318 return mService.getDefaultRequest();
2319 } catch (RemoteException e) {
2320 throw e.rethrowFromSystemServer();
2321 }
2322 }
2323
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09002324 /* TODO: These permissions checks don't belong in client-side code. Move them to
2325 * services.jar, possibly in com.android.server.net. */
2326
2327 /** {@hide} */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002328 public static final void enforceChangePermission(Context context,
2329 String callingPkg, String callingAttributionTag) {
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002330 int uid = Binder.getCallingUid();
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002331 checkAndNoteChangeNetworkStateOperation(context, uid, callingPkg,
2332 callingAttributionTag, true /* throwException */);
2333 }
2334
2335 /**
2336 * Check if the package is a allowed to change the network state. This also accounts that such
2337 * an access happened.
2338 *
2339 * @return {@code true} iff the package is allowed to change the network state.
2340 */
2341 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2342 private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context,
2343 int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag,
2344 boolean throwException) {
2345 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, callingPackage,
2346 throwException);
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002347 }
2348
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002349 /**
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002350 * Check if the package is a allowed to write settings. This also accounts that such an access
2351 * happened.
2352 *
2353 * @return {@code true} iff the package is allowed to write settings.
2354 */
2355 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2356 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2357 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2358 boolean throwException) {
2359 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2360 throwException);
2361 }
2362
2363 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05002364 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2365 * situations where a Context pointer is unavailable.
2366 * @hide
2367 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002368 @Deprecated
Paul Jensenee2f45d2015-03-10 10:54:12 -04002369 static ConnectivityManager getInstanceOrNull() {
2370 return sInstance;
2371 }
2372
2373 /**
2374 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2375 * situations where a Context pointer is unavailable.
2376 * @hide
2377 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07002378 @Deprecated
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002379 @UnsupportedAppUsage
Paul Jensenee2f45d2015-03-10 10:54:12 -04002380 private static ConnectivityManager getInstance() {
2381 if (getInstanceOrNull() == null) {
Paul Jensenc0618a62014-12-10 15:12:18 -05002382 throw new IllegalStateException("No ConnectivityManager yet constructed");
2383 }
Paul Jensenee2f45d2015-03-10 10:54:12 -04002384 return getInstanceOrNull();
Paul Jensenc0618a62014-12-10 15:12:18 -05002385 }
2386
2387 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002388 * Get the set of tetherable, available interfaces. This list is limited by
2389 * device configuration and current interface existence.
2390 *
2391 * @return an array of 0 or more Strings of tetherable interface names.
2392 *
markchien6ae63e52020-01-21 13:11:06 +08002393 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002394 * {@hide}
2395 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002396 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002397 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002398 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002399 public String[] getTetherableIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002400 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002401 }
2402
2403 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002404 * Get the set of tethered interfaces.
2405 *
2406 * @return an array of 0 or more String of currently tethered interface names.
2407 *
markchien6ae63e52020-01-21 13:11:06 +08002408 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002409 * {@hide}
2410 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002411 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002412 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002413 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002414 public String[] getTetheredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002415 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002416 }
2417
2418 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002419 * Get the set of interface names which attempted to tether but
2420 * failed. Re-attempting to tether may cause them to reset to the Tethered
2421 * state. Alternatively, causing the interface to be destroyed and recreated
2422 * may cause them to reset to the available state.
2423 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2424 * information on the cause of the errors.
2425 *
2426 * @return an array of 0 or more String indicating the interface names
2427 * which failed to tether.
2428 *
markchien6ae63e52020-01-21 13:11:06 +08002429 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002430 * {@hide}
2431 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002432 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002433 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002434 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002435 public String[] getTetheringErroredIfaces() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002436 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002437 }
2438
2439 /**
Robert Greenwalte594a762014-06-23 14:53:42 -07002440 * Get the set of tethered dhcp ranges.
2441 *
markchien2e6ba522020-02-14 11:55:48 +08002442 * @deprecated This method is not supported.
2443 * TODO: remove this function when all of clients are removed.
Robert Greenwalte594a762014-06-23 14:53:42 -07002444 * {@hide}
2445 */
paulhu8e96a752019-08-12 16:25:11 +08002446 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien6ae63e52020-01-21 13:11:06 +08002447 @Deprecated
Robert Greenwalte594a762014-06-23 14:53:42 -07002448 public String[] getTetheredDhcpRanges() {
markchien2e6ba522020-02-14 11:55:48 +08002449 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalte594a762014-06-23 14:53:42 -07002450 }
2451
2452 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002453 * Attempt to tether the named interface. This will setup a dhcp server
2454 * on the interface, forward and NAT IP packets and forward DNS requests
2455 * to the best active upstream network interface. Note that if no upstream
2456 * IP network interface is available, dhcp will still run and traffic will be
2457 * allowed between the tethered devices and this device, though upstream net
2458 * access will of course fail until an upstream network interface becomes
2459 * active.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002460 *
2461 * <p>This method requires the caller to hold either the
2462 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2463 * or the ability to modify system settings as determined by
2464 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002465 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002466 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2467 * and WifiStateMachine which need direct access. All other clients should use
2468 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2469 * logic.</p>
2470 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002471 * @param iface the interface name to tether.
2472 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002473 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002474 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002475 * {@hide}
2476 */
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002477 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien91c78e52020-01-20 19:31:56 +08002478 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002479 public int tether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002480 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002481 }
2482
2483 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002484 * Stop tethering the named interface.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002485 *
2486 * <p>This method requires the caller to hold either the
2487 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2488 * or the ability to modify system settings as determined by
2489 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002490 *
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002491 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2492 * and WifiStateMachine which need direct access. All other clients should use
2493 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2494 * logic.</p>
2495 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002496 * @param iface the interface name to untether.
2497 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2498 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002499 * {@hide}
2500 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002501 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002502 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002503 public int untether(String iface) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002504 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002505 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002506
2507 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002508 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002509 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002510 * due to device configuration.
2511 *
Chalard Jeanffacaef2017-09-26 15:45:18 +09002512 * <p>If this app does not have permission to use this API, it will always
2513 * return false rather than throw an exception.</p>
2514 *
2515 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2516 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2517 *
2518 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2519 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2520 *
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002521 * @return a boolean - {@code true} indicating Tethering is supported.
2522 *
markchien6ae63e52020-01-21 13:11:06 +08002523 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002524 * {@hide}
2525 */
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002526 @SystemApi
Chalard Jeanffacaef2017-09-26 15:45:18 +09002527 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2528 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002529 public boolean isTetheringSupported() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002530 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002531 }
2532
2533 /**
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002534 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchien91c78e52020-01-20 19:31:56 +08002535 *
2536 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002537 * @hide
2538 */
2539 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002540 @Deprecated
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002541 public static abstract class OnStartTetheringCallback {
2542 /**
2543 * Called when tethering has been successfully started.
2544 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002545 public void onTetheringStarted() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002546
2547 /**
2548 * Called when starting tethering failed.
2549 */
Chalard Jean9dd11612018-06-04 16:52:49 +09002550 public void onTetheringFailed() {}
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002551 }
2552
2553 /**
2554 * Convenient overload for
2555 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2556 * handler to run on the current thread's {@link Looper}.
markchien91c78e52020-01-20 19:31:56 +08002557 *
2558 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002559 * @hide
2560 */
2561 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002562 @Deprecated
Udam Saini8f7d6a72017-06-07 12:06:28 -07002563 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002564 public void startTethering(int type, boolean showProvisioningUi,
2565 final OnStartTetheringCallback callback) {
2566 startTethering(type, showProvisioningUi, callback, null);
2567 }
2568
2569 /**
2570 * Runs tether provisioning for the given type if needed and then starts tethering if
2571 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2572 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2573 * schedules tether provisioning re-checks if appropriate.
2574 *
2575 * @param type The type of tethering to start. Must be one of
2576 * {@link ConnectivityManager.TETHERING_WIFI},
2577 * {@link ConnectivityManager.TETHERING_USB}, or
2578 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2579 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2580 * is one. This should be true the first time this function is called and also any time
2581 * the user can see this UI. It gives users information from their carrier about the
2582 * check failing and how they can sign up for tethering if possible.
2583 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2584 * of the result of trying to tether.
2585 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien91c78e52020-01-20 19:31:56 +08002586 *
2587 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002588 * @hide
2589 */
2590 @SystemApi
markchien91c78e52020-01-20 19:31:56 +08002591 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002592 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002593 public void startTethering(int type, boolean showProvisioningUi,
2594 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09002595 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002596
markchien91c78e52020-01-20 19:31:56 +08002597 final Executor executor = new Executor() {
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002598 @Override
markchien91c78e52020-01-20 19:31:56 +08002599 public void execute(Runnable command) {
2600 if (handler == null) {
2601 command.run();
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002602 } else {
markchien91c78e52020-01-20 19:31:56 +08002603 handler.post(command);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002604 }
2605 }
2606 };
Jeremy Klein35e99ea2016-03-12 16:29:54 -08002607
markchien91c78e52020-01-20 19:31:56 +08002608 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2609 @Override
2610 public void onTetheringStarted() {
2611 callback.onTetheringStarted();
2612 }
2613
2614 @Override
markchienf47d8342020-03-19 13:37:43 +08002615 public void onTetheringFailed(final int error) {
markchien91c78e52020-01-20 19:31:56 +08002616 callback.onTetheringFailed();
2617 }
2618 };
2619
2620 final TetheringRequest request = new TetheringRequest.Builder(type)
markchienf47d8342020-03-19 13:37:43 +08002621 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchien91c78e52020-01-20 19:31:56 +08002622
Amos Bianchia9b415a2020-03-04 11:07:38 -08002623 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002624 }
2625
2626 /**
2627 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2628 * applicable.
2629 *
2630 * @param type The type of tethering to stop. Must be one of
2631 * {@link ConnectivityManager.TETHERING_WIFI},
2632 * {@link ConnectivityManager.TETHERING_USB}, or
2633 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien6ae63e52020-01-21 13:11:06 +08002634 *
2635 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002636 * @hide
2637 */
2638 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002639 @Deprecated
Jeff Sharkey9b39e9a2017-06-02 17:36:26 -06002640 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002641 public void stopTethering(int type) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002642 mTetheringManager.stopTethering(type);
Jeremy Klein3dabcb92016-01-22 14:11:45 -08002643 }
2644
2645 /**
markchien4ef53e82019-02-27 14:56:11 +08002646 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2647 * upstream status.
2648 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002649 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien6ae63e52020-01-21 13:11:06 +08002650 * @hide
markchien4ef53e82019-02-27 14:56:11 +08002651 */
2652 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002653 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002654 public abstract static class OnTetheringEventCallback {
2655
2656 /**
2657 * Called when tethering upstream changed. This can be called multiple times and can be
2658 * called any time.
2659 *
2660 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2661 * have any upstream.
2662 */
2663 public void onUpstreamChanged(@Nullable Network network) {}
2664 }
2665
markchien6ae63e52020-01-21 13:11:06 +08002666 @GuardedBy("mTetheringEventCallbacks")
2667 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2668 mTetheringEventCallbacks = new ArrayMap<>();
2669
markchien4ef53e82019-02-27 14:56:11 +08002670 /**
2671 * Start listening to tethering change events. Any new added callback will receive the last
markchien42e22092019-04-03 10:43:09 +08002672 * tethering status right away. If callback is registered when tethering has no upstream or
markchien4ef53e82019-02-27 14:56:11 +08002673 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2674 * with a null argument. The same callback object cannot be registered twice.
2675 *
2676 * @param executor the executor on which callback will be invoked.
2677 * @param callback the callback to be called when tethering has change events.
markchien6ae63e52020-01-21 13:11:06 +08002678 *
Nathan Harold74f0fb82020-01-23 18:03:46 -08002679 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002680 * @hide
2681 */
2682 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002683 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002684 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2685 public void registerTetheringEventCallback(
2686 @NonNull @CallbackExecutor Executor executor,
2687 @NonNull final OnTetheringEventCallback callback) {
2688 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2689
markchien6ae63e52020-01-21 13:11:06 +08002690 final TetheringEventCallback tetherCallback =
2691 new TetheringEventCallback() {
2692 @Override
2693 public void onUpstreamChanged(@Nullable Network network) {
2694 callback.onUpstreamChanged(network);
2695 }
2696 };
2697
2698 synchronized (mTetheringEventCallbacks) {
2699 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002700 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002701 }
markchien4ef53e82019-02-27 14:56:11 +08002702 }
2703
2704 /**
2705 * Remove tethering event callback previously registered with
2706 * {@link #registerTetheringEventCallback}.
2707 *
2708 * @param callback previously registered callback.
markchien6ae63e52020-01-21 13:11:06 +08002709 *
2710 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien4ef53e82019-02-27 14:56:11 +08002711 * @hide
2712 */
2713 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002714 @Deprecated
markchien4ef53e82019-02-27 14:56:11 +08002715 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2716 public void unregisterTetheringEventCallback(
2717 @NonNull final OnTetheringEventCallback callback) {
markchien6ae63e52020-01-21 13:11:06 +08002718 Objects.requireNonNull(callback, "The callback must be non-null");
2719 synchronized (mTetheringEventCallbacks) {
2720 final TetheringEventCallback tetherCallback =
2721 mTetheringEventCallbacks.remove(callback);
Amos Bianchia9b415a2020-03-04 11:07:38 -08002722 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien6ae63e52020-01-21 13:11:06 +08002723 }
markchien4ef53e82019-02-27 14:56:11 +08002724 }
2725
2726
2727 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002728 * Get the list of regular expressions that define any tetherable
2729 * USB network interfaces. If USB tethering is not supported by the
2730 * device, this list should be empty.
2731 *
2732 * @return an array of 0 or more regular expression Strings defining
2733 * what interfaces are considered tetherable usb interfaces.
2734 *
markchien6ae63e52020-01-21 13:11:06 +08002735 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002736 * {@hide}
2737 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002738 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002739 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002740 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002741 public String[] getTetherableUsbRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002742 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002743 }
2744
2745 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002746 * Get the list of regular expressions that define any tetherable
2747 * Wifi network interfaces. If Wifi tethering is not supported by the
2748 * device, this list should be empty.
2749 *
2750 * @return an array of 0 or more regular expression Strings defining
2751 * what interfaces are considered tetherable wifi interfaces.
2752 *
markchien6ae63e52020-01-21 13:11:06 +08002753 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002754 * {@hide}
2755 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002756 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002757 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002758 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002759 public String[] getTetherableWifiRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002760 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002761 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002762
Danica Chang96567052010-08-11 14:54:43 -07002763 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002764 * Get the list of regular expressions that define any tetherable
2765 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2766 * device, this list should be empty.
2767 *
2768 * @return an array of 0 or more regular expression Strings defining
2769 * what interfaces are considered tetherable bluetooth interfaces.
2770 *
markchien6ae63e52020-01-21 13:11:06 +08002771 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2772 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002773 * {@hide}
2774 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002775 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002776 @UnsupportedAppUsage
markchien6ae63e52020-01-21 13:11:06 +08002777 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002778 public String[] getTetherableBluetoothRegexs() {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002779 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002780 }
2781
Mike Lockwooded4a1742011-07-19 13:04:47 -07002782 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002783 * Attempt to both alter the mode of USB and Tethering of USB. A
2784 * utility method to deal with some of the complexity of USB - will
2785 * attempt to switch to Rndis and subsequently tether the resulting
2786 * interface on {@code true} or turn off tethering and switch off
2787 * Rndis on {@code false}.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09002788 *
2789 * <p>This method requires the caller to hold either the
2790 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2791 * or the ability to modify system settings as determined by
2792 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002793 *
2794 * @param enable a boolean - {@code true} to enable tethering
2795 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchien91c78e52020-01-20 19:31:56 +08002796 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002797 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002798 * {@hide}
2799 */
Mathew Inwoodc5b9bec2018-08-08 14:52:47 +01002800 @UnsupportedAppUsage
markchien91c78e52020-01-20 19:31:56 +08002801 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002802 public int setUsbTethering(boolean enable) {
Amos Bianchia9b415a2020-03-04 11:07:38 -08002803 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002804 }
2805
markchien6ae63e52020-01-21 13:11:06 +08002806 /**
2807 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2808 * {@hide}
2809 */
markchien0f45bb92019-01-16 17:44:13 +08002810 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002811 @Deprecated
2812 public static final int TETHER_ERROR_NO_ERROR = TetheringManager.TETHER_ERROR_NO_ERROR;
2813 /**
2814 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2815 * {@hide}
2816 */
2817 @Deprecated
2818 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2819 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2820 /**
2821 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2822 * {@hide}
2823 */
2824 @Deprecated
2825 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2826 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2827 /**
2828 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2829 * {@hide}
2830 */
2831 @Deprecated
2832 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2833 /**
2834 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2835 * {@hide}
2836 */
2837 @Deprecated
2838 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2839 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2840 /**
markchienf47d8342020-03-19 13:37:43 +08002841 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002842 * {@hide}
2843 */
2844 @Deprecated
markchienf47d8342020-03-19 13:37:43 +08002845 public static final int TETHER_ERROR_MASTER_ERROR =
2846 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002847 /**
2848 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2849 * {@hide}
2850 */
2851 @Deprecated
2852 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2853 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2854 /**
2855 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2856 * {@hide}
2857 */
2858 @Deprecated
2859 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2860 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2861 /**
markchienf47d8342020-03-19 13:37:43 +08002862 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002863 * {@hide}
2864 */
2865 @Deprecated
2866 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002867 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002868 /**
markchienf47d8342020-03-19 13:37:43 +08002869 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien6ae63e52020-01-21 13:11:06 +08002870 * {@hide}
2871 */
2872 @Deprecated
2873 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchienf47d8342020-03-19 13:37:43 +08002874 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien6ae63e52020-01-21 13:11:06 +08002875 /**
2876 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2877 * {@hide}
2878 */
2879 @Deprecated
2880 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2881 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2882 /**
markchienf47d8342020-03-19 13:37:43 +08002883 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien6ae63e52020-01-21 13:11:06 +08002884 * {@hide}
2885 */
markchien0f45bb92019-01-16 17:44:13 +08002886 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002887 @Deprecated
2888 public static final int TETHER_ERROR_PROVISION_FAILED =
markchienf47d8342020-03-19 13:37:43 +08002889 TetheringManager.TETHER_ERROR_PROVISIONING_FAILED;
markchien6ae63e52020-01-21 13:11:06 +08002890 /**
2891 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2892 * {@hide}
2893 */
2894 @Deprecated
2895 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2896 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2897 /**
2898 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2899 * {@hide}
2900 */
markchien0f45bb92019-01-16 17:44:13 +08002901 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002902 @Deprecated
2903 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN =
2904 TetheringManager.TETHER_ERROR_ENTITLEMENT_UNKNOWN;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002905
2906 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002907 * Get a more detailed error code after a Tethering or Untethering
2908 * request asynchronously failed.
2909 *
2910 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002911 * @return error The error code of the last error tethering or untethering the named
2912 * interface
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002913 *
markchien6ae63e52020-01-21 13:11:06 +08002914 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002915 * {@hide}
2916 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06002917 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00002918 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien6ae63e52020-01-21 13:11:06 +08002919 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002920 public int getLastTetherError(String iface) {
markchienf47d8342020-03-19 13:37:43 +08002921 int error = mTetheringManager.getLastTetherError(iface);
2922 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2923 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2924 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2925 // instead.
2926 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2927 }
2928 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002929 }
2930
markchienbf5ab012019-03-06 16:25:00 +08002931 /** @hide */
2932 @Retention(RetentionPolicy.SOURCE)
2933 @IntDef(value = {
2934 TETHER_ERROR_NO_ERROR,
2935 TETHER_ERROR_PROVISION_FAILED,
2936 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2937 })
2938 public @interface EntitlementResultCode {
2939 }
2940
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002941 /**
markchienbf5ab012019-03-06 16:25:00 +08002942 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien0f45bb92019-01-16 17:44:13 +08002943 * entitlement succeeded.
markchien6ae63e52020-01-21 13:11:06 +08002944 *
2945 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien0f45bb92019-01-16 17:44:13 +08002946 * @hide
2947 */
2948 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002949 @Deprecated
markchienbf5ab012019-03-06 16:25:00 +08002950 public interface OnTetheringEntitlementResultListener {
2951 /**
2952 * Called to notify entitlement result.
2953 *
2954 * @param resultCode an int value of entitlement result. It may be one of
2955 * {@link #TETHER_ERROR_NO_ERROR},
2956 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2957 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2958 */
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002959 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002960 }
2961
2962 /**
markchien0f45bb92019-01-16 17:44:13 +08002963 * Get the last value of the entitlement check on this downstream. If the cached value is
2964 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2965 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2966 * guaranteed that the UI-based entitlement check will complete in any specific time period
2967 * and may in fact never complete. Any successful entitlement check the platform performs for
2968 * any reason will update the cached value.
2969 *
2970 * @param type the downstream type of tethering. Must be one of
2971 * {@link #TETHERING_WIFI},
2972 * {@link #TETHERING_USB}, or
2973 * {@link #TETHERING_BLUETOOTH}.
2974 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchienbf5ab012019-03-06 16:25:00 +08002975 * @param executor the executor on which callback will be invoked.
2976 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2977 * notify the caller of the result of entitlement check. The listener may be called zero
2978 * or one time.
markchien6ae63e52020-01-21 13:11:06 +08002979 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien0f45bb92019-01-16 17:44:13 +08002980 * {@hide}
2981 */
2982 @SystemApi
markchien6ae63e52020-01-21 13:11:06 +08002983 @Deprecated
markchien0f45bb92019-01-16 17:44:13 +08002984 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchienbf5ab012019-03-06 16:25:00 +08002985 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2986 @NonNull @CallbackExecutor Executor executor,
2987 @NonNull final OnTetheringEntitlementResultListener listener) {
2988 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2989 ResultReceiver wrappedListener = new ResultReceiver(null) {
2990 @Override
2991 protected void onReceiveResult(int resultCode, Bundle resultData) {
2992 Binder.withCleanCallingIdentity(() ->
2993 executor.execute(() -> {
Jeremy Klein7e7c7422019-03-12 13:32:08 -07002994 listener.onTetheringEntitlementResult(resultCode);
markchienbf5ab012019-03-06 16:25:00 +08002995 }));
2996 }
2997 };
2998
Amos Bianchia9b415a2020-03-04 11:07:38 -08002999 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien5776f962019-12-16 20:15:20 +08003000 showEntitlementUi);
markchienbf5ab012019-03-06 16:25:00 +08003001 }
3002
3003 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003004 * Report network connectivity status. This is currently used only
3005 * to alter status bar UI.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003006 * <p>This method requires the caller to hold the permission
3007 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003008 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003009 * @param networkType The type of network you want to report on
3010 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003011 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003012 * {@hide}
3013 */
3014 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003015 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003016 try {
3017 mService.reportInetCondition(networkType, percentage);
3018 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003019 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003020 }
3021 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003022
3023 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003024 * Report a problem network to the framework. This provides a hint to the system
Ye Wenca7abab2014-07-21 14:19:01 -07003025 * that there might be connectivity problems on this network and may cause
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003026 * the framework to re-evaluate network connectivity and/or switch to another
3027 * network.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003028 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003029 * @param network The {@link Network} the application was attempting to use
3030 * or {@code null} to indicate the current default network.
Paul Jensenb95d7952015-04-07 12:43:13 -04003031 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3032 * working and non-working connectivity.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003033 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003034 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09003035 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003036 printStackTrace();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003037 try {
Paul Jensenb95d7952015-04-07 12:43:13 -04003038 // One of these will be ignored because it matches system's current state.
3039 // The other will trigger the necessary reevaluation.
3040 mService.reportNetworkConnectivity(network, true);
3041 mService.reportNetworkConnectivity(network, false);
3042 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003043 throw e.rethrowFromSystemServer();
Paul Jensenb95d7952015-04-07 12:43:13 -04003044 }
3045 }
3046
3047 /**
3048 * Report to the framework whether a network has working connectivity.
3049 * This provides a hint to the system that a particular network is providing
3050 * working connectivity or not. In response the framework may re-evaluate
3051 * the network's connectivity and might take further action thereafter.
3052 *
3053 * @param network The {@link Network} the application was attempting to use
3054 * or {@code null} to indicate the current default network.
3055 * @param hasConnectivity {@code true} if the application was able to successfully access the
3056 * Internet using {@code network} or {@code false} if not.
3057 */
Chalard Jean158702d2019-01-07 19:26:34 +09003058 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003059 printStackTrace();
Paul Jensenb95d7952015-04-07 12:43:13 -04003060 try {
3061 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003062 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003063 throw e.rethrowFromSystemServer();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003064 }
3065 }
3066
3067 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003068 * Set a network-independent global http proxy. This is not normally what you want
3069 * for typical HTTP proxies - they are general network dependent. However if you're
3070 * doing something unusual like general internal filtering this may be useful. On
3071 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen08f9dbb2015-05-06 11:10:18 -04003072 *
3073 * @param p A {@link ProxyInfo} object defining the new global
3074 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003075 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003076 */
paulhu8e96a752019-08-12 16:25:11 +08003077 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk4d5e20f2014-04-25 15:00:09 -04003078 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003079 try {
3080 mService.setGlobalProxy(p);
3081 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003082 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003083 }
3084 }
3085
3086 /**
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003087 * Retrieve any network-independent global HTTP proxy.
3088 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003089 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003090 * if no global HTTP proxy is set.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003091 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003092 */
Jason Monk4d5e20f2014-04-25 15:00:09 -04003093 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003094 try {
3095 return mService.getGlobalProxy();
3096 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003097 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003098 }
3099 }
3100
3101 /**
Paul Jensendb93dd92015-05-06 07:32:40 -04003102 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3103 * network-specific HTTP proxy. If {@code network} is null, the
3104 * network-specific proxy returned is the proxy of the default active
3105 * network.
3106 *
3107 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3108 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3109 * or when {@code network} is {@code null},
3110 * the {@code ProxyInfo} for the default active network. Returns
3111 * {@code null} when no proxy applies or the caller doesn't have
3112 * permission to use {@code network}.
3113 * @hide
3114 */
3115 public ProxyInfo getProxyForNetwork(Network network) {
3116 try {
3117 return mService.getProxyForNetwork(network);
3118 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003119 throw e.rethrowFromSystemServer();
Paul Jensendb93dd92015-05-06 07:32:40 -04003120 }
3121 }
3122
3123 /**
Paul Jensenc0618a62014-12-10 15:12:18 -05003124 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3125 * otherwise if this process is bound to a {@link Network} using
Paul Jensenee2f45d2015-03-10 10:54:12 -04003126 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensenc0618a62014-12-10 15:12:18 -05003127 * the default network's proxy is returned.
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003128 *
Jason Monk4d5e20f2014-04-25 15:00:09 -04003129 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003130 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003131 */
Chalard Jean158702d2019-01-07 19:26:34 +09003132 @Nullable
Paul Jensenc0618a62014-12-10 15:12:18 -05003133 public ProxyInfo getDefaultProxy() {
Paul Jensendb93dd92015-05-06 07:32:40 -04003134 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003135 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003136
3137 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003138 * Returns true if the hardware supports the given network type
3139 * else it returns false. This doesn't indicate we have coverage
3140 * or are authorized onto a network, just whether or not the
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003141 * hardware supports it. For example a GSM phone without a SIM
3142 * should still return {@code true} for mobile data, but a wifi only
3143 * tablet would return {@code false}.
3144 *
3145 * @param networkType The network type we'd like to check
3146 * @return {@code true} if supported, else {@code false}
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003147 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003148 * @hide
3149 */
Chalard Jean7eaf3b12018-03-08 13:54:53 +09003150 @Deprecated
Jeff Sharkey656584a2017-04-24 11:18:03 -06003151 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeana3b77512019-04-09 15:46:21 +09003152 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003153 public boolean isNetworkSupported(int networkType) {
3154 try {
3155 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003156 } catch (RemoteException e) {
3157 throw e.rethrowFromSystemServer();
3158 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003159 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003160
3161 /**
3162 * Returns if the currently active data network is metered. A network is
3163 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003164 * that connection due to monetary costs, data limitations or
3165 * battery/performance issues. You should check this before doing large
3166 * data transfers, and warn the user or delay the operation until another
3167 * network is available.
3168 *
3169 * @return {@code true} if large transfers should be avoided, otherwise
3170 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003171 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06003172 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003173 public boolean isActiveNetworkMetered() {
3174 try {
3175 return mService.isActiveNetworkMetered();
3176 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003177 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003178 }
3179 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003180
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003181 /**
3182 * If the LockdownVpn mechanism is enabled, updates the vpn
3183 * with a reload of its profile.
3184 *
3185 * @return a boolean with {@code} indicating success
3186 *
3187 * <p>This method can only be called by the system UID
3188 * {@hide}
3189 */
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003190 public boolean updateLockdownVpn() {
3191 try {
3192 return mService.updateLockdownVpn();
3193 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003194 throw e.rethrowFromSystemServer();
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003195 }
3196 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07003197
3198 /**
Sarah Chincabcbff2020-11-25 12:15:14 -08003199 * Set sign in error notification to visible or invisible
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003200 *
Sarah Chincabcbff2020-11-25 12:15:14 -08003201 * @hide
Paul Jensendda8e592015-03-18 12:23:02 -04003202 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003203 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07003204 @Deprecated
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003205 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04003206 String action) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003207 try {
Paul Jensenebeaecd2014-09-15 15:59:36 -04003208 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003209 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003210 throw e.rethrowFromSystemServer();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003211 }
3212 }
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003213
3214 /**
3215 * Set the value for enabling/disabling airplane mode
3216 *
3217 * @param enable whether to enable airplane mode or not
3218 *
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003219 * @hide
3220 */
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003221 @RequiresPermission(anyOf = {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003222 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003223 android.Manifest.permission.NETWORK_SETTINGS,
3224 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3225 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti0bfef022018-10-09 18:50:32 +09003226 @SystemApi
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003227 public void setAirplaneMode(boolean enable) {
3228 try {
3229 mService.setAirplaneMode(enable);
3230 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003231 throw e.rethrowFromSystemServer();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07003232 }
3233 }
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003234
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003235 /**
3236 * Registers the specified {@link NetworkProvider}.
3237 * Each listener must only be registered once. The listener can be unregistered with
3238 * {@link #unregisterNetworkProvider}.
3239 *
3240 * @param provider the provider to register
3241 * @return the ID of the provider. This ID must be used by the provider when registering
3242 * {@link android.net.NetworkAgent}s.
3243 * @hide
3244 */
3245 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003246 @RequiresPermission(anyOf = {
3247 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3248 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003249 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3250 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003251 throw new IllegalStateException("NetworkProviders can only be registered once");
3252 }
3253
3254 try {
3255 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3256 provider.getName());
3257 provider.setProviderId(providerId);
3258 } catch (RemoteException e) {
3259 throw e.rethrowFromSystemServer();
3260 }
3261 return provider.getProviderId();
3262 }
3263
3264 /**
3265 * Unregisters the specified NetworkProvider.
3266 *
3267 * @param provider the provider to unregister
3268 * @hide
3269 */
3270 @SystemApi
paulhub6ba8e82020-03-04 09:43:41 +08003271 @RequiresPermission(anyOf = {
3272 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3273 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003274 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3275 try {
3276 mService.unregisterNetworkProvider(provider.getMessenger());
3277 } catch (RemoteException e) {
3278 throw e.rethrowFromSystemServer();
3279 }
3280 provider.setProviderId(NetworkProvider.ID_NONE);
3281 }
3282
3283
3284 /** @hide exposed via the NetworkProvider class. */
paulhub6ba8e82020-03-04 09:43:41 +08003285 @RequiresPermission(anyOf = {
3286 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3287 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09003288 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3289 try {
3290 mService.declareNetworkRequestUnfulfillable(request);
3291 } catch (RemoteException e) {
3292 throw e.rethrowFromSystemServer();
3293 }
3294 }
3295
Chalard Jean29d06db2018-05-02 21:14:54 +09003296 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3297 // of dependent changes that would conflict throughout the automerger graph. Having this
3298 // temporarily helps with the process of going through with all these dependent changes across
3299 // the entire tree.
Paul Jensen1f567382015-02-13 14:18:39 -05003300 /**
3301 * @hide
3302 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003303 * @return Network corresponding to NetworkAgent.
Paul Jensen1f567382015-02-13 14:18:39 -05003304 */
paulhub6ba8e82020-03-04 09:43:41 +08003305 @RequiresPermission(anyOf = {
3306 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3307 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003308 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003309 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003310 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean29d06db2018-05-02 21:14:54 +09003311 }
3312
3313 /**
3314 * @hide
3315 * Register a NetworkAgent with ConnectivityService.
Chalard Jeanf78c9642019-12-13 19:47:12 +09003316 * @return Network corresponding to NetworkAgent.
Chalard Jean29d06db2018-05-02 21:14:54 +09003317 */
paulhub6ba8e82020-03-04 09:43:41 +08003318 @RequiresPermission(anyOf = {
3319 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3320 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003321 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003322 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003323 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003324 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensen1f567382015-02-13 14:18:39 -05003325 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003326 throw e.rethrowFromSystemServer();
Paul Jensen1f567382015-02-13 14:18:39 -05003327 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003328 }
3329
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003330 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003331 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3332 * changes. Should be extended by applications wanting notifications.
3333 *
3334 * A {@code NetworkCallback} is registered by calling
3335 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3336 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichicbfbb372018-02-07 21:17:43 +09003337 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003338 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3339 * A {@code NetworkCallback} should be registered at most once at any time.
3340 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003341 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003342 public static class NetworkCallback {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003343 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003344 * Called when the framework connects to a new network to evaluate whether it satisfies this
3345 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3346 * callback. There is no guarantee that this new network will satisfy any requests, or that
3347 * the network will stay connected for longer than the time necessary to evaluate it.
3348 * <p>
3349 * Most applications <b>should not</b> act on this callback, and should instead use
3350 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3351 * the framework in properly evaluating the network &mdash; for example, an application that
3352 * can automatically log in to a captive portal without user intervention.
3353 *
3354 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti3a9df1a2015-06-11 14:27:17 +09003355 *
3356 * @hide
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003357 */
paulhu1a407652019-03-22 16:35:06 +08003358 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003359
3360 /**
Lorenzo Colitti14574592015-04-24 12:23:24 +09003361 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003362 * This callback may be called more than once if the {@link Network} that is
3363 * satisfying the request changes.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003364 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003365 * @param network The {@link Network} of the satisfying network.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003366 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3367 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulaif2c67e42018-08-07 19:50:45 +08003368 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003369 * @hide
3370 */
paulhu1a407652019-03-22 16:35:06 +08003371 public void onAvailable(@NonNull Network network,
3372 @NonNull NetworkCapabilities networkCapabilities,
3373 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003374 // Internally only this method is called when a new network is available, and
3375 // it calls the callback in the same way and order that older versions used
3376 // to call so as not to change the behavior.
3377 onAvailable(network);
3378 if (!networkCapabilities.hasCapability(
3379 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3380 onNetworkSuspended(network);
3381 }
3382 onCapabilitiesChanged(network, networkCapabilities);
3383 onLinkPropertiesChanged(network, linkProperties);
junyulaif2c67e42018-08-07 19:50:45 +08003384 onBlockedStatusChanged(network, blocked);
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003385 }
3386
3387 /**
3388 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean01378b62019-08-30 16:27:28 +09003389 *
3390 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3391 * be available at the same time, and onAvailable will be called for each of these as they
3392 * appear.
3393 *
3394 * <p>For callbacks registered with {@link #requestNetwork} and
3395 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3396 * is the new best network for this request and is now tracked by this callback ; this
3397 * callback will no longer receive method calls about other networks that may have been
3398 * passed to this method previously. The previously-best network may have disconnected, or
3399 * it may still be around and the newly-best network may simply be better.
3400 *
3401 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3402 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3403 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3404 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3405 *
3406 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3407 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3408 * this callback as this is prone to race conditions (there is no guarantee the objects
3409 * returned by these methods will be current). Instead, wait for a call to
3410 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3411 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3412 * to be well-ordered with respect to other callbacks.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003413 *
3414 * @param network The {@link Network} of the satisfying network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003415 */
paulhu1a407652019-03-22 16:35:06 +08003416 public void onAvailable(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003417
3418 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003419 * Called when the network is about to be lost, typically because there are no outstanding
3420 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3421 * with the new replacement network for graceful handover. This method is not guaranteed
3422 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3423 * network is suddenly disconnected.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003424 *
Chalard Jean01378b62019-08-30 16:27:28 +09003425 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3426 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3427 * this callback as this is prone to race conditions ; calling these methods while in a
3428 * callback may return an outdated or even a null object.
3429 *
3430 * @param network The {@link Network} that is about to be lost.
3431 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3432 * connected for graceful handover; note that the network may still
3433 * suffer a hard loss at any time.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003434 */
paulhu1a407652019-03-22 16:35:06 +08003435 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003436
3437 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003438 * Called when a network disconnects or otherwise no longer satisfies this request or
3439 * callback.
3440 *
3441 * <p>If the callback was registered with requestNetwork() or
3442 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3443 * returned by onAvailable() when that network is lost and no other network satisfies
3444 * the criteria of the request.
3445 *
3446 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3447 * each network which no longer satisfies the criteria of the callback.
3448 *
3449 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3450 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3451 * this callback as this is prone to race conditions ; calling these methods while in a
3452 * callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003453 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003454 * @param network The {@link Network} lost.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003455 */
paulhu1a407652019-03-22 16:35:06 +08003456 public void onLost(@NonNull Network network) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003457
3458 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003459 * Called if no network is found within the timeout time specified in
Etan Cohenfbfdd842019-01-08 12:09:18 -08003460 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3461 * requested network request cannot be fulfilled (whether or not a timeout was
3462 * specified). When this callback is invoked the associated
Etan Cohenf67bde92017-03-01 12:47:28 -08003463 * {@link NetworkRequest} will have already been removed and released, as if
3464 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003465 */
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003466 public void onUnavailable() {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003467
3468 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003469 * Called when the network corresponding to this request changes capabilities but still
3470 * satisfies the requested criteria.
3471 *
3472 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3473 * to be called immediately after {@link #onAvailable}.
3474 *
3475 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3476 * ConnectivityManager methods in this callback as this is prone to race conditions :
3477 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003478 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003479 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003480 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3481 * network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003482 */
paulhu1a407652019-03-22 16:35:06 +08003483 public void onCapabilitiesChanged(@NonNull Network network,
3484 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003485
3486 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003487 * Called when the network corresponding to this request changes {@link LinkProperties}.
3488 *
3489 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3490 * to be called immediately after {@link #onAvailable}.
3491 *
3492 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3493 * ConnectivityManager methods in this callback as this is prone to race conditions :
3494 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003495 *
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003496 * @param network The {@link Network} whose link properties have changed.
3497 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003498 */
paulhu1a407652019-03-22 16:35:06 +08003499 public void onLinkPropertiesChanged(@NonNull Network network,
3500 @NonNull LinkProperties linkProperties) {}
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003501
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003502 /**
Chalard Jean01378b62019-08-30 16:27:28 +09003503 * Called when the network the framework connected to for this request suspends data
3504 * transmission temporarily.
3505 *
3506 * <p>This generally means that while the TCP connections are still live temporarily
3507 * network data fails to transfer. To give a specific example, this is used on cellular
3508 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3509 * means read operations on sockets on this network will block once the buffers are
3510 * drained, and write operations will block once the buffers are full.
3511 *
3512 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3513 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3514 * this callback as this is prone to race conditions (there is no guarantee the objects
3515 * returned by these methods will be current).
3516 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003517 * @hide
3518 */
paulhu1a407652019-03-22 16:35:06 +08003519 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003520
3521 /**
3522 * Called when the network the framework connected to for this request
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003523 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3524 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean01378b62019-08-30 16:27:28 +09003525
3526 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3527 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3528 * this callback as this is prone to race conditions : calling these methods while in a
3529 * callback may return an outdated or even a null object.
3530 *
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003531 * @hide
3532 */
paulhu1a407652019-03-22 16:35:06 +08003533 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003534
junyulaif2c67e42018-08-07 19:50:45 +08003535 /**
3536 * Called when access to the specified network is blocked or unblocked.
3537 *
Chalard Jean01378b62019-08-30 16:27:28 +09003538 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3539 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3540 * this callback as this is prone to race conditions : calling these methods while in a
3541 * callback may return an outdated or even a null object.
3542 *
junyulaif2c67e42018-08-07 19:50:45 +08003543 * @param network The {@link Network} whose blocked status has changed.
3544 * @param blocked The blocked status of this {@link Network}.
3545 */
junyulai7e06ad42019-03-04 22:45:36 +08003546 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulaif2c67e42018-08-07 19:50:45 +08003547
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003548 private NetworkRequest networkRequest;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003549 }
3550
Hugo Benichia590ab82017-05-11 13:16:17 +09003551 /**
3552 * Constant error codes used by ConnectivityService to communicate about failures and errors
3553 * across a Binder boundary.
3554 * @hide
3555 */
3556 public interface Errors {
Chalard Jean9dd11612018-06-04 16:52:49 +09003557 int TOO_MANY_REQUESTS = 1;
Hugo Benichia590ab82017-05-11 13:16:17 +09003558 }
3559
3560 /** @hide */
3561 public static class TooManyRequestsException extends RuntimeException {}
3562
3563 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3564 switch (e.errorCode) {
3565 case Errors.TOO_MANY_REQUESTS:
3566 return new TooManyRequestsException();
3567 default:
3568 Log.w(TAG, "Unknown service error code " + e.errorCode);
3569 return new RuntimeException(e);
3570 }
3571 }
3572
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003573 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003574 /** @hide */
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003575 public static final int CALLBACK_PRECHECK = BASE + 1;
3576 /** @hide */
3577 public static final int CALLBACK_AVAILABLE = BASE + 2;
3578 /** @hide arg1 = TTL */
3579 public static final int CALLBACK_LOSING = BASE + 3;
3580 /** @hide */
3581 public static final int CALLBACK_LOST = BASE + 4;
3582 /** @hide */
3583 public static final int CALLBACK_UNAVAIL = BASE + 5;
3584 /** @hide */
3585 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3586 /** @hide */
3587 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003588 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003589 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003590 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003591 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003592 /** @hide */
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09003593 public static final int CALLBACK_RESUMED = BASE + 10;
junyulaif2c67e42018-08-07 19:50:45 +08003594 /** @hide */
3595 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003596
Erik Kline155a59a2015-11-25 12:49:38 +09003597 /** @hide */
3598 public static String getCallbackName(int whichCallback) {
3599 switch (whichCallback) {
3600 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3601 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3602 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3603 case CALLBACK_LOST: return "CALLBACK_LOST";
3604 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3605 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3606 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003607 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3608 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3609 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulaif2c67e42018-08-07 19:50:45 +08003610 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline155a59a2015-11-25 12:49:38 +09003611 default:
3612 return Integer.toString(whichCallback);
3613 }
3614 }
3615
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003616 private class CallbackHandler extends Handler {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003617 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt72877c22015-09-03 16:41:45 -07003618 private static final boolean DBG = false;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003619
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003620 CallbackHandler(Looper looper) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003621 super(looper);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003622 }
3623
Hugo Benichifd44e912017-02-02 17:02:36 +09003624 CallbackHandler(Handler handler) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003625 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichifd44e912017-02-02 17:02:36 +09003626 }
3627
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003628 @Override
3629 public void handleMessage(Message message) {
Hugo Benichib6c24062017-05-09 14:36:02 +09003630 if (message.what == EXPIRE_LEGACY_REQUEST) {
3631 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3632 return;
3633 }
3634
3635 final NetworkRequest request = getObject(message, NetworkRequest.class);
3636 final Network network = getObject(message, Network.class);
3637 final NetworkCallback callback;
3638 synchronized (sCallbacks) {
3639 callback = sCallbacks.get(request);
Etan Cohenb58e3662019-05-21 12:06:04 -07003640 if (callback == null) {
3641 Log.w(TAG,
3642 "callback not found for " + getCallbackName(message.what) + " message");
3643 return;
3644 }
Etan Cohen6cb65992019-04-16 15:07:55 -07003645 if (message.what == CALLBACK_UNAVAIL) {
3646 sCallbacks.remove(request);
3647 callback.networkRequest = ALREADY_UNREGISTERED;
3648 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003649 }
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003650 if (DBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09003651 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittib027e6e2016-03-01 22:56:37 +09003652 }
Hugo Benichib6c24062017-05-09 14:36:02 +09003653
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003654 switch (message.what) {
3655 case CALLBACK_PRECHECK: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003656 callback.onPreCheck(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003657 break;
3658 }
3659 case CALLBACK_AVAILABLE: {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09003660 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3661 LinkProperties lp = getObject(message, LinkProperties.class);
junyulaif2c67e42018-08-07 19:50:45 +08003662 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003663 break;
3664 }
3665 case CALLBACK_LOSING: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003666 callback.onLosing(network, message.arg1);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003667 break;
3668 }
3669 case CALLBACK_LOST: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003670 callback.onLost(network);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003671 break;
3672 }
3673 case CALLBACK_UNAVAIL: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003674 callback.onUnavailable();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003675 break;
3676 }
3677 case CALLBACK_CAP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003678 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3679 callback.onCapabilitiesChanged(network, cap);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003680 break;
3681 }
3682 case CALLBACK_IP_CHANGED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003683 LinkProperties lp = getObject(message, LinkProperties.class);
3684 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003685 break;
3686 }
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003687 case CALLBACK_SUSPENDED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003688 callback.onNetworkSuspended(network);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07003689 break;
3690 }
3691 case CALLBACK_RESUMED: {
Hugo Benichib6c24062017-05-09 14:36:02 +09003692 callback.onNetworkResumed(network);
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003693 break;
3694 }
junyulaif2c67e42018-08-07 19:50:45 +08003695 case CALLBACK_BLK_CHANGED: {
3696 boolean blocked = message.arg1 != 0;
3697 callback.onBlockedStatusChanged(network, blocked);
3698 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003699 }
3700 }
3701
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003702 private <T> T getObject(Message msg, Class<T> c) {
3703 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003704 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003705 }
3706
Hugo Benichifd44e912017-02-02 17:02:36 +09003707 private CallbackHandler getDefaultHandler() {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003708 synchronized (sCallbacks) {
3709 if (sCallbackHandler == null) {
3710 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003711 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003712 return sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003713 }
3714 }
3715
Hugo Benichibc4ac972017-02-03 14:18:44 +09003716 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3717 private static CallbackHandler sCallbackHandler;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003718
Hugo Benichibc4ac972017-02-03 14:18:44 +09003719 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaiad010792021-01-11 16:53:38 +08003720 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09003721 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09003722 checkCallbackNotNull(callback);
junyulaiad010792021-01-11 16:53:38 +08003723 Preconditions.checkArgument(
3724 reqType == TRACK_DEFAULT || need != null, "null NetworkCapabilities");
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003725 final NetworkRequest request;
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003726 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003727 try {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003728 synchronized(sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09003729 if (callback.networkRequest != null
3730 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi2aa65af2017-03-06 09:17:06 +09003731 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3732 // and requests (http://b/20701525).
3733 Log.e(TAG, "NetworkCallback was already registered");
3734 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003735 Messenger messenger = new Messenger(handler);
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003736 Binder binder = new Binder();
junyulaiad010792021-01-11 16:53:38 +08003737 if (reqType == LISTEN) {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08003738 request = mService.listenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003739 need, messenger, binder, callingPackageName,
3740 getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003741 } else {
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003742 request = mService.requestNetwork(
junyulaiad010792021-01-11 16:53:38 +08003743 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3744 callingPackageName, getAttributionTag());
Paul Jensenbb427682014-06-27 11:05:32 -04003745 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003746 if (request != null) {
Hugo Benichi3b41f052016-07-07 10:15:56 +09003747 sCallbacks.put(request, callback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003748 }
Hugo Benichi3b41f052016-07-07 10:15:56 +09003749 callback.networkRequest = request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003750 }
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003751 } catch (RemoteException e) {
3752 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09003753 } catch (ServiceSpecificException e) {
3754 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07003755 }
Hugo Benichi0b42baf2016-07-06 22:53:17 +09003756 return request;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003757 }
3758
3759 /**
Erik Kline23bf99c2016-03-16 15:31:39 +09003760 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003761 *
markchienfac84a22020-03-18 21:16:15 +08003762 * This API is only for use in internal system code that requests networks with legacy type and
3763 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchiend6eeffd2020-01-14 00:55:21 +08003764 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003765 *
markchiend6eeffd2020-01-14 00:55:21 +08003766 * @param request {@link NetworkRequest} describing this request.
markchiend6eeffd2020-01-14 00:55:21 +08003767 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3768 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3769 * be a positive value (i.e. >0).
3770 * @param legacyType to specify the network type(#TYPE_*).
3771 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchienfac84a22020-03-18 21:16:15 +08003772 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3773 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003774 *
3775 * @hide
3776 */
markchiend6eeffd2020-01-14 00:55:21 +08003777 @SystemApi
markchienfac84a22020-03-18 21:16:15 +08003778 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean158702d2019-01-07 19:26:34 +09003779 public void requestNetwork(@NonNull NetworkRequest request,
markchienfac84a22020-03-18 21:16:15 +08003780 int timeoutMs, int legacyType, @NonNull Handler handler,
3781 @NonNull NetworkCallback networkCallback) {
3782 if (legacyType == TYPE_NONE) {
3783 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3784 }
Hugo Benichifd44e912017-02-02 17:02:36 +09003785 CallbackHandler cbHandler = new CallbackHandler(handler);
3786 NetworkCapabilities nc = request.networkCapabilities;
3787 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti6653c4d2015-11-25 12:00:52 +09003788 }
3789
3790 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003791 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003792 *
Chalard Jean01378b62019-08-30 16:27:28 +09003793 * <p>This method will attempt to find the best network that matches the passed
3794 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3795 * criteria. The platform will evaluate which network is the best at its own discretion.
3796 * Throughput, latency, cost per byte, policy, user preference and other considerations
3797 * may be factored in the decision of what is considered the best network.
3798 *
3799 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3800 * matching this request, while always attempting to match the request to a better network if
3801 * possible. If a better match is found, the platform will switch this request to the now-best
3802 * network and inform the app of the newly best network by invoking
3803 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3804 * will not try to maintain any other network than the best one currently matching the request:
3805 * a network not matching any network request may be disconnected at any time.
3806 *
3807 * <p>For example, an application could use this method to obtain a connected cellular network
3808 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3809 * radio to consume additional power. Or, an application could inform the system that it wants
3810 * a network supporting sending MMSes and have the system let it know about the currently best
3811 * MMS-supporting network through the provided {@link NetworkCallback}.
3812 *
3813 * <p>The status of the request can be followed by listening to the various callbacks described
3814 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3815 * used to direct traffic to the network (although accessing some networks may be subject to
3816 * holding specific permissions). Callers will learn about the specific characteristics of the
3817 * network through
3818 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3819 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3820 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3821 * matching the request at any given time; therefore when a better network matching the request
3822 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3823 * with the new network after which no further updates are given about the previously-best
3824 * network, unless it becomes the best again at some later time. All callbacks are invoked
3825 * in order on the same thread, which by default is a thread created by the framework running
3826 * in the app.
3827 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3828 * callbacks are invoked.
3829 *
3830 * <p>This{@link NetworkRequest} will live until released via
3831 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3832 * which point the system may let go of the network at any time.
3833 *
3834 * <p>A version of this method which takes a timeout is
3835 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3836 * wait for a limited amount of time for the network to become unavailable.
3837 *
Paul Jensenee52d232015-06-16 15:11:58 -04003838 * <p>It is presently unsupported to request a network with mutable
3839 * {@link NetworkCapabilities} such as
3840 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3841 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3842 * as these {@code NetworkCapabilities} represent states that a particular
3843 * network may never attain, and whether a network will attain these states
3844 * is unknown prior to bringing up the network so the framework does not
Chalard Jean01378b62019-08-30 16:27:28 +09003845 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09003846 *
3847 * <p>This method requires the caller to hold either the
3848 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3849 * or the ability to modify system settings as determined by
3850 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003851 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09003852 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3853 * number of outstanding requests to 100 per app (identified by their UID), shared with
3854 * all variants of this method, of {@link #registerNetworkCallback} as well as
3855 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3856 * Requesting a network with this method will count toward this limit. If this limit is
3857 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3858 * make sure to unregister the callbacks with
3859 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3860 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003861 * @param request {@link NetworkRequest} describing this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003862 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3863 * the callback must not be shared - it uniquely specifies this request.
3864 * The callback is invoked on the default internal Handler.
Chalard Jean31740e42019-05-13 15:13:58 +09003865 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3866 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09003867 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003868 */
Chalard Jean158702d2019-01-07 19:26:34 +09003869 public void requestNetwork(@NonNull NetworkRequest request,
3870 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003871 requestNetwork(request, networkCallback, getDefaultHandler());
3872 }
3873
3874 /**
3875 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3876 *
Chalard Jean01378b62019-08-30 16:27:28 +09003877 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3878 * but runs all the callbacks on the passed Handler.
Hugo Benichifd44e912017-02-02 17:02:36 +09003879 *
Chalard Jean01378b62019-08-30 16:27:28 +09003880 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003881 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3882 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003883 *
3884 * @param request {@link NetworkRequest} describing this request.
3885 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3886 * the callback must not be shared - it uniquely specifies this request.
3887 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichifd44e912017-02-02 17:02:36 +09003888 */
Chalard Jean158702d2019-01-07 19:26:34 +09003889 public void requestNetwork(@NonNull NetworkRequest request,
3890 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09003891 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003892 NetworkCapabilities nc = request.networkCapabilities;
3893 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003894 }
3895
3896 /**
Etan Cohenf67bde92017-03-01 12:47:28 -08003897 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3898 * by a timeout.
3899 *
3900 * This function behaves identically to the non-timed-out version
3901 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3902 * is not found within the given time (in milliseconds) the
3903 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3904 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3905 * not have to be released if timed-out (it is automatically released). Unregistering a
3906 * request that timed out is not an error.
3907 *
3908 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3909 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3910 * for that purpose. Calling this method will attempt to bring up the requested network.
3911 *
Chalard Jean01378b62019-08-30 16:27:28 +09003912 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003913 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3914 * and throws the same exceptions in the same conditions.
Etan Cohenf67bde92017-03-01 12:47:28 -08003915 *
3916 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003917 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3918 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003919 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3920 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3921 * be a positive value (i.e. >0).
Etan Cohenf67bde92017-03-01 12:47:28 -08003922 */
Chalard Jean158702d2019-01-07 19:26:34 +09003923 public void requestNetwork(@NonNull NetworkRequest request,
3924 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003925 checkTimeout(timeoutMs);
markchienfac84a22020-03-18 21:16:15 +08003926 NetworkCapabilities nc = request.networkCapabilities;
3927 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3928 getDefaultHandler());
Hugo Benichifd44e912017-02-02 17:02:36 +09003929 }
3930
Hugo Benichifd44e912017-02-02 17:02:36 +09003931 /**
3932 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3933 * by a timeout.
3934 *
Chalard Jean01378b62019-08-30 16:27:28 +09003935 * This method behaves identically to
3936 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3937 * on the passed Handler.
Etan Cohenf67bde92017-03-01 12:47:28 -08003938 *
Chalard Jean01378b62019-08-30 16:27:28 +09003939 * <p>This method has the same permission requirements as
Chalard Jeana5ff1132020-05-20 16:11:50 +09003940 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3941 * and throws the same exceptions in the same conditions.
Hugo Benichifd44e912017-02-02 17:02:36 +09003942 *
3943 * @param request {@link NetworkRequest} describing this request.
Etan Cohenf67bde92017-03-01 12:47:28 -08003944 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3945 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichifd44e912017-02-02 17:02:36 +09003946 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09003947 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3948 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09003949 */
Chalard Jean158702d2019-01-07 19:26:34 +09003950 public void requestNetwork(@NonNull NetworkRequest request,
3951 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichibc1104b2017-05-09 15:19:01 +09003952 checkTimeout(timeoutMs);
Hugo Benichifd44e912017-02-02 17:02:36 +09003953 CallbackHandler cbHandler = new CallbackHandler(handler);
markchienfac84a22020-03-18 21:16:15 +08003954 NetworkCapabilities nc = request.networkCapabilities;
3955 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003956 }
3957
3958 /**
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003959 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003960 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003961 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinc5302632015-02-11 16:51:13 -08003962 * <p>
Paul Jensenee2f45d2015-03-10 10:54:12 -04003963 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3964 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003965 */
Erik Kline8a826212014-11-19 12:12:24 +09003966 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003967
3968 /**
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003969 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003970 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003971 * {@link android.content.Intent#getParcelableExtra(String)}.
3972 */
Erik Kline8a826212014-11-19 12:12:24 +09003973 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003974
3975
3976 /**
Lorenzo Colitti21e9a152015-04-23 15:32:42 +09003977 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003978 *
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003979 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003980 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003981 * the request may outlive the calling application and get called back when a suitable
3982 * network is found.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003983 * <p>
3984 * The operation is an Intent broadcast that goes to a broadcast receiver that
3985 * you registered with {@link Context#registerReceiver} or through the
3986 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3987 * <p>
3988 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline8a826212014-11-19 12:12:24 +09003989 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3990 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003991 * the original requests parameters. It is important to create a new,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07003992 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003993 * Intent to reserve the network or it will be released shortly after the Intent
3994 * is processed.
3995 * <p>
Paul Jensenc8873fc2015-06-17 14:15:39 -04003996 * If there is already a request for this Intent registered (with the equality of
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003997 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltf3017f72014-05-18 23:07:25 -07003998 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003999 * <p>
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004000 * The request may be released normally by calling
4001 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenee52d232015-06-16 15:11:58 -04004002 * <p>It is presently unsupported to request a network with either
4003 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4004 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4005 * as these {@code NetworkCapabilities} represent states that a particular
4006 * network may never attain, and whether a network will attain these states
4007 * is unknown prior to bringing up the network so the framework does not
Chalard Jean9dd11612018-06-04 16:52:49 +09004008 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004009 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004010 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4011 * number of outstanding requests to 100 per app (identified by their UID), shared with
4012 * all variants of this method, of {@link #registerNetworkCallback} as well as
4013 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4014 * Requesting a network with this method will count toward this limit. If this limit is
4015 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4016 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4017 * or {@link #releaseNetworkRequest(PendingIntent)}.
4018 *
Lorenzo Colitti0b40c872015-10-15 16:29:00 +09004019 * <p>This method requires the caller to hold either the
4020 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4021 * or the ability to modify system settings as determined by
4022 * {@link android.provider.Settings.System#canWrite}.</p>
4023 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004024 * @param request {@link NetworkRequest} describing this request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004025 * @param operation Action to perform when the network is available (corresponds
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004026 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004027 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean31740e42019-05-13 15:13:58 +09004028 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4029 * @throws SecurityException if missing the appropriate permissions.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004030 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004031 */
Chalard Jean158702d2019-01-07 19:26:34 +09004032 public void requestNetwork(@NonNull NetworkRequest request,
4033 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004034 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004035 checkPendingIntentNotNull(operation);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004036 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004037 mService.pendingRequestForNetwork(
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004038 request.networkCapabilities, operation, mContext.getOpPackageName(),
4039 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004040 } catch (RemoteException e) {
4041 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004042 } catch (ServiceSpecificException e) {
4043 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004044 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004045 }
4046
4047 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004048 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4049 * <p>
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004050 * This method has the same behavior as
4051 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004052 * releasing network resources and disconnecting.
4053 *
4054 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4055 * PendingIntent passed to
4056 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4057 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4058 */
Chalard Jean158702d2019-01-07 19:26:34 +09004059 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004060 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004061 checkPendingIntentNotNull(operation);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004062 try {
4063 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004064 } catch (RemoteException e) {
4065 throw e.rethrowFromSystemServer();
4066 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004067 }
4068
Hugo Benichibc1104b2017-05-09 15:19:01 +09004069 private static void checkPendingIntentNotNull(PendingIntent intent) {
4070 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4071 }
4072
4073 private static void checkCallbackNotNull(NetworkCallback callback) {
4074 Preconditions.checkNotNull(callback, "null NetworkCallback");
4075 }
4076
4077 private static void checkTimeout(int timeoutMs) {
4078 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004079 }
4080
4081 /**
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004082 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004083 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004084 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4085 * called.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004086 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004087 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4088 * number of outstanding requests to 100 per app (identified by their UID), shared with
4089 * all variants of this method, of {@link #requestNetwork} as well as
4090 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4091 * Requesting a network with this method will count toward this limit. If this limit is
4092 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4093 * make sure to unregister the callbacks with
4094 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4095 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004096 * @param request {@link NetworkRequest} describing this request.
4097 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4098 * networks change state.
Hugo Benichifd44e912017-02-02 17:02:36 +09004099 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004100 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004101 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004102 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004103 public void registerNetworkCallback(@NonNull NetworkRequest request,
4104 @NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004105 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4106 }
4107
4108 /**
4109 * Registers to receive notifications about all networks which satisfy the given
4110 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang3b723c22019-02-27 17:14:50 +08004111 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4112 * called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004113 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004114 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4115 * number of outstanding requests to 100 per app (identified by their UID), shared with
4116 * all variants of this method, of {@link #requestNetwork} as well as
4117 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4118 * Requesting a network with this method will count toward this limit. If this limit is
4119 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4120 * make sure to unregister the callbacks with
4121 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4122 *
4123 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004124 * @param request {@link NetworkRequest} describing this request.
4125 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4126 * networks change state.
4127 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004128 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004129 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004130 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004131 public void registerNetworkCallback(@NonNull NetworkRequest request,
4132 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004133 CallbackHandler cbHandler = new CallbackHandler(handler);
4134 NetworkCapabilities nc = request.networkCapabilities;
4135 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004136 }
4137
4138 /**
Paul Jensenc8873fc2015-06-17 14:15:39 -04004139 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4140 * {@link NetworkRequest}.
4141 *
4142 * This function behaves identically to the version that takes a NetworkCallback, but instead
4143 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4144 * the request may outlive the calling application and get called back when a suitable
4145 * network is found.
4146 * <p>
4147 * The operation is an Intent broadcast that goes to a broadcast receiver that
4148 * you registered with {@link Context#registerReceiver} or through the
4149 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4150 * <p>
4151 * The operation Intent is delivered with two extras, a {@link Network} typed
4152 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4153 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4154 * the original requests parameters.
4155 * <p>
4156 * If there is already a request for this Intent registered (with the equality of
4157 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4158 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4159 * <p>
4160 * The request may be released normally by calling
Paul Jensen169f6622015-06-30 14:29:18 -04004161 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004162 *
4163 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4164 * number of outstanding requests to 100 per app (identified by their UID), shared with
4165 * all variants of this method, of {@link #requestNetwork} as well as
4166 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4167 * Requesting a network with this method will count toward this limit. If this limit is
4168 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4169 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4170 * or {@link #releaseNetworkRequest(PendingIntent)}.
4171 *
Paul Jensenc8873fc2015-06-17 14:15:39 -04004172 * @param request {@link NetworkRequest} describing this request.
4173 * @param operation Action to perform when the network is available (corresponds
4174 * to the {@link NetworkCallback#onAvailable} call. Typically
4175 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004176 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensenc8873fc2015-06-17 14:15:39 -04004177 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004178 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004179 public void registerNetworkCallback(@NonNull NetworkRequest request,
4180 @NonNull PendingIntent operation) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004181 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004182 checkPendingIntentNotNull(operation);
Paul Jensenc8873fc2015-06-17 14:15:39 -04004183 try {
Roshan Piusbc7e37d2020-01-16 12:17:17 -08004184 mService.pendingListenForNetwork(
Roshan Piusaa24fde2020-12-17 14:53:09 -08004185 request.networkCapabilities, operation, mContext.getOpPackageName(),
4186 getAttributionTag());
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004187 } catch (RemoteException e) {
4188 throw e.rethrowFromSystemServer();
Hugo Benichia590ab82017-05-11 13:16:17 +09004189 } catch (ServiceSpecificException e) {
4190 throw convertServiceException(e);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004191 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004192 }
4193
4194 /**
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004195 * Registers to receive notifications about changes in the system default network. The callbacks
4196 * will continue to be called until either the application exits or
4197 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Kline23bf99c2016-03-16 15:31:39 +09004198 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004199 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4200 * number of outstanding requests to 100 per app (identified by their UID), shared with
4201 * all variants of this method, of {@link #requestNetwork} as well as
4202 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4203 * Requesting a network with this method will count toward this limit. If this limit is
4204 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4205 * make sure to unregister the callbacks with
4206 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4207 *
Erik Kline23bf99c2016-03-16 15:31:39 +09004208 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4209 * system default network changes.
Hugo Benichifd44e912017-02-02 17:02:36 +09004210 * The callback is invoked on the default internal Handler.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004211 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Kline23bf99c2016-03-16 15:31:39 +09004212 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004213 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004214 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichifd44e912017-02-02 17:02:36 +09004215 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4216 }
4217
4218 /**
4219 * Registers to receive notifications about changes in the system default network. The callbacks
4220 * will continue to be called until either the application exits or
4221 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichifd44e912017-02-02 17:02:36 +09004222 *
Chalard Jeana5ff1132020-05-20 16:11:50 +09004223 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4224 * number of outstanding requests to 100 per app (identified by their UID), shared with
4225 * all variants of this method, of {@link #requestNetwork} as well as
4226 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4227 * Requesting a network with this method will count toward this limit. If this limit is
4228 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4229 * make sure to unregister the callbacks with
4230 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4231 *
Hugo Benichifd44e912017-02-02 17:02:36 +09004232 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4233 * system default network changes.
4234 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jeana5ff1132020-05-20 16:11:50 +09004235 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichifd44e912017-02-02 17:02:36 +09004236 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004237 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004238 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4239 @NonNull Handler handler) {
Erik Kline23bf99c2016-03-16 15:31:39 +09004240 // This works because if the NetworkCapabilities are null,
4241 // ConnectivityService takes them from the default request.
4242 //
4243 // Since the capabilities are exactly the same as the default request's
4244 // capabilities, this request is guaranteed, at all times, to be
4245 // satisfied by the same network, if any, that satisfies the default
4246 // request, i.e., the system default network.
Hugo Benichifd44e912017-02-02 17:02:36 +09004247 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean9dd11612018-06-04 16:52:49 +09004248 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
junyulaiad010792021-01-11 16:53:38 +08004249 TRACK_DEFAULT, TYPE_NONE, cbHandler);
Erik Kline23bf99c2016-03-16 15:31:39 +09004250 }
4251
4252 /**
fenglub00f4882015-04-21 17:12:05 -07004253 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4254 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4255 * network connection for updated bandwidth information. The caller will be notified via
4256 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004257 * method assumes that the caller has previously called
4258 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4259 * changes.
fenglu3f357402015-03-20 11:29:56 -07004260 *
fengluea2d9282015-04-27 14:28:04 -07004261 * @param network {@link Network} specifying which network you're interested.
fenglub00f4882015-04-21 17:12:05 -07004262 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu3f357402015-03-20 11:29:56 -07004263 */
Chalard Jean158702d2019-01-07 19:26:34 +09004264 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu3f357402015-03-20 11:29:56 -07004265 try {
fenglub00f4882015-04-21 17:12:05 -07004266 return mService.requestBandwidthUpdate(network);
fenglu3f357402015-03-20 11:29:56 -07004267 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004268 throw e.rethrowFromSystemServer();
fenglu3f357402015-03-20 11:29:56 -07004269 }
4270 }
4271
4272 /**
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004273 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti15874cd2016-04-13 22:00:02 +09004274 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4275 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4276 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti7f6a2bf2015-04-24 17:03:31 +09004277 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4278 * will be disconnected.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004279 *
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004280 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4281 * triggering it as soon as this call returns.
4282 *
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07004283 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004284 */
Chalard Jean158702d2019-01-07 19:26:34 +09004285 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004286 printStackTrace();
Hugo Benichibc1104b2017-05-09 15:19:01 +09004287 checkCallbackNotNull(networkCallback);
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004288 final List<NetworkRequest> reqs = new ArrayList<>();
4289 // Find all requests associated to this callback and stop callback triggers immediately.
4290 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4291 synchronized (sCallbacks) {
Hugo Benichibee30fe2017-06-17 13:14:12 +09004292 Preconditions.checkArgument(networkCallback.networkRequest != null,
4293 "NetworkCallback was not registered");
Etan Cohen6cb65992019-04-16 15:07:55 -07004294 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4295 Log.d(TAG, "NetworkCallback was already unregistered");
4296 return;
4297 }
Hugo Benichi2aa65af2017-03-06 09:17:06 +09004298 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4299 if (e.getValue() == networkCallback) {
4300 reqs.add(e.getKey());
4301 }
4302 }
4303 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4304 for (NetworkRequest r : reqs) {
4305 try {
4306 mService.releaseNetworkRequest(r);
4307 } catch (RemoteException e) {
4308 throw e.rethrowFromSystemServer();
4309 }
4310 // Only remove mapping if rpc was successful.
4311 sCallbacks.remove(r);
4312 }
Hugo Benichibee30fe2017-06-17 13:14:12 +09004313 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004314 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004315 }
Paul Jensen8cdda642014-05-29 10:12:39 -04004316
4317 /**
Paul Jensen169f6622015-06-30 14:29:18 -04004318 * Unregisters a callback previously registered via
4319 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4320 *
4321 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4322 * PendingIntent passed to
4323 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4324 * Cannot be null.
4325 */
Chalard Jean158702d2019-01-07 19:26:34 +09004326 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen169f6622015-06-30 14:29:18 -04004327 releaseNetworkRequest(operation);
4328 }
4329
4330 /**
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004331 * Informs the system whether it should switch to {@code network} regardless of whether it is
4332 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4333 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4334 * the system default network regardless of any other network that's currently connected. If
4335 * {@code always} is true, then the choice is remembered, so that the next time the user
4336 * connects to this network, the system will switch to it.
4337 *
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004338 * @param network The network to accept.
4339 * @param accept Whether to accept the network even if unvalidated.
4340 * @param always Whether to remember this choice in the future.
4341 *
4342 * @hide
4343 */
lucaslin2240ef62019-03-12 13:08:03 +08004344 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004345 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4346 try {
4347 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004348 } catch (RemoteException e) {
4349 throw e.rethrowFromSystemServer();
4350 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004351 }
4352
4353 /**
lucaslin2240ef62019-03-12 13:08:03 +08004354 * Informs the system whether it should consider the network as validated even if it only has
4355 * partial connectivity. If {@code accept} is true, then the network will be considered as
4356 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4357 * is remembered, so that the next time the user connects to this network, the system will
4358 * switch to it.
4359 *
4360 * @param network The network to accept.
4361 * @param accept Whether to consider the network as validated even if it has partial
4362 * connectivity.
4363 * @param always Whether to remember this choice in the future.
4364 *
4365 * @hide
4366 */
4367 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4368 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4369 try {
4370 mService.setAcceptPartialConnectivity(network, accept, always);
4371 } catch (RemoteException e) {
4372 throw e.rethrowFromSystemServer();
4373 }
4374 }
4375
4376 /**
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004377 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4378 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4379 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4380 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4381 *
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004382 * @param network The network to accept.
4383 *
4384 * @hide
4385 */
lucaslin2240ef62019-03-12 13:08:03 +08004386 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004387 public void setAvoidUnvalidated(Network network) {
4388 try {
4389 mService.setAvoidUnvalidated(network);
4390 } catch (RemoteException e) {
4391 throw e.rethrowFromSystemServer();
4392 }
4393 }
4394
4395 /**
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004396 * Requests that the system open the captive portal app on the specified network.
4397 *
4398 * @param network The network to log into.
4399 *
4400 * @hide
4401 */
paulhu8e96a752019-08-12 16:25:11 +08004402 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004403 public void startCaptivePortalApp(Network network) {
4404 try {
4405 mService.startCaptivePortalApp(network);
4406 } catch (RemoteException e) {
4407 throw e.rethrowFromSystemServer();
4408 }
4409 }
4410
4411 /**
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004412 * Requests that the system open the captive portal app with the specified extras.
4413 *
4414 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4415 * corresponding permission.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004416 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004417 * @param appExtras Extras to include in the app start intent.
4418 * @hide
4419 */
4420 @SystemApi
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004421 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhucbbc3db2019-03-08 16:35:20 +08004422 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004423 try {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004424 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004425 } catch (RemoteException e) {
4426 throw e.rethrowFromSystemServer();
4427 }
4428 }
4429
4430 /**
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004431 * Determine whether the device is configured to avoid bad wifi.
4432 * @hide
4433 */
4434 @SystemApi
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004435 @RequiresPermission(anyOf = {
4436 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4437 android.Manifest.permission.NETWORK_STACK})
4438 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004439 try {
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004440 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004441 } catch (RemoteException e) {
4442 throw e.rethrowFromSystemServer();
4443 }
4444 }
4445
4446 /**
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004447 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4448 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti139a48c2017-04-28 00:56:30 +09004449 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4450 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004451 *
4452 * An example of such an operation might be a time-sensitive foreground activity, such as a
4453 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4454 */
4455 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4456
4457 /**
4458 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4459 * a backup channel for traffic that is primarily going over another network.
4460 *
4461 * An example might be maintaining backup connections to peers or servers for the purpose of
4462 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4463 * on backup paths should be negligible compared to the traffic on the main path.
4464 */
4465 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4466
4467 /**
4468 * It is acceptable to use metered data to improve network latency and performance.
4469 */
4470 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4471
4472 /**
4473 * Return value to use for unmetered networks. On such networks we currently set all the flags
4474 * to true.
4475 * @hide
4476 */
4477 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4478 MULTIPATH_PREFERENCE_HANDOVER |
4479 MULTIPATH_PREFERENCE_RELIABILITY |
4480 MULTIPATH_PREFERENCE_PERFORMANCE;
4481
4482 /** @hide */
4483 @Retention(RetentionPolicy.SOURCE)
4484 @IntDef(flag = true, value = {
4485 MULTIPATH_PREFERENCE_HANDOVER,
4486 MULTIPATH_PREFERENCE_RELIABILITY,
4487 MULTIPATH_PREFERENCE_PERFORMANCE,
4488 })
4489 public @interface MultipathPreference {
4490 }
4491
4492 /**
4493 * Provides a hint to the calling application on whether it is desirable to use the
4494 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4495 * for multipath data transfer on this network when it is not the system default network.
4496 * Applications desiring to use multipath network protocols should call this method before
4497 * each such operation.
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004498 *
4499 * @param network The network on which the application desires to use multipath data.
4500 * If {@code null}, this method will return the a preference that will generally
4501 * apply to metered networks.
4502 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4503 */
Jeff Sharkey656584a2017-04-24 11:18:03 -06004504 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean158702d2019-01-07 19:26:34 +09004505 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004506 try {
4507 return mService.getMultipathPreference(network);
4508 } catch (RemoteException e) {
4509 throw e.rethrowFromSystemServer();
4510 }
4511 }
4512
4513 /**
Stuart Scott0f835ac2015-03-30 13:17:11 -07004514 * Resets all connectivity manager settings back to factory defaults.
4515 * @hide
4516 */
paulhu8e96a752019-08-12 16:25:11 +08004517 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott0f835ac2015-03-30 13:17:11 -07004518 public void factoryReset() {
Stuart Scott0f835ac2015-03-30 13:17:11 -07004519 try {
Stuart Scottd5463642015-04-02 18:00:02 -07004520 mService.factoryReset();
Amos Bianchia9b415a2020-03-04 11:07:38 -08004521 mTetheringManager.stopAllTethering();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004522 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004523 throw e.rethrowFromSystemServer();
Stuart Scott0f835ac2015-03-30 13:17:11 -07004524 }
4525 }
4526
4527 /**
Paul Jensen8cdda642014-05-29 10:12:39 -04004528 * Binds the current process to {@code network}. All Sockets created in the future
4529 * (and not explicitly bound via a bound SocketFactory from
4530 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4531 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4532 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4533 * work and all host name resolutions will fail. This is by design so an application doesn't
4534 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4535 * To clear binding pass {@code null} for {@code network}. Using individually bound
4536 * Sockets created by Network.getSocketFactory().createSocket() and
4537 * performing network-specific host name resolutions via
4538 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensenee2f45d2015-03-10 10:54:12 -04004539 * {@code bindProcessToNetwork}.
Paul Jensen8cdda642014-05-29 10:12:39 -04004540 *
4541 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4542 * the current binding.
4543 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4544 */
Chalard Jean158702d2019-01-07 19:26:34 +09004545 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean9dd11612018-06-04 16:52:49 +09004546 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensenee2f45d2015-03-10 10:54:12 -04004547 // instantiated.
4548 return setProcessDefaultNetwork(network);
4549 }
4550
4551 /**
4552 * Binds the current process to {@code network}. All Sockets created in the future
4553 * (and not explicitly bound via a bound SocketFactory from
4554 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4555 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4556 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4557 * work and all host name resolutions will fail. This is by design so an application doesn't
4558 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4559 * To clear binding pass {@code null} for {@code network}. Using individually bound
4560 * Sockets created by Network.getSocketFactory().createSocket() and
4561 * performing network-specific host name resolutions via
4562 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4563 * {@code setProcessDefaultNetwork}.
4564 *
4565 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4566 * the current binding.
4567 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4568 * @deprecated This function can throw {@link IllegalStateException}. Use
4569 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4570 * is a direct replacement.
4571 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004572 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004573 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen3e2917c2014-08-27 12:38:45 -04004574 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004575 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4576
Lorenzo Colitti3a1cb9d2019-01-30 23:04:54 +09004577 if (netId != NETID_UNSET) {
4578 netId = network.getNetIdForResolv();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004579 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004580
4581 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4582 return false;
4583 }
4584
4585 if (!isSameNetId) {
Paul Jensenc0618a62014-12-10 15:12:18 -05004586 // Set HTTP proxy system properties to match network.
4587 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti41b1fbc2015-04-22 11:52:48 +09004588 try {
4589 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4590 } catch (SecurityException e) {
4591 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4592 Log.e(TAG, "Can't set proxy properties", e);
4593 }
Paul Jensen3e2917c2014-08-27 12:38:45 -04004594 // Must flush DNS cache as new network may have different DNS resolutions.
4595 InetAddress.clearDnsCache();
4596 // Must flush socket pool as idle sockets will be bound to previous network and may
4597 // cause subsequent fetches to be performed on old network.
4598 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen3e2917c2014-08-27 12:38:45 -04004599 }
Lorenzo Colitti3c766eb2019-01-31 13:08:24 +09004600
4601 return true;
Paul Jensen8cdda642014-05-29 10:12:39 -04004602 }
4603
4604 /**
4605 * Returns the {@link Network} currently bound to this process via
Paul Jensenee2f45d2015-03-10 10:54:12 -04004606 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen8cdda642014-05-29 10:12:39 -04004607 *
4608 * @return {@code Network} to which this process is bound, or {@code null}.
4609 */
Chalard Jean158702d2019-01-07 19:26:34 +09004610 @Nullable
Paul Jensenee2f45d2015-03-10 10:54:12 -04004611 public Network getBoundNetworkForProcess() {
4612 // Forcing callers to call thru non-static function ensures ConnectivityManager
4613 // instantiated.
4614 return getProcessDefaultNetwork();
4615 }
4616
4617 /**
4618 * Returns the {@link Network} currently bound to this process via
4619 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4620 *
4621 * @return {@code Network} to which this process is bound, or {@code null}.
4622 * @deprecated Using this function can lead to other functions throwing
4623 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4624 * {@code getBoundNetworkForProcess} is a direct replacement.
4625 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004626 @Deprecated
Chalard Jean158702d2019-01-07 19:26:34 +09004627 @Nullable
Paul Jensen8cdda642014-05-29 10:12:39 -04004628 public static Network getProcessDefaultNetwork() {
Paul Jensenee2f45d2015-03-10 10:54:12 -04004629 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen65743a22014-07-11 08:17:29 -04004630 if (netId == NETID_UNSET) return null;
Paul Jensen8cdda642014-05-29 10:12:39 -04004631 return new Network(netId);
4632 }
4633
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004634 private void unsupportedStartingFrom(int version) {
4635 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09004636 // The getApplicationInfo() call we make below is not supported in system context. Let
4637 // the call through here, and rely on the fact that ConnectivityService will refuse to
4638 // allow the system to use these APIs anyway.
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004639 return;
4640 }
4641
4642 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4643 throw new UnsupportedOperationException(
4644 "This method is not supported in target SDK version " + version + " and above");
4645 }
4646 }
4647
4648 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4649 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang0a922fd2016-01-07 23:20:38 -08004650 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004651 // remove these exemptions. Note that this check is not secure, and apps can still access these
4652 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4653 // so is unsupported and may break in the future. http://b/22728205
4654 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn18c1d832015-07-31 10:35:34 -07004655 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti2780e4b2015-07-29 11:41:21 +09004656 }
4657
Paul Jensen8cdda642014-05-29 10:12:39 -04004658 /**
4659 * Binds host resolutions performed by this process to {@code network}.
Paul Jensenee2f45d2015-03-10 10:54:12 -04004660 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen8cdda642014-05-29 10:12:39 -04004661 *
4662 * @param network The {@link Network} to bind host resolutions from the current process to, or
4663 * {@code null} to clear the current binding.
4664 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4665 * @hide
4666 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4667 */
Aurimas Liutikase80a0eb2016-05-24 15:22:55 -07004668 @Deprecated
Mathew Inwoode1a17ba2020-11-04 09:29:36 +00004669 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen8cdda642014-05-29 10:12:39 -04004670 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen65743a22014-07-11 08:17:29 -04004671 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Kline767b7f22018-04-27 22:48:33 +09004672 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen8cdda642014-05-29 10:12:39 -04004673 }
Felipe Leme30511352016-01-22 09:44:57 -08004674
4675 /**
4676 * Device is not restricting metered network activity while application is running on
4677 * background.
4678 */
4679 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4680
4681 /**
4682 * Device is restricting metered network activity while application is running on background,
4683 * but application is allowed to bypass it.
4684 * <p>
4685 * In this state, application should take action to mitigate metered network access.
4686 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4687 */
4688 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4689
4690 /**
4691 * Device is restricting metered network activity while application is running on background.
Felipe Lemed34c9af2016-01-27 14:46:39 -08004692 * <p>
Felipe Leme30511352016-01-22 09:44:57 -08004693 * In this state, application should not try to use the network while running on background,
4694 * because it would be denied.
4695 */
4696 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4697
Felipe Lemed34c9af2016-01-27 14:46:39 -08004698 /**
4699 * A change in the background metered network activity restriction has occurred.
4700 * <p>
4701 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4702 * applies to them.
4703 * <p>
4704 * This is only sent to registered receivers, not manifest receivers.
4705 */
4706 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4707 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4708 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4709
Felipe Leme7e4c1852016-01-25 11:48:04 -08004710 /** @hide */
4711 @Retention(RetentionPolicy.SOURCE)
Felipe Leme30511352016-01-22 09:44:57 -08004712 @IntDef(flag = false, value = {
4713 RESTRICT_BACKGROUND_STATUS_DISABLED,
4714 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4715 RESTRICT_BACKGROUND_STATUS_ENABLED,
4716 })
Felipe Leme30511352016-01-22 09:44:57 -08004717 public @interface RestrictBackgroundStatus {
4718 }
4719
4720 private INetworkPolicyManager getNetworkPolicyManager() {
4721 synchronized (this) {
4722 if (mNPManager != null) {
4723 return mNPManager;
4724 }
4725 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4726 .getService(Context.NETWORK_POLICY_SERVICE));
4727 return mNPManager;
4728 }
4729 }
4730
4731 /**
4732 * Determines if the calling application is subject to metered network restrictions while
4733 * running on background.
Felipe Leme3edc6162016-05-16 13:57:19 -07004734 *
4735 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4736 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4737 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme30511352016-01-22 09:44:57 -08004738 */
4739 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4740 try {
4741 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4742 } catch (RemoteException e) {
Jeff Sharkeyc78f85c2016-03-01 19:27:23 -07004743 throw e.rethrowFromSystemServer();
Felipe Leme30511352016-01-22 09:44:57 -08004744 }
4745 }
Ricky Wai7097cc92018-01-23 04:09:45 +00004746
4747 /**
4748 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai04baf112018-03-20 14:20:54 +00004749 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4750 * currently used by the system for validation purposes.
Ricky Wai7097cc92018-01-23 04:09:45 +00004751 *
4752 * @return Hash of network watchlist config file. Null if config does not exist.
4753 */
Chalard Jean158702d2019-01-07 19:26:34 +09004754 @Nullable
Ricky Wai7097cc92018-01-23 04:09:45 +00004755 public byte[] getNetworkWatchlistConfigHash() {
4756 try {
4757 return mService.getNetworkWatchlistConfigHash();
4758 } catch (RemoteException e) {
4759 Log.e(TAG, "Unable to get watchlist config hash");
4760 throw e.rethrowFromSystemServer();
4761 }
4762 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004763
4764 /**
4765 * Returns the {@code uid} of the owner of a network connection.
4766 *
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004767 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4768 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004769 * @param local The local {@link InetSocketAddress} of a connection.
4770 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004771 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004772 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4773 * android.os.Process#INVALID_UID} if the connection is not found.
4774 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4775 * user.
4776 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004777 */
Benedict Wong0bd4bba2020-01-20 22:14:59 -08004778 public int getConnectionOwnerUid(
4779 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004780 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4781 try {
4782 return mService.getConnectionOwnerUid(connectionInfo);
4783 } catch (RemoteException e) {
4784 throw e.rethrowFromSystemServer();
4785 }
4786 }
Soi, Yoshinarib8102ef2015-11-12 12:09:02 +09004787
4788 private void printStackTrace() {
4789 if (DEBUG) {
4790 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4791 final StringBuffer sb = new StringBuffer();
4792 for (int i = 3; i < callStack.length; i++) {
4793 final String stackTrace = callStack[i].toString();
4794 if (stackTrace == null || stackTrace.contains("android.os")) {
4795 break;
4796 }
4797 sb.append(" [").append(stackTrace).append("]");
4798 }
4799 Log.d(TAG, "StackLog:" + sb.toString());
4800 }
4801 }
Cody Kestingf53a0752020-04-15 12:33:28 -07004802
Remi NGUYEN VAN5f406422021-01-15 23:02:47 +09004803 /** @hide */
4804 public TestNetworkManager startOrGetTestNetworkManager() {
4805 final IBinder tnBinder;
4806 try {
4807 tnBinder = mService.startOrGetTestNetworkService();
4808 } catch (RemoteException e) {
4809 throw e.rethrowFromSystemServer();
4810 }
4811
4812 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4813 }
4814
4815 /** @hide */
4816 public VpnManager createVpnManager() {
4817 return new VpnManager(mContext, mService);
4818 }
4819
4820 /** @hide */
4821 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4822 return new ConnectivityDiagnosticsManager(mContext, mService);
4823 }
4824
Cody Kestingf53a0752020-04-15 12:33:28 -07004825 /**
4826 * Simulates a Data Stall for the specified Network.
4827 *
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004828 * <p>This method should only be used for tests.
4829 *
Cody Kestingf53a0752020-04-15 12:33:28 -07004830 * <p>The caller must be the owner of the specified Network.
4831 *
4832 * @param detectionMethod The detection method used to identify the Data Stall.
4833 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4834 * @param network The Network for which a Data Stall is being simluated.
4835 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4836 * @throws SecurityException if the caller is not the owner of the given network.
4837 * @hide
4838 */
Remi NGUYEN VAN761c7ad2021-01-12 18:40:04 +09004839 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingf53a0752020-04-15 12:33:28 -07004840 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4841 android.Manifest.permission.NETWORK_STACK})
4842 public void simulateDataStall(int detectionMethod, long timestampMillis,
4843 @NonNull Network network, @NonNull PersistableBundle extras) {
4844 try {
4845 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4846 } catch (RemoteException e) {
4847 e.rethrowFromSystemServer();
4848 }
4849 }
James Mattis356a8792020-10-28 21:48:54 -07004850
James Mattis47db0582021-01-01 14:13:35 -08004851 private void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
4852 try {
4853 mService.setOemNetworkPreference(preference);
4854 } catch (RemoteException e) {
4855 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
4856 throw e.rethrowFromSystemServer();
4857 }
James Mattis356a8792020-10-28 21:48:54 -07004858 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004859
4860 @NonNull
4861 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4862
4863 /**
4864 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4865 * receive available QoS events related to the {@link Network} and local ip + port
4866 * specified within socketInfo.
4867 * <p/>
4868 * The same {@link QosCallback} must be unregistered before being registered a second time,
4869 * otherwise {@link QosCallbackRegistrationException} is thrown.
4870 * <p/>
4871 * This API does not, in itself, require any permission if called with a network that is not
4872 * restricted. However, the underlying implementation currently only supports the IMS network,
4873 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4874 * useful, because they'd never be called back on networks that they would have access to.
4875 *
4876 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4877 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4878 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4879 * @throws RuntimeException if the app already has too many callbacks registered.
4880 *
4881 * Exceptions after the time of registration is passed through
4882 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4883 *
4884 * @param socketInfo the socket information used to match QoS events
4885 * @param callback receives qos events that satisfy socketInfo
4886 * @param executor The executor on which the callback will be invoked. The provided
4887 * {@link Executor} must run callback sequentially, otherwise the order of
4888 * callbacks cannot be guaranteed.
4889 *
4890 * @hide
4891 */
4892 @SystemApi
4893 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4894 @NonNull final QosCallback callback,
4895 @CallbackExecutor @NonNull final Executor executor) {
4896 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4897 Objects.requireNonNull(callback, "callback must be non-null");
4898 Objects.requireNonNull(executor, "executor must be non-null");
4899
4900 try {
4901 synchronized (mQosCallbackConnections) {
4902 if (getQosCallbackConnection(callback) == null) {
4903 final QosCallbackConnection connection =
4904 new QosCallbackConnection(this, callback, executor);
4905 mQosCallbackConnections.add(connection);
4906 mService.registerQosSocketCallback(socketInfo, connection);
4907 } else {
4908 Log.e(TAG, "registerQosCallback: Callback already registered");
4909 throw new QosCallbackRegistrationException();
4910 }
4911 }
4912 } catch (final RemoteException e) {
4913 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4914
4915 // The same unregister method method is called for consistency even though nothing
4916 // will be sent to the ConnectivityService since the callback was never successfully
4917 // registered.
4918 unregisterQosCallback(callback);
4919 e.rethrowFromSystemServer();
4920 } catch (final ServiceSpecificException e) {
4921 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4922 unregisterQosCallback(callback);
4923 throw convertServiceException(e);
4924 }
4925 }
4926
4927 /**
4928 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4929 * events once unregistered and can be registered a second time.
4930 * <p/>
4931 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4932 *
4933 * @param callback the callback being unregistered
4934 *
4935 * @hide
4936 */
4937 @SystemApi
4938 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4939 Objects.requireNonNull(callback, "The callback must be non-null");
4940 try {
4941 synchronized (mQosCallbackConnections) {
4942 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4943 if (connection != null) {
4944 connection.stopReceivingMessages();
4945 mService.unregisterQosCallback(connection);
4946 mQosCallbackConnections.remove(connection);
4947 } else {
4948 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4949 }
4950 }
4951 } catch (final RemoteException e) {
4952 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4953 e.rethrowFromSystemServer();
4954 }
4955 }
4956
4957 /**
4958 * Gets the connection related to the callback.
4959 *
4960 * @param callback the callback to look up
4961 * @return the related connection
4962 */
4963 @Nullable
4964 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4965 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4966 // Checking by reference here is intentional
4967 if (connection.getCallback() == callback) {
4968 return connection;
4969 }
4970 }
4971 return null;
4972 }
Junyu Laia62493f2021-01-19 11:10:56 +00004973
4974 /**
4975 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4976 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4977 * be used to request that the system provide a network without causing the network to be
4978 * in the foreground.
4979 *
4980 * <p>This method will attempt to find the best network that matches the passed
4981 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4982 * criteria. The platform will evaluate which network is the best at its own discretion.
4983 * Throughput, latency, cost per byte, policy, user preference and other considerations
4984 * may be factored in the decision of what is considered the best network.
4985 *
4986 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4987 * matching this request, while always attempting to match the request to a better network if
4988 * possible. If a better match is found, the platform will switch this request to the now-best
4989 * network and inform the app of the newly best network by invoking
4990 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4991 * will not try to maintain any other network than the best one currently matching the request:
4992 * a network not matching any network request may be disconnected at any time.
4993 *
4994 * <p>For example, an application could use this method to obtain a connected cellular network
4995 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4996 * radio to consume additional power. Or, an application could inform the system that it wants
4997 * a network supporting sending MMSes and have the system let it know about the currently best
4998 * MMS-supporting network through the provided {@link NetworkCallback}.
4999 *
5000 * <p>The status of the request can be followed by listening to the various callbacks described
5001 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5002 * used to direct traffic to the network (although accessing some networks may be subject to
5003 * holding specific permissions). Callers will learn about the specific characteristics of the
5004 * network through
5005 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5006 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5007 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5008 * matching the request at any given time; therefore when a better network matching the request
5009 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5010 * with the new network after which no further updates are given about the previously-best
5011 * network, unless it becomes the best again at some later time. All callbacks are invoked
5012 * in order on the same thread, which by default is a thread created by the framework running
5013 * in the app.
5014 *
5015 * <p>This{@link NetworkRequest} will live until released via
5016 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5017 * which point the system may let go of the network at any time.
5018 *
5019 * <p>It is presently unsupported to request a network with mutable
5020 * {@link NetworkCapabilities} such as
5021 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5022 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5023 * as these {@code NetworkCapabilities} represent states that a particular
5024 * network may never attain, and whether a network will attain these states
5025 * is unknown prior to bringing up the network so the framework does not
5026 * know how to go about satisfying a request with these capabilities.
5027 *
5028 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5029 * number of outstanding requests to 100 per app (identified by their UID), shared with
5030 * all variants of this method, of {@link #registerNetworkCallback} as well as
5031 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5032 * Requesting a network with this method will count toward this limit. If this limit is
5033 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5034 * make sure to unregister the callbacks with
5035 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5036 *
5037 * @param request {@link NetworkRequest} describing this request.
5038 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5039 * If null, the callback is invoked on the default internal Handler.
5040 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5041 * the callback must not be shared - it uniquely specifies this request.
5042 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5043 * @throws SecurityException if missing the appropriate permissions.
5044 * @throws RuntimeException if the app already has too many callbacks registered.
5045 *
5046 * @hide
5047 */
5048 @SystemApi(client = MODULE_LIBRARIES)
5049 @SuppressLint("ExecutorRegistration")
5050 @RequiresPermission(anyOf = {
5051 android.Manifest.permission.NETWORK_SETTINGS,
5052 android.Manifest.permission.NETWORK_STACK,
5053 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5054 })
5055 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
5056 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
5057 final NetworkCapabilities nc = request.networkCapabilities;
5058 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
5059 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
5060 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005061}