blob: 987dcc4898b59a3f14b9e5b8b824b9709d46e593 [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 Lai23568a42021-01-19 11:10:56 +000018import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
junyulai48a59382019-01-15 11:32:44 +080019import static android.net.IpSecManager.INVALID_RESOURCE_ID;
Junyu Lai23568a42021-01-19 11:10:56 +000020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
junyulaid1a78162021-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 Bright60f02ed2020-06-15 16:10:01 -070024import static android.net.QosCallback.QosCallbackRegistrationException;
junyulai48a59382019-01-15 11:32:44 +080025
junyulaia86defc2018-12-27 17:25:29 +080026import android.annotation.CallbackExecutor;
Felipe Lemed16384b2016-01-22 09:44:57 -080027import android.annotation.IntDef;
Chalard Jean42a9c292019-01-07 19:26:34 +090028import android.annotation.NonNull;
Robin Lee33c73e22016-01-05 18:03:46 +000029import android.annotation.Nullable;
Jeff Sharkey2ac62992017-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 Lai23568a42021-01-19 11:10:56 +000033import android.annotation.SuppressLint;
Udam Saini53b71ee2016-01-04 12:16:14 -080034import android.annotation.SystemApi;
Jeff Sharkeyb8c73032017-06-02 17:36:26 -060035import android.annotation.SystemService;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070036import android.app.PendingIntent;
Artur Satayev0e45d782019-12-10 17:47:52 +000037import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -070038import android.content.Context;
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -070039import android.content.Intent;
junyulaia86defc2018-12-27 17:25:29 +080040import android.net.IpSecManager.UdpEncapsulationSocket;
41import android.net.SocketKeepalive.Callback;
markchiencc1bc1b2020-01-20 19:31:56 +080042import android.net.TetheringManager.StartTetheringCallback;
markchieneeea0be2020-01-21 13:11:06 +080043import android.net.TetheringManager.TetheringEventCallback;
markchiencc1bc1b2020-01-20 19:31:56 +080044import android.net.TetheringManager.TetheringRequest;
Robert Greenwalt2034b912009-08-12 16:08:25 -070045import android.os.Binder;
Mathew Inwoodac5968e2018-12-20 15:30:45 +000046import android.os.Build;
Jeff Sharkey39c01eb2011-08-16 14:37:57 -070047import android.os.Build.VERSION_CODES;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080048import android.os.Bundle;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070049import android.os.Handler;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080050import android.os.IBinder;
51import android.os.INetworkActivityListener;
52import android.os.INetworkManagementService;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070053import android.os.Looper;
54import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070055import android.os.Messenger;
junyulai61143782019-03-04 22:45:36 +080056import android.os.ParcelFileDescriptor;
Cody Kestingb5c7abd2020-04-15 12:33:28 -070057import android.os.PersistableBundle;
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +090058import android.os.Process;
The Android Open Source Project28527d22009-03-03 19:31:44 -080059import android.os.RemoteException;
Jeremy Klein9a36ec82016-01-22 14:11:45 -080060import android.os.ResultReceiver;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080061import android.os.ServiceManager;
Hugo Benichi145e3792017-05-11 13:16:17 +090062import android.os.ServiceSpecificException;
Jeff Sharkey971cd162011-08-29 16:02:57 -070063import android.provider.Settings;
Wink Saville02eb35c2014-12-05 11:10:30 -080064import android.telephony.SubscriptionManager;
Meng Wang91311c02019-11-18 17:10:00 -080065import android.telephony.TelephonyManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -080066import android.util.ArrayMap;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -070067import android.util.Log;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090068import android.util.Range;
Erik Kline50068e52017-01-26 18:08:28 +090069import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080070
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +090071import com.android.connectivity.aidl.INetworkAgent;
markchieneeea0be2020-01-21 13:11:06 +080072import com.android.internal.annotations.GuardedBy;
Hugo Benichi45a49542017-03-06 09:17:06 +090073import com.android.internal.util.Preconditions;
74import com.android.internal.util.Protocol;
Robert Greenwalt3d6c9582014-05-21 20:04:36 -070075
Paul Jensen99c36662014-08-27 12:38:45 -040076import libcore.net.event.NetworkEventDispatcher;
77
junyulai61143782019-03-04 22:45:36 +080078import java.io.IOException;
79import java.io.UncheckedIOException;
Felipe Lemed16384b2016-01-22 09:44:57 -080080import java.lang.annotation.Retention;
81import java.lang.annotation.RetentionPolicy;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090082import java.net.DatagramSocket;
Jeremy Klein04863332015-12-28 15:11:58 -080083import java.net.InetAddress;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -070084import java.net.InetSocketAddress;
junyulaic7ea1242019-01-08 20:04:33 +080085import java.net.Socket;
Hugo Benichi45a49542017-03-06 09:17:06 +090086import java.util.ArrayList;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +090087import java.util.Collection;
Jeremy Klein04863332015-12-28 15:11:58 -080088import java.util.HashMap;
Hugo Benichi45a49542017-03-06 09:17:06 +090089import java.util.List;
90import java.util.Map;
markchieneeea0be2020-01-21 13:11:06 +080091import java.util.Objects;
junyulaia86defc2018-12-27 17:25:29 +080092import java.util.concurrent.Executor;
junyulai9f872232019-01-16 20:23:34 +080093import java.util.concurrent.ExecutorService;
94import java.util.concurrent.Executors;
95import java.util.concurrent.RejectedExecutionException;
Jeremy Klein04863332015-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 Sharkeyb8c73032017-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 Greenwaltd0ebdbb2014-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 Sharkeyb8c73032017-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, Yoshinari99efcbd2015-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 Greenwaltd0ebdbb2014-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 Lue1682a02016-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 Greenwalt26744a52013-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 Jeanae2424a2018-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 Sharkey6932ff62013-02-20 18:21:19 -0800153 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jeanae2424a2018-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 Jensened4d55c2015-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 Jensen4173cce2015-05-22 10:50:39 -0400162 * desire to sign in to the network. Apps handling this activity should
Paul Jensened4d55c2015-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 Jensen4173cce2015-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 Jean73d9db72018-06-04 16:52:49 +0900177 * data network.</li>
Paul Jensen4173cce2015-05-22 10:50:39 -0400178 * <li> When the app handling this action believes the user explicitly wants
Paul Jensened4d55c2015-02-27 22:55:47 -0500179 * to ignore the captive portal and the network, the app should call
Paul Jensen4173cce2015-05-22 10:50:39 -0400180 * {@link CaptivePortal#ignoreNetwork}. </li>
181 * </ul>
Paul Jensened4d55c2015-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 Jeancc47b522019-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 Jeancc47b522019-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 Jeancc47b522019-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)}.
junyulai5c2f6262018-12-13 12:47:51 +0800214 *
215 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800216 */
junyulai5c2f6262018-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)}.
junyulai5c2f6262018-12-13 12:47:51 +0800223 *
224 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800225 */
junyulai5c2f6262018-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)}.
junyulai5c2f6262018-12-13 12:47:51 +0800247 *
248 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800249 */
junyulai5c2f6262018-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 Jensen4173cce2015-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 Jensened4d55c2015-02-27 22:55:47 -0500267 */
Paul Jensen4173cce2015-05-22 10:50:39 -0400268 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist0f3b4442015-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 Jensened4d55c2015-02-27 22:55:47 -0500275 /**
Remi NGUYEN VANd937e3a2018-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 VANe541d182019-01-17 14:38:31 +0900280 @SystemApi
Remi NGUYEN VANd937e3a2018-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 Benichidce21c52016-12-14 08:23:40 +0900285 * Key for passing a user agent string to the captive portal login activity.
286 * {@hide}
287 */
Remi NGUYEN VANe541d182019-01-17 14:38:31 +0900288 @SystemApi
Hugo Benichidce21c52016-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 Greenwalt26744a52013-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 Jean73d9db72018-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 Sharma601fba92014-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 Sharkey6932ff62013-02-20 18:21:19 -0800350 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood0b8f8612018-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 Greenwalt26744a52013-02-15 10:56:35 -0800356 * Broadcast Action: A tetherable connection has come or gone.
357 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline449ccfe2017-04-17 16:47:23 +0900358 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
359 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt26744a52013-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 Sharkey6932ff62013-02-20 18:21:19 -0800365 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwood5a09a712020-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 =
markchien1f523702019-12-25 19:40:32 +0800368 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800369
370 /**
371 * @hide
Robert Greenwalt26744a52013-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 Inwood5a09a712020-11-04 09:29:36 +0000375 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-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 Kline449ccfe2017-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 */
markchien1f523702019-12-25 19:40:32 +0800383 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline449ccfe2017-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 Inwood5a09a712020-11-04 09:29:36 +0000390 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-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 Greenwalt26744a52013-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 Inwood5a09a712020-11-04 09:29:36 +0000399 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchien1f523702019-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 Brenner4774b022013-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 Sharkey6932ff62013-02-20 18:21:19 -0800408 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner4774b022013-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 Colitti36fbebe2015-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 Colitti477bf5c2016-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 /**
lucaslin25a50472019-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 Klein9a36ec82016-01-22 14:11:45 -0800446 * Invalid tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900447 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800448 * @hide
449 */
markchien1f523702019-12-25 19:40:32 +0800450 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800451
452 /**
453 * Wifi tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900454 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800455 * @hide
456 */
457 @SystemApi
markchien1f523702019-12-25 19:40:32 +0800458 public static final int TETHERING_WIFI = TetheringManager.TETHERING_WIFI;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800459
460 /**
461 * USB tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900462 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800463 * @hide
464 */
465 @SystemApi
markchien1f523702019-12-25 19:40:32 +0800466 public static final int TETHERING_USB = TetheringManager.TETHERING_USB;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800467
468 /**
469 * Bluetooth tethering type.
Chalard Jean73d9db72018-06-04 16:52:49 +0900470 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800471 * @hide
472 */
473 @SystemApi
markchien1f523702019-12-25 19:40:32 +0800474 public static final int TETHERING_BLUETOOTH = TetheringManager.TETHERING_BLUETOOTH;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800475
476 /**
Jimmy Chen87db1542019-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 */
markchien1f523702019-12-25 19:40:32 +0800482 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chen87db1542019-07-15 18:03:23 +0800483
484 /**
Jeremy Klein9a36ec82016-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 */
markchieneeea0be2020-01-21 13:11:06 +0800489 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein9a36ec82016-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 */
markchieneeea0be2020-01-21 13:11:06 +0800496 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein9a36ec82016-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 */
markchieneeea0be2020-01-21 13:11:06 +0800503 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800504
505 /**
506 * Tells the TetherService to run a provision check now.
507 * @hide
508 */
markchieneeea0be2020-01-21 13:11:06 +0800509 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein9a36ec82016-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 */
markchieneeea0be2020-01-21 13:11:06 +0800516 public static final String EXTRA_PROVISION_CALLBACK =
517 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein9a36ec82016-01-22 14:11:45 -0800518
519 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -0800520 * The absence of a connection type.
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700521 * @hide
522 */
paulhu62af6122020-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 Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900533 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700534 public static final int TYPE_MOBILE = 0;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900535
Robert Greenwalt2034b912009-08-12 16:08:25 -0700536 /**
Chalard Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900543 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700544 public static final int TYPE_WIFI = 1;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900545
Robert Greenwalt2034b912009-08-12 16:08:25 -0700546 /**
Robert Greenwalt26744a52013-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 Colitti7cc32c52015-04-23 15:32:42 +0900551 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900552 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900553 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900554 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700555 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700556 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700557 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900558
Robert Greenwalt2034b912009-08-12 16:08:25 -0700559 /**
Robert Greenwalt26744a52013-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 Colitti7cc32c52015-04-23 15:32:42 +0900564 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900565 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colittiefd396e2015-04-24 17:03:31 +0900566 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900567 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt2034b912009-08-12 16:08:25 -0700568 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700569 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700570 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900571
Robert Greenwalt2034b912009-08-12 16:08:25 -0700572 /**
Robert Greenwalt26744a52013-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 Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900582 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700583 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900584
Robert Greenwalt2034b912009-08-12 16:08:25 -0700585 /**
Robert Greenwalt26744a52013-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 Colitti7cc32c52015-04-23 15:32:42 +0900588 * is different.
589 *
Chalard Jean5acb7b72018-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 Liutikasa6bb0232016-05-24 15:22:55 -0700594 @Deprecated
Robert Greenwalt2034b912009-08-12 16:08:25 -0700595 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean5acb7b72018-03-08 13:54:53 +0900596
jshbfa81722010-03-11 15:04:43 -0800597 /**
Chalard Jean5acb7b72018-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 Jean5acb7b72018-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 Jean5acb7b72018-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 Jean5acb7b72018-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 Wang7d5f3782020-07-28 13:53:09 +0800618 * Fake data connection. This should not be used on shipping devices.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900619 * @deprecated This is not used any more.
Robert Greenwaltf76c55d2011-04-22 15:28:18 -0700620 */
Chalard Jean5acb7b72018-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 Jean5acb7b72018-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 Jean5acb7b72018-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 Greenwalt26744a52013-02-15 10:56:35 -0800635 * Over the air Administration.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900636 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Savilleb7c92c72011-03-12 14:52:01 -0800637 * {@hide}
638 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900639 @Deprecated
Chalard Jeanaa91c9d2019-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 Greenwalt26744a52013-02-15 10:56:35 -0800644 * IP Multimedia Subsystem.
Chalard Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900648 @Deprecated
Mathew Inwood0b8f8612018-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 Greenwalt26744a52013-02-15 10:56:35 -0800653 * Carrier Branded Services.
Chalard Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900657 @Deprecated
Chalard Jeanaa91c9d2019-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 Jean5acb7b72018-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 Jean5acb7b72018-03-08 13:54:53 +0900667 @Deprecated
paulhu028732e2020-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 Saville70dbdcc2013-07-29 15:00:57 -0700671 /**
672 * The network to use for initially attaching to the network
Chalard Jean5acb7b72018-03-08 13:54:53 +0900673 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville70dbdcc2013-07-29 15:00:57 -0700674 * {@hide}
675 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900676 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +0100677 @UnsupportedAppUsage
Wink Saville70dbdcc2013-07-29 15:00:57 -0700678 public static final int TYPE_MOBILE_IA = 14;
repo syncf5de5572011-07-29 23:55:49 -0700679
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +0900680 /**
Robert Greenwalt9db5f3c2015-07-09 14:49:35 -0700681 * Emergency PDN connection for emergency services. This
682 * may include IMS and MMS in emergency situations.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900683 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram201d45f2014-06-26 11:03:44 -0700684 * {@hide}
685 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900686 @Deprecated
Chalard Jeanaa91c9d2019-04-09 15:46:21 +0900687 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram201d45f2014-06-26 11:03:44 -0700688 public static final int TYPE_MOBILE_EMERGENCY = 15;
689
Hui Lu07f29332014-01-15 11:05:36 -0500690 /**
691 * The network that uses proxy to achieve connectivity.
Chalard Jean5acb7b72018-03-08 13:54:53 +0900692 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu07f29332014-01-15 11:05:36 -0500693 * {@hide}
694 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900695 @Deprecated
Remi NGUYEN VANdaeafee2020-11-30 19:23:45 +0900696 @SystemApi
Hui Lu07f29332014-01-15 11:05:36 -0500697 public static final int TYPE_PROXY = 16;
Wink Saville70dbdcc2013-07-29 15:00:57 -0700698
Robert Greenwaltb2a03d12014-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 Jean5acb7b72018-03-08 13:54:53 +0900702 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700703 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900704 @Deprecated
Robert Greenwaltb2a03d12014-07-07 17:09:01 -0700705 public static final int TYPE_VPN = 17;
Hui Lu07f29332014-01-15 11:05:36 -0500706
Benedict Wong80156022018-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 Greenwaltb2a03d12014-07-07 17:09:01 -0700715
Chalard Jeane5b9e822020-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 Jean1f42df12019-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 Greenwaltb2a03d12014-07-07 17:09:01 -0700752 /** {@hide} */
Benedict Wong80156022018-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 Benichi37d5c3c2017-06-20 14:07:59 +0900758 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
759
Jianzheng Zhoua8aa1602012-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 Greenwalt26744a52013-02-15 10:56:35 -0800766 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800767 * networkAttributes in config.xml. You can determine
Robert Greenwalt1ee3d2c2012-12-07 09:56:50 -0800768 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoua8aa1602012-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 Sharkey5eccd9c2012-09-26 22:03:49 -0700774 /**
Robert Greenwalta1402df2014-03-19 17:56:12 -0700775 * @hide
776 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900777 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwaltc34f83b2014-06-08 16:42:59 -0700778
Paul Jensen0478ace2014-07-11 12:28:19 -0400779 /**
Hugo Benichi1c027fe2017-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 Jean73d9db72018-06-04 16:52:49 +0900782 * registered from those that were already unregistered.
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900783 * @hide
784 */
Hugo Benichibcc81df2017-06-20 14:10:14 +0900785 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi1c027fe2017-06-17 13:14:12 +0900786 new NetworkRequest.Builder().clearCapabilities().build();
787
788 /**
Paul Jensen0478ace2014-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 Kline1ecdd962017-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 Klineae1a3af2018-05-16 16:41:57 +0900822 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline1ecdd962017-10-30 15:29:44 +0900823
Chalard Jeanaa91c9d2019-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 Jensen12131352014-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 Colitti9b026fa2015-07-29 11:41:21 +0900834 private final Context mContext;
835
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800836 private INetworkManagementService mNMService;
Felipe Lemed16384b2016-01-22 09:44:57 -0800837 private INetworkPolicyManager mNPManager;
Amos Bianchiddadca42020-03-04 11:07:38 -0800838 private final TetheringManager mTetheringManager;
Dianne Hackbornb4b09e82014-02-26 16:20:52 -0800839
Robert Greenwalt26744a52013-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 Jensen1c9f2e42015-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 Greenwalt26744a52013-02-15 10:56:35 -0800846 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700847 @Deprecated
Jeff Sharkey21062e72011-05-28 20:56:34 -0700848 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi37d5c3c2017-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 Greenwalt26744a52013-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 Jean5acb7b72018-03-08 13:54:53 +0900858 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800859 * {@hide}
860 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900861 @Deprecated
Mathew Inwood5a09a712020-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 Benichi37d5c3c2017-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 Saville70dbdcc2013-07-29 15:00:57 -0700895 case TYPE_MOBILE_IA:
896 return "MOBILE_IA";
Ram201d45f2014-06-26 11:03:44 -0700897 case TYPE_MOBILE_EMERGENCY:
898 return "MOBILE_EMERGENCY";
Hui Lu07f29332014-01-15 11:05:36 -0500899 case TYPE_PROXY:
900 return "PROXY";
Erik Klineb1ff7002014-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 Greenwalt26744a52013-02-15 10:56:35 -0800908 /**
Aaron Huang925d09b2020-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 Greenwalt26744a52013-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 Jean5acb7b72018-03-08 13:54:53 +0900925 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800926 * {@hide}
927 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900928 @Deprecated
Chalard Jeanaa91c9d2019-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 Saville70dbdcc2013-07-29 15:00:57 -0700940 case TYPE_MOBILE_IA:
Ram201d45f2014-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 Greenwalt26744a52013-02-15 10:56:35 -0800948 /**
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700949 * Checks if the given network type is backed by a Wi-Fi radio.
950 *
Chalard Jean5acb7b72018-03-08 13:54:53 +0900951 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkeye9bda1d2013-06-04 12:29:00 -0700952 * @hide
953 */
Chalard Jean5acb7b72018-03-08 13:54:53 +0900954 @Deprecated
Jeff Sharkeye9bda1d2013-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 Greenwalt26744a52013-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 Greenwalt26744a52013-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 Greenwaltd0ebdbb2014-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 Greenwalt26744a52013-02-15 10:56:35 -0800976 */
Aurimas Liutikasa6bb0232016-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 Greenwalt26744a52013-02-15 10:56:35 -0800981 /**
982 * Retrieves the current preferred network type.
Robert Greenwalt26744a52013-02-15 10:56:35 -0800983 *
984 * @return an integer representing the preferred network type
985 *
Robert Greenwaltd0ebdbb2014-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 Greenwalt26744a52013-02-15 10:56:35 -0800990 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -0700991 @Deprecated
Jeff Sharkey2ac62992017-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 Greenwaltd0ebdbb2014-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 Greenwalt26744a52013-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 Jean7c85ba42018-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 Greenwalt26744a52013-02-15 10:56:35 -08001007 *
1008 * @return a {@link NetworkInfo} object for the current default network
Paul Jensena9208b92015-02-13 14:18:39 -05001009 * or {@code null} if no default network is currently active
junyulai5c2f6262018-12-13 12:47:51 +08001010 * @deprecated See {@link NetworkInfo}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001011 */
junyulai5c2f6262018-12-13 12:47:51 +08001012 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001013 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-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 Sharkeya6066fd2016-03-01 19:27:23 -07001019 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001020 }
1021 }
1022
Robert Greenwalt26744a52013-02-15 10:56:35 -08001023 /**
Paul Jensenc2569432015-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 Jensenc2569432015-02-13 14:18:39 -05001032 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001033 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001034 @Nullable
Paul Jensenc2569432015-02-13 14:18:39 -05001035 public Network getActiveNetwork() {
1036 try {
1037 return mService.getActiveNetwork();
1038 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001039 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05001040 }
1041 }
1042
1043 /**
Robin Leeda4d2e22016-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 Leeda4d2e22016-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 */
paulhud70b7dd2019-08-12 16:25:11 +08001055 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09001056 @Nullable
Robin Leeda4d2e22016-03-24 12:07:00 +00001057 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001058 return getActiveNetworkForUid(uid, false);
1059 }
1060
1061 /** {@hide} */
1062 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leeda4d2e22016-03-24 12:07:00 +00001063 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001064 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001065 } catch (RemoteException e) {
1066 throw e.rethrowFromSystemServer();
1067 }
1068 }
1069
1070 /**
Charles He729f0b42017-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 He4bfaefe2017-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 He729f0b42017-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 Lee33c73e22016-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 Leeab2788a2016-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 Wang7d5f3782020-07-28 13:53:09 +08001106 * @param lockdownAllowlist The list of packages that are allowed to access network directly
Pavel Grafov4753f402019-01-25 08:50:06 +00001107 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
Chiachang Wang7d5f3782020-07-28 13:53:09 +08001108 * this method must be called when a package that should be allowed is installed or
Pavel Grafov4753f402019-01-25 08:50:06 +00001109 * uninstalled.
Robin Lee33c73e22016-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 Grafov4753f402019-01-25 08:50:06 +00001114 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leeab2788a2016-05-03 13:23:03 +01001115 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Chiachang Wang7d5f3782020-07-28 13:53:09 +08001116 boolean lockdownEnabled, @Nullable List<String> lockdownAllowlist) {
Robin Lee33c73e22016-01-05 18:03:46 +00001117 try {
Pavel Grafov4753f402019-01-25 08:50:06 +00001118 return mService.setAlwaysOnVpnPackage(
Chiachang Wang7d5f3782020-07-28 13:53:09 +08001119 userId, vpnPackage, lockdownEnabled, lockdownAllowlist);
Robin Lee33c73e22016-01-05 18:03:46 +00001120 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001121 throw e.rethrowFromSystemServer();
Robin Lee33c73e22016-01-05 18:03:46 +00001122 }
1123 }
1124
Pavel Grafov4753f402019-01-25 08:50:06 +00001125 /**
Robin Lee33c73e22016-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 Grafov4753f402019-01-25 08:50:06 +00001134 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee33c73e22016-01-05 18:03:46 +00001135 public String getAlwaysOnVpnPackageForUser(int userId) {
1136 try {
1137 return mService.getAlwaysOnVpnPackage(userId);
1138 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001139 throw e.rethrowFromSystemServer();
Robin Lee33c73e22016-01-05 18:03:46 +00001140 }
1141 }
1142
1143 /**
Pavel Grafov4753f402019-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 Colittie8ce2052020-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 Greenwalt26744a52013-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 Greenwalt26744a52013-02-15 10:56:35 -08001231 * {@hide}
1232 */
paulhud70b7dd2019-08-12 16:25:11 +08001233 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwood5a09a712020-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 Sharkey833c35b2016-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 Sharkey833c35b2016-04-28 15:33:18 -06001242 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001243 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001244 throw e.rethrowFromSystemServer();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001245 }
1246 }
1247
Robert Greenwalt26744a52013-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 Jean7c85ba42018-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 Greenwalt26744a52013-02-15 10:56:35 -08001261 *
Paul Jensena8e6dc62015-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 Greenwalt26744a52013-02-15 10:56:35 -08001265 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001266 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001267 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-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 Sharkeya6066fd2016-03-01 19:27:23 -07001273 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001274 }
1275 }
1276
Robert Greenwalt26744a52013-02-15 10:56:35 -08001277 /**
Robert Greenwalt701a5c32014-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.
junyulai5c2f6262018-12-13 12:47:51 +08001286 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001287 */
junyulai5c2f6262018-12-13 12:47:51 +08001288 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001289 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001290 @Nullable
1291 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey833c35b2016-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 Greenwalt701a5c32014-06-23 11:40:00 -07001297 try {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001298 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001299 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001300 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001301 }
1302 }
1303
1304 /**
Robert Greenwalt26744a52013-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 Jensena8e6dc62015-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 Greenwalt26744a52013-02-15 10:56:35 -08001314 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001315 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001316 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-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 Sharkeya6066fd2016-03-01 19:27:23 -07001322 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001323 }
1324 }
1325
Robert Greenwalt26744a52013-02-15 10:56:35 -08001326 /**
Lorenzo Colitti2b2d73c2014-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 Colitti2b2d73c2014-08-22 17:10:50 -07001330 * @hide
Paul Jensena8e6dc62015-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 Colitti2b2d73c2014-08-22 17:10:50 -07001334 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001335 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001336 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001337 @UnsupportedAppUsage
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001338 public Network getNetworkForType(int networkType) {
1339 try {
1340 return mService.getNetworkForType(networkType);
1341 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001342 throw e.rethrowFromSystemServer();
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001343 }
1344 }
1345
1346 /**
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001347 * Returns an array of all {@link Network} currently tracked by the
1348 * framework.
Paul Jensen19b3ee72015-05-06 11:10:18 -04001349 *
1350 * @return an array of {@link Network} objects.
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001351 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001352 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001353 @NonNull
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001354 public Network[] getAllNetworks() {
1355 try {
1356 return mService.getAllNetworks();
1357 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001358 throw e.rethrowFromSystemServer();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001359 }
1360 }
1361
1362 /**
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +09001363 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001364 * the Networks that applications run by the given user will use by default.
1365 * @hide
1366 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01001367 @UnsupportedAppUsage
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001368 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1369 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001370 return mService.getDefaultNetworkCapabilitiesForUser(
1371 userId, mContext.getOpPackageName());
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001372 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001373 throw e.rethrowFromSystemServer();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001374 }
1375 }
1376
1377 /**
Robert Greenwalt26744a52013-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 Greenwalt26744a52013-02-15 10:56:35 -08001384 * {@hide}
Chalard Jeancc47b522019-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 Greenwalt26744a52013-02-15 10:56:35 -08001389 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001390 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeancc47b522019-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 Sharkeya6066fd2016-03-01 19:27:23 -07001396 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001397 }
1398 }
1399
Robert Greenwalt26744a52013-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 Greenwalt26744a52013-02-15 10:56:35 -08001408 * {@hide}
Paul Jensena8e6dc62015-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 Greenwalt26744a52013-02-15 10:56:35 -08001413 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001414 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001415 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-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 Greenwalt2bebbfb2014-03-26 16:47:06 -07001419 return mService.getLinkPropertiesForType(networkType);
1420 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001421 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001422 }
1423 }
1424
Robert Greenwaltd0ebdbb2014-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 Jensen19b3ee72015-05-06 11:10:18 -04001431 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001432 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001433 @Nullable
1434 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001435 try {
1436 return mService.getLinkProperties(network);
1437 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001438 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001439 }
1440 }
1441
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001442 /**
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +09001443 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd0ebdbb2014-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 Colitti7cc32c52015-04-23 15:32:42 +09001447 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001448 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06001449 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09001450 @Nullable
1451 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001452 try {
Qingxi Libf6bf082020-01-08 12:51:49 -08001453 return mService.getNetworkCapabilities(network, mContext.getOpPackageName());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001454 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001455 throw e.rethrowFromSystemServer();
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001456 }
1457 }
1458
Robert Greenwalt26744a52013-02-15 10:56:35 -08001459 /**
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001460 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Saini53b71ee2016-01-04 12:16:14 -08001461 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1462 * portal is present.
1463 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1464 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1465 *
Remi NGUYEN VAN69a57cb2019-03-20 14:22:49 +09001466 * The system network validation may be using different strategies to detect captive portals,
1467 * so this method does not necessarily return a URL used by the system. It only returns a URL
1468 * that may be relevant for other components trying to detect captive portals.
paulhud70b7dd2019-08-12 16:25:11 +08001469 *
Udam Saini53b71ee2016-01-04 12:16:14 -08001470 * @hide
paulhud70b7dd2019-08-12 16:25:11 +08001471 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1472 * system.
Udam Saini53b71ee2016-01-04 12:16:14 -08001473 */
paulhud70b7dd2019-08-12 16:25:11 +08001474 @Deprecated
Udam Saini53b71ee2016-01-04 12:16:14 -08001475 @SystemApi
paulhud70b7dd2019-08-12 16:25:11 +08001476 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Saini53b71ee2016-01-04 12:16:14 -08001477 public String getCaptivePortalServerUrl() {
1478 try {
1479 return mService.getCaptivePortalServerUrl();
1480 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001481 throw e.rethrowFromSystemServer();
Udam Saini53b71ee2016-01-04 12:16:14 -08001482 }
1483 }
1484
1485 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001486 * Tells the underlying networking system that the caller wants to
1487 * begin using the named feature. The interpretation of {@code feature}
1488 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001489 *
1490 * <p>This method requires the caller to hold either the
1491 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1492 * or the ability to modify system settings as determined by
1493 * {@link android.provider.Settings.System#canWrite}.</p>
1494 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001495 * @param networkType specifies which network the request pertains to
1496 * @param feature the name of the feature to be used
1497 * @return an integer value representing the outcome of the request.
1498 * The interpretation of this value is specific to each networking
1499 * implementation+feature combination, except that the value {@code -1}
1500 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001501 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09001502 * @deprecated Deprecated in favor of the cleaner
1503 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001504 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001505 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001506 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001507 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001508 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001509 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001510 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001511 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1512 if (netCap == null) {
1513 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1514 feature);
Chalard Jean1f42df12019-11-21 14:48:00 +09001515 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001516 }
1517
1518 NetworkRequest request = null;
1519 synchronized (sLegacyRequests) {
1520 LegacyRequest l = sLegacyRequests.get(netCap);
1521 if (l != null) {
1522 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1523 renewRequestLocked(l);
1524 if (l.currentNetwork != null) {
Chalard Jean1f42df12019-11-21 14:48:00 +09001525 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001526 } else {
Chalard Jean1f42df12019-11-21 14:48:00 +09001527 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001528 }
1529 }
1530
1531 request = requestNetworkForFeatureLocked(netCap);
1532 }
1533 if (request != null) {
Robert Greenwaltca3c5cf2014-06-20 10:58:45 -07001534 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jean1f42df12019-11-21 14:48:00 +09001535 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001536 } else {
1537 Log.d(TAG, " request Failed");
Chalard Jean1f42df12019-11-21 14:48:00 +09001538 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001539 }
1540 }
1541
1542 /**
1543 * Tells the underlying networking system that the caller is finished
1544 * using the named feature. The interpretation of {@code feature}
1545 * is completely up to each networking implementation.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09001546 *
1547 * <p>This method requires the caller to hold either the
1548 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1549 * or the ability to modify system settings as determined by
1550 * {@link android.provider.Settings.System#canWrite}.</p>
1551 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001552 * @param networkType specifies which network the request pertains to
1553 * @param feature the name of the feature that is no longer needed
1554 * @return an integer value representing the outcome of the request.
1555 * The interpretation of this value is specific to each networking
1556 * implementation+feature combination, except that the value {@code -1}
1557 * always indicates failure.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07001558 *
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09001559 * @deprecated Deprecated in favor of the cleaner
1560 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07001561 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001562 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09001563 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08001564 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07001565 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08001566 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09001567 checkLegacyRoutingApiAccess();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001568 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1569 if (netCap == null) {
1570 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1571 feature);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001572 return -1;
1573 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001574
Paul Jensen034dea32014-12-17 10:39:34 -05001575 if (removeRequestForFeature(netCap)) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001576 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001577 }
1578 return 1;
1579 }
1580
Mathew Inwood5a09a712020-11-04 09:29:36 +00001581 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001582 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1583 if (networkType == TYPE_MOBILE) {
Erik Kline50068e52017-01-26 18:08:28 +09001584 switch (feature) {
1585 case "enableCBS":
1586 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1587 case "enableDUN":
1588 case "enableDUNAlways":
1589 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1590 case "enableFOTA":
1591 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1592 case "enableHIPRI":
1593 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1594 case "enableIMS":
1595 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1596 case "enableMMS":
1597 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1598 case "enableSUPL":
1599 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1600 default:
1601 return null;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001602 }
Erik Kline50068e52017-01-26 18:08:28 +09001603 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1604 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001605 }
1606 return null;
1607 }
1608
Robert Greenwalt5a367872014-06-02 15:32:02 -07001609 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001610 if (netCap == null) return TYPE_NONE;
1611 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1612 return TYPE_MOBILE_CBS;
1613 }
1614 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1615 return TYPE_MOBILE_IMS;
1616 }
1617 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1618 return TYPE_MOBILE_FOTA;
1619 }
1620 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1621 return TYPE_MOBILE_DUN;
1622 }
1623 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1624 return TYPE_MOBILE_SUPL;
1625 }
1626 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1627 return TYPE_MOBILE_MMS;
1628 }
1629 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1630 return TYPE_MOBILE_HIPRI;
1631 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001632 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1633 return TYPE_WIFI_P2P;
1634 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001635 return TYPE_NONE;
1636 }
1637
1638 private static class LegacyRequest {
1639 NetworkCapabilities networkCapabilities;
1640 NetworkRequest networkRequest;
1641 int expireSequenceNumber;
1642 Network currentNetwork;
1643 int delay = -1;
Paul Jensen034dea32014-12-17 10:39:34 -05001644
1645 private void clearDnsBinding() {
1646 if (currentNetwork != null) {
1647 currentNetwork = null;
1648 setProcessDefaultNetworkForHostResolution(null);
1649 }
1650 }
1651
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001652 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001653 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001654 public void onAvailable(Network network) {
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001655 currentNetwork = network;
1656 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensene98c6e02014-05-29 10:12:39 -04001657 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001658 }
1659 @Override
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07001660 public void onLost(Network network) {
Paul Jensen034dea32014-12-17 10:39:34 -05001661 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001662 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1663 }
1664 };
1665 }
1666
Mathew Inwood5a09a712020-11-04 09:29:36 +00001667 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Chalard Jean73d9db72018-06-04 16:52:49 +09001668 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1669 new HashMap<>();
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001670
1671 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1672 synchronized (sLegacyRequests) {
1673 LegacyRequest l = sLegacyRequests.get(netCap);
1674 if (l != null) return l.networkRequest;
1675 }
1676 return null;
1677 }
1678
1679 private void renewRequestLocked(LegacyRequest l) {
1680 l.expireSequenceNumber++;
1681 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1682 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1683 }
1684
1685 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1686 int ourSeqNum = -1;
1687 synchronized (sLegacyRequests) {
1688 LegacyRequest l = sLegacyRequests.get(netCap);
1689 if (l == null) return;
1690 ourSeqNum = l.expireSequenceNumber;
Paul Jensen034dea32014-12-17 10:39:34 -05001691 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001692 }
1693 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1694 }
1695
Mathew Inwood5a09a712020-11-04 09:29:36 +00001696 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001697 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1698 int delay = -1;
Robert Greenwalt5a367872014-06-02 15:32:02 -07001699 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001700 try {
1701 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07001702 } catch (RemoteException e) {
1703 throw e.rethrowFromSystemServer();
1704 }
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001705 LegacyRequest l = new LegacyRequest();
1706 l.networkCapabilities = netCap;
1707 l.delay = delay;
1708 l.expireSequenceNumber = 0;
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001709 l.networkRequest = sendRequestForNetwork(
1710 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001711 if (l.networkRequest == null) return null;
1712 sLegacyRequests.put(netCap, l);
1713 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1714 return l.networkRequest;
1715 }
1716
1717 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1718 if (delay >= 0) {
1719 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09001720 CallbackHandler handler = getDefaultHandler();
Hugo Benichiec180d52017-02-03 14:18:44 +09001721 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1722 handler.sendMessageDelayed(msg, delay);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001723 }
1724 }
1725
Mathew Inwood5a09a712020-11-04 09:29:36 +00001726 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensen034dea32014-12-17 10:39:34 -05001727 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1728 final LegacyRequest l;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001729 synchronized (sLegacyRequests) {
Paul Jensen034dea32014-12-17 10:39:34 -05001730 l = sLegacyRequests.remove(netCap);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07001731 }
Paul Jensen034dea32014-12-17 10:39:34 -05001732 if (l == null) return false;
1733 unregisterNetworkCallback(l.networkCallback);
1734 l.clearDnsBinding();
1735 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001736 }
1737
Erik Kline50068e52017-01-26 18:08:28 +09001738 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1739 static {
1740 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1741 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1742 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1743 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1744 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1745 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1746 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1747 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1748 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1749 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1750 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1751 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1752 }
1753
1754 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1755 static {
1756 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1757 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1758 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1759 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1760 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1761 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1762 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1763 }
1764
1765 /**
1766 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1767 * instance suitable for registering a request or callback. Throws an
1768 * IllegalArgumentException if no mapping from the legacy type to
1769 * NetworkCapabilities is known.
1770 *
Chalard Jean5acb7b72018-03-08 13:54:53 +09001771 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1772 * to find the network instead.
Erik Kline50068e52017-01-26 18:08:28 +09001773 * @hide
1774 */
1775 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1776 final NetworkCapabilities nc = new NetworkCapabilities();
1777
1778 // Map from type to transports.
1779 final int NOT_FOUND = -1;
1780 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichiff4bf602017-05-09 15:19:01 +09001781 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline50068e52017-01-26 18:08:28 +09001782 nc.addTransportType(transport);
1783
1784 // Map from type to capabilities.
1785 nc.addCapability(sLegacyTypeToCapability.get(
1786 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1787 nc.maybeMarkCapabilitiesRestricted();
1788 return nc;
1789 }
1790
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001791 /** @hide */
1792 public static class PacketKeepaliveCallback {
Mathew Inwood5a09a712020-11-04 09:29:36 +00001793 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Artur Satayev198d6502019-11-04 17:50:59 +00001794 public PacketKeepaliveCallback() {
1795 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001796 /** The requested keepalive was successfully started. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001797 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001798 public void onStarted() {}
1799 /** The keepalive was successfully stopped. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001800 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001801 public void onStopped() {}
1802 /** An error occurred. */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001803 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001804 public void onError(int error) {}
1805 }
1806
1807 /**
1808 * Allows applications to request that the system periodically send specific packets on their
1809 * behalf, using hardware offload to save battery power.
1810 *
1811 * To request that the system send keepalives, call one of the methods that return a
1812 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1813 * passing in a non-null callback. If the callback is successfully started, the callback's
1814 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1815 * specifying one of the {@code ERROR_*} constants in this class.
1816 *
Chalard Jean73d9db72018-06-04 16:52:49 +09001817 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1818 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1819 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001820 *
junyulaia86defc2018-12-27 17:25:29 +08001821 * @deprecated Use {@link SocketKeepalive} instead.
1822 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001823 * @hide
1824 */
1825 public class PacketKeepalive {
1826
1827 private static final String TAG = "PacketKeepalive";
1828
1829 /** @hide */
1830 public static final int SUCCESS = 0;
1831
1832 /** @hide */
1833 public static final int NO_KEEPALIVE = -1;
1834
1835 /** @hide */
1836 public static final int BINDER_DIED = -10;
1837
1838 /** The specified {@code Network} is not connected. */
1839 public static final int ERROR_INVALID_NETWORK = -20;
1840 /** The specified IP addresses are invalid. For example, the specified source IP address is
1841 * not configured on the specified {@code Network}. */
1842 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1843 /** The requested port is invalid. */
1844 public static final int ERROR_INVALID_PORT = -22;
1845 /** The packet length is invalid (e.g., too long). */
1846 public static final int ERROR_INVALID_LENGTH = -23;
1847 /** The packet transmission interval is invalid (e.g., too short). */
1848 public static final int ERROR_INVALID_INTERVAL = -24;
1849
1850 /** The hardware does not support this request. */
1851 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti2aab7182015-09-08 16:46:36 +09001852 /** The hardware returned an error. */
1853 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001854
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001855 /** The NAT-T destination port for IPsec */
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001856 public static final int NATT_PORT = 4500;
1857
Nathan Harolde8ae0eb2018-02-14 13:09:45 -08001858 /** The minimum interval in seconds between keepalive packet transmissions */
1859 public static final int MIN_INTERVAL = 10;
1860
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001861 private final Network mNetwork;
junyulai9f872232019-01-16 20:23:34 +08001862 private final ISocketKeepaliveCallback mCallback;
1863 private final ExecutorService mExecutor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001864
1865 private volatile Integer mSlot;
1866
Mathew Inwood5a09a712020-11-04 09:29:36 +00001867 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001868 public void stop() {
1869 try {
junyulai9f872232019-01-16 20:23:34 +08001870 mExecutor.execute(() -> {
1871 try {
1872 if (mSlot != null) {
1873 mService.stopKeepalive(mNetwork, mSlot);
1874 }
1875 } catch (RemoteException e) {
1876 Log.e(TAG, "Error stopping packet keepalive: ", e);
1877 throw e.rethrowFromSystemServer();
1878 }
1879 });
1880 } catch (RejectedExecutionException e) {
1881 // The internal executor has already stopped due to previous event.
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001882 }
1883 }
1884
1885 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichi45a49542017-03-06 09:17:06 +09001886 Preconditions.checkNotNull(network, "network cannot be null");
1887 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001888 mNetwork = network;
junyulai9f872232019-01-16 20:23:34 +08001889 mExecutor = Executors.newSingleThreadExecutor();
1890 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001891 @Override
junyulai9f872232019-01-16 20:23:34 +08001892 public void onStarted(int slot) {
lucaslinad369e32020-12-30 11:54:55 +08001893 final long token = Binder.clearCallingIdentity();
1894 try {
1895 mExecutor.execute(() -> {
1896 mSlot = slot;
1897 callback.onStarted();
1898 });
1899 } finally {
1900 Binder.restoreCallingIdentity(token);
1901 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001902 }
junyulai9f872232019-01-16 20:23:34 +08001903
1904 @Override
1905 public void onStopped() {
lucaslinad369e32020-12-30 11:54:55 +08001906 final long token = Binder.clearCallingIdentity();
1907 try {
1908 mExecutor.execute(() -> {
1909 mSlot = null;
1910 callback.onStopped();
1911 });
1912 } finally {
1913 Binder.restoreCallingIdentity(token);
1914 }
junyulai9f872232019-01-16 20:23:34 +08001915 mExecutor.shutdown();
1916 }
1917
1918 @Override
1919 public void onError(int error) {
lucaslinad369e32020-12-30 11:54:55 +08001920 final long token = Binder.clearCallingIdentity();
1921 try {
1922 mExecutor.execute(() -> {
1923 mSlot = null;
1924 callback.onError(error);
1925 });
1926 } finally {
1927 Binder.restoreCallingIdentity(token);
1928 }
junyulai9f872232019-01-16 20:23:34 +08001929 mExecutor.shutdown();
1930 }
1931
1932 @Override
1933 public void onDataReceived() {
1934 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1935 // this callback when data is received.
1936 }
1937 };
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001938 }
1939 }
1940
1941 /**
1942 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1943 *
junyulaia86defc2018-12-27 17:25:29 +08001944 * @deprecated Use {@link #createSocketKeepalive} instead.
1945 *
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001946 * @hide
1947 */
Mathew Inwood5a09a712020-11-04 09:29:36 +00001948 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001949 public PacketKeepalive startNattKeepalive(
1950 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1951 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1952 final PacketKeepalive k = new PacketKeepalive(network, callback);
1953 try {
junyulai9f872232019-01-16 20:23:34 +08001954 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001955 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1956 } catch (RemoteException e) {
1957 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai9f872232019-01-16 20:23:34 +08001958 throw e.rethrowFromSystemServer();
Lorenzo Colittid1039d12015-06-15 14:29:22 +09001959 }
1960 return k;
1961 }
1962
Chiachang Wangc5f86f42021-01-15 11:06:21 +08001963 // Construct an invalid fd.
1964 private ParcelFileDescriptor createInvalidFd() {
1965 final int invalidFd = -1;
1966 return ParcelFileDescriptor.adoptFd(invalidFd);
1967 }
1968
The Android Open Source Project28527d22009-03-03 19:31:44 -08001969 /**
junyulaia86defc2018-12-27 17:25:29 +08001970 * Request that keepalives be started on a IPsec NAT-T socket.
1971 *
1972 * @param network The {@link Network} the socket is on.
1973 * @param socket The socket that needs to be kept alive.
1974 * @param source The source address of the {@link UdpEncapsulationSocket}.
1975 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1976 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1977 * must run callback sequentially, otherwise the order of callbacks cannot be
1978 * guaranteed.
1979 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1980 * changes. Must be extended by applications that use this API.
1981 *
junyulaic7ea1242019-01-08 20:04:33 +08001982 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1983 * given socket.
junyulaia86defc2018-12-27 17:25:29 +08001984 **/
junyulai61143782019-03-04 22:45:36 +08001985 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaia86defc2018-12-27 17:25:29 +08001986 @NonNull UdpEncapsulationSocket socket,
1987 @NonNull InetAddress source,
1988 @NonNull InetAddress destination,
1989 @NonNull @CallbackExecutor Executor executor,
1990 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08001991 ParcelFileDescriptor dup;
1992 try {
junyulaic4fb2482019-03-27 11:00:37 +08001993 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1994 // which cannot be obtained by the app process.
junyulai61143782019-03-04 22:45:36 +08001995 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1996 } catch (IOException ignored) {
1997 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1998 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08001999 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002000 }
2001 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2002 destination, executor, callback);
junyulai48a59382019-01-15 11:32:44 +08002003 }
2004
2005 /**
2006 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2007 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2008 *
2009 * @param network The {@link Network} the socket is on.
junyulai61143782019-03-04 22:45:36 +08002010 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2011 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2012 * from that port.
junyulai48a59382019-01-15 11:32:44 +08002013 * @param source The source address of the {@link UdpEncapsulationSocket}.
2014 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2015 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2016 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2017 * must run callback sequentially, otherwise the order of callbacks cannot be
2018 * guaranteed.
2019 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2020 * changes. Must be extended by applications that use this API.
2021 *
junyulaic7ea1242019-01-08 20:04:33 +08002022 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2023 * given socket.
junyulai48a59382019-01-15 11:32:44 +08002024 * @hide
2025 */
2026 @SystemApi
2027 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002028 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2029 @NonNull ParcelFileDescriptor pfd,
junyulai48a59382019-01-15 11:32:44 +08002030 @NonNull InetAddress source,
2031 @NonNull InetAddress destination,
2032 @NonNull @CallbackExecutor Executor executor,
2033 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002034 ParcelFileDescriptor dup;
2035 try {
junyulaic4fb2482019-03-27 11:00:37 +08002036 // TODO: Consider remove unnecessary dup.
junyulai61143782019-03-04 22:45:36 +08002037 dup = pfd.dup();
2038 } catch (IOException ignored) {
2039 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2040 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002041 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002042 }
2043 return new NattSocketKeepalive(mService, network, dup,
2044 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulaia86defc2018-12-27 17:25:29 +08002045 }
2046
2047 /**
junyulaic7ea1242019-01-08 20:04:33 +08002048 * Request that keepalives be started on a TCP socket.
2049 * The socket must be established.
2050 *
2051 * @param network The {@link Network} the socket is on.
2052 * @param socket The socket that needs to be kept alive.
2053 * @param executor The executor on which callback will be invoked. This implementation assumes
2054 * the provided {@link Executor} runs the callbacks in sequence with no
2055 * concurrency. Failing this, no guarantee of correctness can be made. It is
2056 * the responsibility of the caller to ensure the executor provides this
2057 * guarantee. A simple way of creating such an executor is with the standard
2058 * tool {@code Executors.newSingleThreadExecutor}.
2059 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2060 * changes. Must be extended by applications that use this API.
2061 *
2062 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2063 * given socket.
2064 * @hide
2065 */
2066 @SystemApi
2067 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai61143782019-03-04 22:45:36 +08002068 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulaic7ea1242019-01-08 20:04:33 +08002069 @NonNull Socket socket,
2070 @NonNull Executor executor,
2071 @NonNull Callback callback) {
junyulai61143782019-03-04 22:45:36 +08002072 ParcelFileDescriptor dup;
2073 try {
2074 dup = ParcelFileDescriptor.fromSocket(socket);
2075 } catch (UncheckedIOException ignored) {
2076 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2077 // ERROR_INVALID_SOCKET.
Chiachang Wangc5f86f42021-01-15 11:06:21 +08002078 dup = createInvalidFd();
junyulai61143782019-03-04 22:45:36 +08002079 }
2080 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulaic7ea1242019-01-08 20:04:33 +08002081 }
2082
2083 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002084 * Ensure that a network route exists to deliver traffic to the specified
2085 * host via the specified network interface. An attempt to add a route that
2086 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002087 *
2088 * <p>This method requires the caller to hold either the
2089 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2090 * or the ability to modify system settings as determined by
2091 * {@link android.provider.Settings.System#canWrite}.</p>
2092 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002093 * @param networkType the type of the network over which traffic to the specified
2094 * host is to be routed
2095 * @param hostAddress the IP address of the host to which the route is desired
2096 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002097 *
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002098 * @deprecated Deprecated in favor of the
2099 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2100 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackbornc16abda2015-07-31 10:35:34 -07002101 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002102 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti7cb18342016-12-09 18:39:30 +09002103 * @removed
The Android Open Source Project28527d22009-03-03 19:31:44 -08002104 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002105 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002106 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002107 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002108 }
2109
2110 /**
2111 * Ensure that a network route exists to deliver traffic to the specified
2112 * host via the specified network interface. An attempt to add a route that
2113 * already exists is ignored, but treated as successful.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002114 *
2115 * <p>This method requires the caller to hold either the
2116 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2117 * or the ability to modify system settings as determined by
2118 * {@link android.provider.Settings.System#canWrite}.</p>
2119 *
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002120 * @param networkType the type of the network over which traffic to the specified
2121 * host is to be routed
2122 * @param hostAddress the IP address of the host to which the route is desired
2123 * @return {@code true} on success, {@code false} on failure
2124 * @hide
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07002125 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09002126 * {@link #bindProcessToNetwork} API.
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002127 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002128 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002129 @UnsupportedAppUsage
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07002130 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002131 checkLegacyRoutingApiAccess();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002132 try {
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002133 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2134 mContext.getOpPackageName(), getAttributionTag());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002135 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002136 throw e.rethrowFromSystemServer();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 }
2138 }
2139
2140 /**
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002141 * @return the context's attribution tag
2142 */
2143 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2144 private @Nullable String getAttributionTag() {
2145 return null;
2146 }
2147
2148 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002149 * Returns the value of the setting for background data usage. If false,
2150 * applications should not use the network if the application is not in the
2151 * foreground. Developers should respect this setting, and check the value
2152 * of this before performing any background data operations.
2153 * <p>
2154 * All applications that have background services that use the network
2155 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002156 * <p>
Scott Main50589142011-10-06 18:32:43 -07002157 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002158 * background data depends on several combined factors, and this method will
2159 * always return {@code true}. Instead, when background data is unavailable,
2160 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang96567052010-08-11 14:54:43 -07002161 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002162 * @return Whether background data usage is allowed.
2163 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002164 @Deprecated
The Android Open Source Project28527d22009-03-03 19:31:44 -08002165 public boolean getBackgroundDataSetting() {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002166 // assume that background data is allowed; final authority is
2167 // NetworkInfo which may be blocked.
2168 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002169 }
2170
2171 /**
2172 * Sets the value of the setting for background data usage.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002173 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 * @param allowBackgroundData Whether an application should use data while
2175 * it is in the background.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002176 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08002177 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2178 * @see #getBackgroundDataSetting()
2179 * @hide
2180 */
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002181 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002182 @UnsupportedAppUsage
The Android Open Source Project28527d22009-03-03 19:31:44 -08002183 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey39c01eb2011-08-16 14:37:57 -07002184 // ignored
The Android Open Source Project28527d22009-03-03 19:31:44 -08002185 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002186
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002187 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002188 * @hide
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002189 * @deprecated Talk to TelephonyManager directly
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002190 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002191 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002192 @UnsupportedAppUsage
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002193 public boolean getMobileDataEnabled() {
Meng Wang91311c02019-11-18 17:10:00 -08002194 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2195 if (tm != null) {
2196 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2197 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2198 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2199 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2200 + " retVal=" + retVal);
2201 return retVal;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002202 }
Wink Saville02eb35c2014-12-05 11:10:30 -08002203 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwalt3d6c9582014-05-21 20:04:36 -07002204 return false;
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08002205 }
2206
The Android Open Source Project28527d22009-03-03 19:31:44 -08002207 /**
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002208 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002209 * to find out when the system default network has gone in to a high power state.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002210 */
2211 public interface OnNetworkActiveListener {
2212 /**
2213 * Called on the main thread of the process to report that the current data network
2214 * has become active, and it is now a good time to perform any pending network
2215 * operations. Note that this listener only tells you when the network becomes
2216 * active; if at any other time you want to know whether it is active (and thus okay
2217 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002218 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002219 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002220 void onNetworkActive();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002221 }
2222
2223 private INetworkManagementService getNetworkManagementService() {
2224 synchronized (this) {
2225 if (mNMService != null) {
2226 return mNMService;
2227 }
2228 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2229 mNMService = INetworkManagementService.Stub.asInterface(b);
2230 return mNMService;
2231 }
2232 }
2233
2234 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean73d9db72018-06-04 16:52:49 +09002235 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002236
2237 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002238 * Start listening to reports when the system's default data network is active, meaning it is
2239 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2240 * to determine the current state of the system's default network after registering the
2241 * listener.
2242 * <p>
2243 * If the process default network has been set with
Paul Jensen895c3942015-03-10 10:54:12 -04002244 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002245 * reflect the process's default, but the system default.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002246 *
2247 * @param l The listener to be told when the network is active.
2248 */
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002249 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002250 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2251 @Override
2252 public void onNetworkActive() throws RemoteException {
2253 l.onNetworkActive();
2254 }
2255 };
2256
2257 try {
2258 getNetworkManagementService().registerNetworkActivityListener(rl);
2259 mNetworkActivityListeners.put(l, rl);
2260 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002261 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002262 }
2263 }
2264
2265 /**
2266 * Remove network active listener previously registered with
Robert Greenwalt2e4731f2014-09-04 16:44:35 -07002267 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002268 *
2269 * @param l Previously registered listener.
2270 */
Chalard Jean42a9c292019-01-07 19:26:34 +09002271 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002272 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichiff4bf602017-05-09 15:19:01 +09002273 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002274 try {
2275 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2276 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002277 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002278 }
2279 }
2280
2281 /**
2282 * Return whether the data network is currently active. An active network means that
2283 * it is currently in a high power state for performing data transmission. On some
2284 * types of networks, it may be expensive to move and stay in such a state, so it is
2285 * more power efficient to batch network traffic together when the radio is already in
2286 * this state. This method tells you whether right now is currently a good time to
2287 * initiate network traffic, as the network is already active.
2288 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07002289 public boolean isDefaultNetworkActive() {
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002290 try {
2291 return getNetworkManagementService().isNetworkActive();
2292 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07002293 throw e.rethrowFromSystemServer();
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002294 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002295 }
2296
2297 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002298 * {@hide}
2299 */
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09002300 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichi45a49542017-03-06 09:17:06 +09002301 mContext = Preconditions.checkNotNull(context, "missing context");
2302 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Amos Bianchiddadca42020-03-04 11:07:38 -08002303 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensen12131352014-12-10 15:12:18 -05002304 sInstance = this;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002305 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002306
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002307 /** {@hide} */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002308 @UnsupportedAppUsage
Jeff Sharkey2d9e5a52012-04-04 20:40:58 -07002309 public static ConnectivityManager from(Context context) {
2310 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2311 }
2312
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09002313 /** @hide */
2314 public NetworkRequest getDefaultRequest() {
2315 try {
2316 // This is not racy as the default request is final in ConnectivityService.
2317 return mService.getDefaultRequest();
2318 } catch (RemoteException e) {
2319 throw e.rethrowFromSystemServer();
2320 }
2321 }
2322
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09002323 /* TODO: These permissions checks don't belong in client-side code. Move them to
2324 * services.jar, possibly in com.android.server.net. */
2325
2326 /** {@hide} */
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002327 public static final void enforceChangePermission(Context context,
2328 String callingPkg, String callingAttributionTag) {
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002329 int uid = Binder.getCallingUid();
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002330 checkAndNoteChangeNetworkStateOperation(context, uid, callingPkg,
2331 callingAttributionTag, true /* throwException */);
2332 }
2333
2334 /**
2335 * Check if the package is a allowed to change the network state. This also accounts that such
2336 * an access happened.
2337 *
2338 * @return {@code true} iff the package is allowed to change the network state.
2339 */
2340 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2341 private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context,
2342 int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag,
2343 boolean throwException) {
2344 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, callingPackage,
2345 throwException);
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002346 }
2347
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002348 /**
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002349 * Check if the package is a allowed to write settings. This also accounts that such an access
2350 * happened.
2351 *
2352 * @return {@code true} iff the package is allowed to write settings.
2353 */
2354 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2355 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2356 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2357 boolean throwException) {
2358 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
2359 throwException);
2360 }
2361
2362 /**
Paul Jensen12131352014-12-10 15:12:18 -05002363 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2364 * situations where a Context pointer is unavailable.
2365 * @hide
2366 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002367 @Deprecated
Paul Jensen895c3942015-03-10 10:54:12 -04002368 static ConnectivityManager getInstanceOrNull() {
2369 return sInstance;
2370 }
2371
2372 /**
2373 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2374 * situations where a Context pointer is unavailable.
2375 * @hide
2376 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07002377 @Deprecated
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002378 @UnsupportedAppUsage
Paul Jensen895c3942015-03-10 10:54:12 -04002379 private static ConnectivityManager getInstance() {
2380 if (getInstanceOrNull() == null) {
Paul Jensen12131352014-12-10 15:12:18 -05002381 throw new IllegalStateException("No ConnectivityManager yet constructed");
2382 }
Paul Jensen895c3942015-03-10 10:54:12 -04002383 return getInstanceOrNull();
Paul Jensen12131352014-12-10 15:12:18 -05002384 }
2385
2386 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002387 * Get the set of tetherable, available interfaces. This list is limited by
2388 * device configuration and current interface existence.
2389 *
2390 * @return an array of 0 or more Strings of tetherable interface names.
2391 *
markchieneeea0be2020-01-21 13:11:06 +08002392 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002393 * {@hide}
2394 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002395 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002396 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002397 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002398 public String[] getTetherableIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002399 return mTetheringManager.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002400 }
2401
2402 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002403 * Get the set of tethered interfaces.
2404 *
2405 * @return an array of 0 or more String of currently tethered interface names.
2406 *
markchieneeea0be2020-01-21 13:11:06 +08002407 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002408 * {@hide}
2409 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002410 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002411 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002412 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002413 public String[] getTetheredIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002414 return mTetheringManager.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002415 }
2416
2417 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002418 * Get the set of interface names which attempted to tether but
2419 * failed. Re-attempting to tether may cause them to reset to the Tethered
2420 * state. Alternatively, causing the interface to be destroyed and recreated
2421 * may cause them to reset to the available state.
2422 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2423 * information on the cause of the errors.
2424 *
2425 * @return an array of 0 or more String indicating the interface names
2426 * which failed to tether.
2427 *
markchieneeea0be2020-01-21 13:11:06 +08002428 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002429 * {@hide}
2430 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002431 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002432 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002433 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002434 public String[] getTetheringErroredIfaces() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002435 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002436 }
2437
2438 /**
Robert Greenwalta75c4652014-06-23 14:53:42 -07002439 * Get the set of tethered dhcp ranges.
2440 *
markchien218230f2020-02-14 11:55:48 +08002441 * @deprecated This method is not supported.
2442 * TODO: remove this function when all of clients are removed.
Robert Greenwalta75c4652014-06-23 14:53:42 -07002443 * {@hide}
2444 */
paulhud70b7dd2019-08-12 16:25:11 +08002445 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchieneeea0be2020-01-21 13:11:06 +08002446 @Deprecated
Robert Greenwalta75c4652014-06-23 14:53:42 -07002447 public String[] getTetheredDhcpRanges() {
markchien218230f2020-02-14 11:55:48 +08002448 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalta75c4652014-06-23 14:53:42 -07002449 }
2450
2451 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002452 * Attempt to tether the named interface. This will setup a dhcp server
2453 * on the interface, forward and NAT IP packets and forward DNS requests
2454 * to the best active upstream network interface. Note that if no upstream
2455 * IP network interface is available, dhcp will still run and traffic will be
2456 * allowed between the tethered devices and this device, though upstream net
2457 * access will of course fail until an upstream network interface becomes
2458 * active.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002459 *
2460 * <p>This method requires the caller to hold either the
2461 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2462 * or the ability to modify system settings as determined by
2463 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002464 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002465 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2466 * and WifiStateMachine which need direct access. All other clients should use
2467 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2468 * logic.</p>
2469 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002470 * @param iface the interface name to tether.
2471 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiencc1bc1b2020-01-20 19:31:56 +08002472 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002473 *
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002474 * {@hide}
2475 */
Mathew Inwood5a09a712020-11-04 09:29:36 +00002476 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchiencc1bc1b2020-01-20 19:31:56 +08002477 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002478 public int tether(String iface) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002479 return mTetheringManager.tether(iface);
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002480 }
2481
2482 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002483 * Stop tethering the named interface.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002484 *
2485 * <p>This method requires the caller to hold either the
2486 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2487 * or the ability to modify system settings as determined by
2488 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002489 *
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002490 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2491 * and WifiStateMachine which need direct access. All other clients should use
2492 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2493 * logic.</p>
2494 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002495 * @param iface the interface name to untether.
2496 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2497 *
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002498 * {@hide}
2499 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002500 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002501 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002502 public int untether(String iface) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002503 return mTetheringManager.untether(iface);
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002504 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002505
2506 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002507 * Check if the device allows for tethering. It may be disabled via
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002508 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt26744a52013-02-15 10:56:35 -08002509 * due to device configuration.
2510 *
Chalard Jean4e1bb722017-09-26 15:45:18 +09002511 * <p>If this app does not have permission to use this API, it will always
2512 * return false rather than throw an exception.</p>
2513 *
2514 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2515 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2516 *
2517 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2518 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2519 *
Robert Greenwalt26744a52013-02-15 10:56:35 -08002520 * @return a boolean - {@code true} indicating Tethering is supported.
2521 *
markchieneeea0be2020-01-21 13:11:06 +08002522 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002523 * {@hide}
2524 */
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002525 @SystemApi
Chalard Jean4e1bb722017-09-26 15:45:18 +09002526 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2527 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002528 public boolean isTetheringSupported() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002529 return mTetheringManager.isTetheringSupported();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002530 }
2531
2532 /**
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002533 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchiencc1bc1b2020-01-20 19:31:56 +08002534 *
2535 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002536 * @hide
2537 */
2538 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002539 @Deprecated
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002540 public static abstract class OnStartTetheringCallback {
2541 /**
2542 * Called when tethering has been successfully started.
2543 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002544 public void onTetheringStarted() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002545
2546 /**
2547 * Called when starting tethering failed.
2548 */
Chalard Jean73d9db72018-06-04 16:52:49 +09002549 public void onTetheringFailed() {}
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002550 }
2551
2552 /**
2553 * Convenient overload for
2554 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2555 * handler to run on the current thread's {@link Looper}.
markchiencc1bc1b2020-01-20 19:31:56 +08002556 *
2557 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002558 * @hide
2559 */
2560 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002561 @Deprecated
Udam Saini15072332017-06-07 12:06:28 -07002562 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002563 public void startTethering(int type, boolean showProvisioningUi,
2564 final OnStartTetheringCallback callback) {
2565 startTethering(type, showProvisioningUi, callback, null);
2566 }
2567
2568 /**
2569 * Runs tether provisioning for the given type if needed and then starts tethering if
2570 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2571 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2572 * schedules tether provisioning re-checks if appropriate.
2573 *
2574 * @param type The type of tethering to start. Must be one of
2575 * {@link ConnectivityManager.TETHERING_WIFI},
2576 * {@link ConnectivityManager.TETHERING_USB}, or
2577 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2578 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2579 * is one. This should be true the first time this function is called and also any time
2580 * the user can see this UI. It gives users information from their carrier about the
2581 * check failing and how they can sign up for tethering if possible.
2582 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2583 * of the result of trying to tether.
2584 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchiencc1bc1b2020-01-20 19:31:56 +08002585 *
2586 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002587 * @hide
2588 */
2589 @SystemApi
markchiencc1bc1b2020-01-20 19:31:56 +08002590 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002591 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002592 public void startTethering(int type, boolean showProvisioningUi,
2593 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichi45a49542017-03-06 09:17:06 +09002594 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein49a57952016-03-12 16:29:54 -08002595
markchiencc1bc1b2020-01-20 19:31:56 +08002596 final Executor executor = new Executor() {
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002597 @Override
markchiencc1bc1b2020-01-20 19:31:56 +08002598 public void execute(Runnable command) {
2599 if (handler == null) {
2600 command.run();
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002601 } else {
markchiencc1bc1b2020-01-20 19:31:56 +08002602 handler.post(command);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002603 }
2604 }
2605 };
Jeremy Klein49a57952016-03-12 16:29:54 -08002606
markchiencc1bc1b2020-01-20 19:31:56 +08002607 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2608 @Override
2609 public void onTetheringStarted() {
2610 callback.onTetheringStarted();
2611 }
2612
2613 @Override
markchien19336c22020-03-19 13:37:43 +08002614 public void onTetheringFailed(final int error) {
markchiencc1bc1b2020-01-20 19:31:56 +08002615 callback.onTetheringFailed();
2616 }
2617 };
2618
2619 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien19336c22020-03-19 13:37:43 +08002620 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchiencc1bc1b2020-01-20 19:31:56 +08002621
Amos Bianchiddadca42020-03-04 11:07:38 -08002622 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002623 }
2624
2625 /**
2626 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2627 * applicable.
2628 *
2629 * @param type The type of tethering to stop. Must be one of
2630 * {@link ConnectivityManager.TETHERING_WIFI},
2631 * {@link ConnectivityManager.TETHERING_USB}, or
2632 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchieneeea0be2020-01-21 13:11:06 +08002633 *
2634 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002635 * @hide
2636 */
2637 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002638 @Deprecated
Jeff Sharkeyb8c73032017-06-02 17:36:26 -06002639 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002640 public void stopTethering(int type) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002641 mTetheringManager.stopTethering(type);
Jeremy Klein9a36ec82016-01-22 14:11:45 -08002642 }
2643
2644 /**
markchiena005c992019-02-27 14:56:11 +08002645 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2646 * upstream status.
2647 *
Nathan Haroldbbb48c62020-01-23 18:03:46 -08002648 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchieneeea0be2020-01-21 13:11:06 +08002649 * @hide
markchiena005c992019-02-27 14:56:11 +08002650 */
2651 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002652 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002653 public abstract static class OnTetheringEventCallback {
2654
2655 /**
2656 * Called when tethering upstream changed. This can be called multiple times and can be
2657 * called any time.
2658 *
2659 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2660 * have any upstream.
2661 */
2662 public void onUpstreamChanged(@Nullable Network network) {}
2663 }
2664
markchieneeea0be2020-01-21 13:11:06 +08002665 @GuardedBy("mTetheringEventCallbacks")
2666 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2667 mTetheringEventCallbacks = new ArrayMap<>();
2668
markchiena005c992019-02-27 14:56:11 +08002669 /**
2670 * Start listening to tethering change events. Any new added callback will receive the last
markchiend378cd32019-04-03 10:43:09 +08002671 * tethering status right away. If callback is registered when tethering has no upstream or
markchiena005c992019-02-27 14:56:11 +08002672 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2673 * with a null argument. The same callback object cannot be registered twice.
2674 *
2675 * @param executor the executor on which callback will be invoked.
2676 * @param callback the callback to be called when tethering has change events.
markchieneeea0be2020-01-21 13:11:06 +08002677 *
Nathan Haroldbbb48c62020-01-23 18:03:46 -08002678 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002679 * @hide
2680 */
2681 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002682 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002683 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2684 public void registerTetheringEventCallback(
2685 @NonNull @CallbackExecutor Executor executor,
2686 @NonNull final OnTetheringEventCallback callback) {
2687 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2688
markchieneeea0be2020-01-21 13:11:06 +08002689 final TetheringEventCallback tetherCallback =
2690 new TetheringEventCallback() {
2691 @Override
2692 public void onUpstreamChanged(@Nullable Network network) {
2693 callback.onUpstreamChanged(network);
2694 }
2695 };
2696
2697 synchronized (mTetheringEventCallbacks) {
2698 mTetheringEventCallbacks.put(callback, tetherCallback);
Amos Bianchiddadca42020-03-04 11:07:38 -08002699 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchieneeea0be2020-01-21 13:11:06 +08002700 }
markchiena005c992019-02-27 14:56:11 +08002701 }
2702
2703 /**
2704 * Remove tethering event callback previously registered with
2705 * {@link #registerTetheringEventCallback}.
2706 *
2707 * @param callback previously registered callback.
markchieneeea0be2020-01-21 13:11:06 +08002708 *
2709 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchiena005c992019-02-27 14:56:11 +08002710 * @hide
2711 */
2712 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002713 @Deprecated
markchiena005c992019-02-27 14:56:11 +08002714 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2715 public void unregisterTetheringEventCallback(
2716 @NonNull final OnTetheringEventCallback callback) {
markchieneeea0be2020-01-21 13:11:06 +08002717 Objects.requireNonNull(callback, "The callback must be non-null");
2718 synchronized (mTetheringEventCallbacks) {
2719 final TetheringEventCallback tetherCallback =
2720 mTetheringEventCallbacks.remove(callback);
Amos Bianchiddadca42020-03-04 11:07:38 -08002721 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchieneeea0be2020-01-21 13:11:06 +08002722 }
markchiena005c992019-02-27 14:56:11 +08002723 }
2724
2725
2726 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002727 * Get the list of regular expressions that define any tetherable
2728 * USB network interfaces. If USB tethering is not supported by the
2729 * device, this list should be empty.
2730 *
2731 * @return an array of 0 or more regular expression Strings defining
2732 * what interfaces are considered tetherable usb interfaces.
2733 *
markchieneeea0be2020-01-21 13:11:06 +08002734 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002735 * {@hide}
2736 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002737 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002738 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002739 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002740 public String[] getTetherableUsbRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002741 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002742 }
2743
2744 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002745 * Get the list of regular expressions that define any tetherable
2746 * Wifi network interfaces. If Wifi tethering is not supported by the
2747 * device, this list should be empty.
2748 *
2749 * @return an array of 0 or more regular expression Strings defining
2750 * what interfaces are considered tetherable wifi interfaces.
2751 *
markchieneeea0be2020-01-21 13:11:06 +08002752 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002753 * {@hide}
2754 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002755 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002756 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002757 @Deprecated
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002758 public String[] getTetherableWifiRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002759 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002760 }
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002761
Danica Chang96567052010-08-11 14:54:43 -07002762 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002763 * Get the list of regular expressions that define any tetherable
2764 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2765 * device, this list should be empty.
2766 *
2767 * @return an array of 0 or more regular expression Strings defining
2768 * what interfaces are considered tetherable bluetooth interfaces.
2769 *
markchieneeea0be2020-01-21 13:11:06 +08002770 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2771 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang96567052010-08-11 14:54:43 -07002772 * {@hide}
2773 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002774 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002775 @UnsupportedAppUsage
markchieneeea0be2020-01-21 13:11:06 +08002776 @Deprecated
Danica Chang96567052010-08-11 14:54:43 -07002777 public String[] getTetherableBluetoothRegexs() {
Amos Bianchiddadca42020-03-04 11:07:38 -08002778 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang96567052010-08-11 14:54:43 -07002779 }
2780
Mike Lockwooded4a1742011-07-19 13:04:47 -07002781 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002782 * Attempt to both alter the mode of USB and Tethering of USB. A
2783 * utility method to deal with some of the complexity of USB - will
2784 * attempt to switch to Rndis and subsequently tether the resulting
2785 * interface on {@code true} or turn off tethering and switch off
2786 * Rndis on {@code false}.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09002787 *
2788 * <p>This method requires the caller to hold either the
2789 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2790 * or the ability to modify system settings as determined by
2791 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt26744a52013-02-15 10:56:35 -08002792 *
2793 * @param enable a boolean - {@code true} to enable tethering
2794 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiencc1bc1b2020-01-20 19:31:56 +08002795 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt26744a52013-02-15 10:56:35 -08002796 *
Mike Lockwooded4a1742011-07-19 13:04:47 -07002797 * {@hide}
2798 */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01002799 @UnsupportedAppUsage
markchiencc1bc1b2020-01-20 19:31:56 +08002800 @Deprecated
Mike Lockwooded4a1742011-07-19 13:04:47 -07002801 public int setUsbTethering(boolean enable) {
Amos Bianchiddadca42020-03-04 11:07:38 -08002802 return mTetheringManager.setUsbTethering(enable);
Mike Lockwooded4a1742011-07-19 13:04:47 -07002803 }
2804
markchieneeea0be2020-01-21 13:11:06 +08002805 /**
2806 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2807 * {@hide}
2808 */
markchien5bd499c2019-01-16 17:44:13 +08002809 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002810 @Deprecated
2811 public static final int TETHER_ERROR_NO_ERROR = TetheringManager.TETHER_ERROR_NO_ERROR;
2812 /**
2813 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2814 * {@hide}
2815 */
2816 @Deprecated
2817 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2818 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2819 /**
2820 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2821 * {@hide}
2822 */
2823 @Deprecated
2824 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2825 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2826 /**
2827 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2828 * {@hide}
2829 */
2830 @Deprecated
2831 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2832 /**
2833 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2834 * {@hide}
2835 */
2836 @Deprecated
2837 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2838 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2839 /**
markchien19336c22020-03-19 13:37:43 +08002840 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002841 * {@hide}
2842 */
2843 @Deprecated
markchien19336c22020-03-19 13:37:43 +08002844 public static final int TETHER_ERROR_MASTER_ERROR =
2845 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002846 /**
2847 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2848 * {@hide}
2849 */
2850 @Deprecated
2851 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2852 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2853 /**
2854 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2855 * {@hide}
2856 */
2857 @Deprecated
2858 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2859 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2860 /**
markchien19336c22020-03-19 13:37:43 +08002861 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002862 * {@hide}
2863 */
2864 @Deprecated
2865 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien19336c22020-03-19 13:37:43 +08002866 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002867 /**
markchien19336c22020-03-19 13:37:43 +08002868 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchieneeea0be2020-01-21 13:11:06 +08002869 * {@hide}
2870 */
2871 @Deprecated
2872 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien19336c22020-03-19 13:37:43 +08002873 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchieneeea0be2020-01-21 13:11:06 +08002874 /**
2875 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2876 * {@hide}
2877 */
2878 @Deprecated
2879 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2880 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2881 /**
markchien19336c22020-03-19 13:37:43 +08002882 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchieneeea0be2020-01-21 13:11:06 +08002883 * {@hide}
2884 */
markchien5bd499c2019-01-16 17:44:13 +08002885 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002886 @Deprecated
2887 public static final int TETHER_ERROR_PROVISION_FAILED =
markchien19336c22020-03-19 13:37:43 +08002888 TetheringManager.TETHER_ERROR_PROVISIONING_FAILED;
markchieneeea0be2020-01-21 13:11:06 +08002889 /**
2890 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2891 * {@hide}
2892 */
2893 @Deprecated
2894 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2895 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2896 /**
2897 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2898 * {@hide}
2899 */
markchien5bd499c2019-01-16 17:44:13 +08002900 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002901 @Deprecated
2902 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN =
2903 TetheringManager.TETHER_ERROR_ENTITLEMENT_UNKNOWN;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002904
2905 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08002906 * Get a more detailed error code after a Tethering or Untethering
2907 * request asynchronously failed.
2908 *
2909 * @param iface The name of the interface of interest
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002910 * @return error The error code of the last error tethering or untethering the named
2911 * interface
Robert Greenwalt26744a52013-02-15 10:56:35 -08002912 *
markchieneeea0be2020-01-21 13:11:06 +08002913 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002914 * {@hide}
2915 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06002916 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwood5a09a712020-11-04 09:29:36 +00002917 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
markchieneeea0be2020-01-21 13:11:06 +08002918 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002919 public int getLastTetherError(String iface) {
markchien19336c22020-03-19 13:37:43 +08002920 int error = mTetheringManager.getLastTetherError(iface);
2921 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2922 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2923 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2924 // instead.
2925 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2926 }
2927 return error;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002928 }
2929
markchiendd41c822019-03-06 16:25:00 +08002930 /** @hide */
2931 @Retention(RetentionPolicy.SOURCE)
2932 @IntDef(value = {
2933 TETHER_ERROR_NO_ERROR,
2934 TETHER_ERROR_PROVISION_FAILED,
2935 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2936 })
2937 public @interface EntitlementResultCode {
2938 }
2939
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002940 /**
markchiendd41c822019-03-06 16:25:00 +08002941 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchien5bd499c2019-01-16 17:44:13 +08002942 * entitlement succeeded.
markchieneeea0be2020-01-21 13:11:06 +08002943 *
2944 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchien5bd499c2019-01-16 17:44:13 +08002945 * @hide
2946 */
2947 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002948 @Deprecated
markchiendd41c822019-03-06 16:25:00 +08002949 public interface OnTetheringEntitlementResultListener {
2950 /**
2951 * Called to notify entitlement result.
2952 *
2953 * @param resultCode an int value of entitlement result. It may be one of
2954 * {@link #TETHER_ERROR_NO_ERROR},
2955 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2956 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2957 */
Jeremy Kleina9aad902019-03-12 13:32:08 -07002958 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchiendd41c822019-03-06 16:25:00 +08002959 }
2960
2961 /**
markchien5bd499c2019-01-16 17:44:13 +08002962 * Get the last value of the entitlement check on this downstream. If the cached value is
2963 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2964 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2965 * guaranteed that the UI-based entitlement check will complete in any specific time period
2966 * and may in fact never complete. Any successful entitlement check the platform performs for
2967 * any reason will update the cached value.
2968 *
2969 * @param type the downstream type of tethering. Must be one of
2970 * {@link #TETHERING_WIFI},
2971 * {@link #TETHERING_USB}, or
2972 * {@link #TETHERING_BLUETOOTH}.
2973 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchiendd41c822019-03-06 16:25:00 +08002974 * @param executor the executor on which callback will be invoked.
2975 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2976 * notify the caller of the result of entitlement check. The listener may be called zero
2977 * or one time.
markchieneeea0be2020-01-21 13:11:06 +08002978 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchien5bd499c2019-01-16 17:44:13 +08002979 * {@hide}
2980 */
2981 @SystemApi
markchieneeea0be2020-01-21 13:11:06 +08002982 @Deprecated
markchien5bd499c2019-01-16 17:44:13 +08002983 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchiendd41c822019-03-06 16:25:00 +08002984 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2985 @NonNull @CallbackExecutor Executor executor,
2986 @NonNull final OnTetheringEntitlementResultListener listener) {
2987 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2988 ResultReceiver wrappedListener = new ResultReceiver(null) {
2989 @Override
2990 protected void onReceiveResult(int resultCode, Bundle resultData) {
2991 Binder.withCleanCallingIdentity(() ->
2992 executor.execute(() -> {
Jeremy Kleina9aad902019-03-12 13:32:08 -07002993 listener.onTetheringEntitlementResult(resultCode);
markchiendd41c822019-03-06 16:25:00 +08002994 }));
2995 }
2996 };
2997
Amos Bianchiddadca42020-03-04 11:07:38 -08002998 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchien4f949812019-12-16 20:15:20 +08002999 showEntitlementUi);
markchiendd41c822019-03-06 16:25:00 +08003000 }
3001
3002 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003003 * Report network connectivity status. This is currently used only
3004 * to alter status bar UI.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003005 * <p>This method requires the caller to hold the permission
3006 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003007 *
Robert Greenwalt986c7412010-09-08 15:24:47 -07003008 * @param networkType The type of network you want to report on
3009 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean5acb7b72018-03-08 13:54:53 +09003010 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwalt986c7412010-09-08 15:24:47 -07003011 * {@hide}
3012 */
3013 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003014 printStackTrace();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003015 try {
3016 mService.reportInetCondition(networkType, percentage);
3017 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003018 throw e.rethrowFromSystemServer();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003019 }
3020 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003021
3022 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003023 * Report a problem network to the framework. This provides a hint to the system
Ye Wen849c72a2014-07-21 14:19:01 -07003024 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003025 * the framework to re-evaluate network connectivity and/or switch to another
3026 * network.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003027 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003028 * @param network The {@link Network} the application was attempting to use
3029 * or {@code null} to indicate the current default network.
Paul Jensen7aac1b32015-04-07 12:43:13 -04003030 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3031 * working and non-working connectivity.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003032 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003033 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09003034 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003035 printStackTrace();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003036 try {
Paul Jensen7aac1b32015-04-07 12:43:13 -04003037 // One of these will be ignored because it matches system's current state.
3038 // The other will trigger the necessary reevaluation.
3039 mService.reportNetworkConnectivity(network, true);
3040 mService.reportNetworkConnectivity(network, false);
3041 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003042 throw e.rethrowFromSystemServer();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003043 }
3044 }
3045
3046 /**
3047 * Report to the framework whether a network has working connectivity.
3048 * This provides a hint to the system that a particular network is providing
3049 * working connectivity or not. In response the framework may re-evaluate
3050 * the network's connectivity and might take further action thereafter.
3051 *
3052 * @param network The {@link Network} the application was attempting to use
3053 * or {@code null} to indicate the current default network.
3054 * @param hasConnectivity {@code true} if the application was able to successfully access the
3055 * Internet using {@code network} or {@code false} if not.
3056 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003057 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003058 printStackTrace();
Paul Jensen7aac1b32015-04-07 12:43:13 -04003059 try {
3060 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003061 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003062 throw e.rethrowFromSystemServer();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003063 }
3064 }
3065
3066 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003067 * Set a network-independent global http proxy. This is not normally what you want
3068 * for typical HTTP proxies - they are general network dependent. However if you're
3069 * doing something unusual like general internal filtering this may be useful. On
3070 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen19b3ee72015-05-06 11:10:18 -04003071 *
3072 * @param p A {@link ProxyInfo} object defining the new global
3073 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003074 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003075 */
paulhud70b7dd2019-08-12 16:25:11 +08003076 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk1e3df5d2014-04-25 15:00:09 -04003077 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003078 try {
3079 mService.setGlobalProxy(p);
3080 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003081 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003082 }
3083 }
3084
3085 /**
Robert Greenwalt26744a52013-02-15 10:56:35 -08003086 * Retrieve any network-independent global HTTP proxy.
3087 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003088 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt26744a52013-02-15 10:56:35 -08003089 * if no global HTTP proxy is set.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003090 * @hide
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003091 */
Jason Monk1e3df5d2014-04-25 15:00:09 -04003092 public ProxyInfo getGlobalProxy() {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003093 try {
3094 return mService.getGlobalProxy();
3095 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003096 throw e.rethrowFromSystemServer();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003097 }
3098 }
3099
3100 /**
Paul Jensenfdec88b2015-05-06 07:32:40 -04003101 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3102 * network-specific HTTP proxy. If {@code network} is null, the
3103 * network-specific proxy returned is the proxy of the default active
3104 * network.
3105 *
3106 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3107 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3108 * or when {@code network} is {@code null},
3109 * the {@code ProxyInfo} for the default active network. Returns
3110 * {@code null} when no proxy applies or the caller doesn't have
3111 * permission to use {@code network}.
3112 * @hide
3113 */
3114 public ProxyInfo getProxyForNetwork(Network network) {
3115 try {
3116 return mService.getProxyForNetwork(network);
3117 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003118 throw e.rethrowFromSystemServer();
Paul Jensenfdec88b2015-05-06 07:32:40 -04003119 }
3120 }
3121
3122 /**
Paul Jensen12131352014-12-10 15:12:18 -05003123 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3124 * otherwise if this process is bound to a {@link Network} using
Paul Jensen895c3942015-03-10 10:54:12 -04003125 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensen12131352014-12-10 15:12:18 -05003126 * the default network's proxy is returned.
Robert Greenwalt26744a52013-02-15 10:56:35 -08003127 *
Jason Monk1e3df5d2014-04-25 15:00:09 -04003128 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt26744a52013-02-15 10:56:35 -08003129 * HTTP proxy is active.
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003130 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003131 @Nullable
Paul Jensen12131352014-12-10 15:12:18 -05003132 public ProxyInfo getDefaultProxy() {
Paul Jensenfdec88b2015-05-06 07:32:40 -04003133 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003134 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07003135
3136 /**
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003137 * Returns true if the hardware supports the given network type
3138 * else it returns false. This doesn't indicate we have coverage
3139 * or are authorized onto a network, just whether or not the
Robert Greenwalt26744a52013-02-15 10:56:35 -08003140 * hardware supports it. For example a GSM phone without a SIM
3141 * should still return {@code true} for mobile data, but a wifi only
3142 * tablet would return {@code false}.
3143 *
3144 * @param networkType The network type we'd like to check
3145 * @return {@code true} if supported, else {@code false}
Chalard Jean5acb7b72018-03-08 13:54:53 +09003146 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003147 * @hide
3148 */
Chalard Jean5acb7b72018-03-08 13:54:53 +09003149 @Deprecated
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003150 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeanaa91c9d2019-04-09 15:46:21 +09003151 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003152 public boolean isNetworkSupported(int networkType) {
3153 try {
3154 return mService.isNetworkSupported(networkType);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003155 } catch (RemoteException e) {
3156 throw e.rethrowFromSystemServer();
3157 }
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003158 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003159
3160 /**
3161 * Returns if the currently active data network is metered. A network is
3162 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt26744a52013-02-15 10:56:35 -08003163 * that connection due to monetary costs, data limitations or
3164 * battery/performance issues. You should check this before doing large
3165 * data transfers, and warn the user or delay the operation until another
3166 * network is available.
3167 *
3168 * @return {@code true} if large transfers should be avoided, otherwise
3169 * {@code false}.
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003170 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06003171 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003172 public boolean isActiveNetworkMetered() {
3173 try {
3174 return mService.isActiveNetworkMetered();
3175 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003176 throw e.rethrowFromSystemServer();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003177 }
3178 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003179
Robert Greenwalt26744a52013-02-15 10:56:35 -08003180 /**
3181 * If the LockdownVpn mechanism is enabled, updates the vpn
3182 * with a reload of its profile.
3183 *
3184 * @return a boolean with {@code} indicating success
3185 *
3186 * <p>This method can only be called by the system UID
3187 * {@hide}
3188 */
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003189 public boolean updateLockdownVpn() {
3190 try {
3191 return mService.updateLockdownVpn();
3192 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003193 throw e.rethrowFromSystemServer();
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003194 }
3195 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07003196
3197 /**
Sarah Chincf44f2f2020-11-25 12:15:14 -08003198 * Set sign in error notification to visible or invisible
Wink Saville89c87b92013-08-29 08:55:16 -07003199 *
Sarah Chincf44f2f2020-11-25 12:15:14 -08003200 * @hide
Paul Jensena8e6dc62015-03-18 12:23:02 -04003201 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville89c87b92013-08-29 08:55:16 -07003202 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07003203 @Deprecated
Wink Saville89c87b92013-08-29 08:55:16 -07003204 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04003205 String action) {
Wink Saville89c87b92013-08-29 08:55:16 -07003206 try {
Paul Jensen82c7e422014-09-15 15:59:36 -04003207 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville89c87b92013-08-29 08:55:16 -07003208 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003209 throw e.rethrowFromSystemServer();
Wink Saville89c87b92013-08-29 08:55:16 -07003210 }
3211 }
Yuhao Zheng15019892013-09-09 17:00:04 -07003212
3213 /**
3214 * Set the value for enabling/disabling airplane mode
3215 *
3216 * @param enable whether to enable airplane mode or not
3217 *
Yuhao Zheng15019892013-09-09 17:00:04 -07003218 * @hide
3219 */
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003220 @RequiresPermission(anyOf = {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01003221 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittic4d01862018-10-09 18:55:11 +09003222 android.Manifest.permission.NETWORK_SETTINGS,
3223 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3224 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti272a77d2018-10-09 18:50:32 +09003225 @SystemApi
Yuhao Zheng15019892013-09-09 17:00:04 -07003226 public void setAirplaneMode(boolean enable) {
3227 try {
3228 mService.setAirplaneMode(enable);
3229 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003230 throw e.rethrowFromSystemServer();
Yuhao Zheng15019892013-09-09 17:00:04 -07003231 }
3232 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003233
Chalard Jean44689aa2018-05-02 21:14:54 +09003234 /** {@hide} - returns the factory serial number */
Mathew Inwood0b8f8612018-08-08 14:52:47 +01003235 @UnsupportedAppUsage
paulhu44939832020-03-04 09:43:41 +08003236 @RequiresPermission(anyOf = {
3237 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3238 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean44689aa2018-05-02 21:14:54 +09003239 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalt948aea52014-04-11 15:53:27 -07003240 try {
Chalard Jean44689aa2018-05-02 21:14:54 +09003241 return mService.registerNetworkFactory(messenger, name);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003242 } catch (RemoteException e) {
3243 throw e.rethrowFromSystemServer();
3244 }
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07003245 }
3246
3247 /** {@hide} */
Mathew Inwoodac5968e2018-12-20 15:30:45 +00003248 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
paulhu44939832020-03-04 09:43:41 +08003249 @RequiresPermission(anyOf = {
3250 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3251 android.Manifest.permission.NETWORK_FACTORY})
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07003252 public void unregisterNetworkFactory(Messenger messenger) {
3253 try {
3254 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003255 } catch (RemoteException e) {
3256 throw e.rethrowFromSystemServer();
3257 }
Robert Greenwalt948aea52014-04-11 15:53:27 -07003258 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003259
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003260 /**
3261 * Registers the specified {@link NetworkProvider}.
3262 * Each listener must only be registered once. The listener can be unregistered with
3263 * {@link #unregisterNetworkProvider}.
3264 *
3265 * @param provider the provider to register
3266 * @return the ID of the provider. This ID must be used by the provider when registering
3267 * {@link android.net.NetworkAgent}s.
3268 * @hide
3269 */
3270 @SystemApi
paulhu44939832020-03-04 09:43:41 +08003271 @RequiresPermission(anyOf = {
3272 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3273 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003274 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3275 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003276 throw new IllegalStateException("NetworkProviders can only be registered once");
3277 }
3278
3279 try {
3280 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3281 provider.getName());
3282 provider.setProviderId(providerId);
3283 } catch (RemoteException e) {
3284 throw e.rethrowFromSystemServer();
3285 }
3286 return provider.getProviderId();
3287 }
3288
3289 /**
3290 * Unregisters the specified NetworkProvider.
3291 *
3292 * @param provider the provider to unregister
3293 * @hide
3294 */
3295 @SystemApi
paulhu44939832020-03-04 09:43:41 +08003296 @RequiresPermission(anyOf = {
3297 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3298 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003299 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3300 try {
3301 mService.unregisterNetworkProvider(provider.getMessenger());
3302 } catch (RemoteException e) {
3303 throw e.rethrowFromSystemServer();
3304 }
3305 provider.setProviderId(NetworkProvider.ID_NONE);
3306 }
3307
3308
3309 /** @hide exposed via the NetworkProvider class. */
paulhu44939832020-03-04 09:43:41 +08003310 @RequiresPermission(anyOf = {
3311 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3312 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09003313 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3314 try {
3315 mService.declareNetworkRequestUnfulfillable(request);
3316 } catch (RemoteException e) {
3317 throw e.rethrowFromSystemServer();
3318 }
3319 }
3320
Chalard Jean44689aa2018-05-02 21:14:54 +09003321 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3322 // of dependent changes that would conflict throughout the automerger graph. Having this
3323 // temporarily helps with the process of going through with all these dependent changes across
3324 // the entire tree.
Paul Jensenc2569432015-02-13 14:18:39 -05003325 /**
3326 * @hide
3327 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana973c7a2019-12-13 19:47:12 +09003328 * @return Network corresponding to NetworkAgent.
Paul Jensenc2569432015-02-13 14:18:39 -05003329 */
paulhu44939832020-03-04 09:43:41 +08003330 @RequiresPermission(anyOf = {
3331 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3332 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003333 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colitticf595362020-01-12 22:28:37 +09003334 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003335 return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean44689aa2018-05-02 21:14:54 +09003336 }
3337
3338 /**
3339 * @hide
3340 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana973c7a2019-12-13 19:47:12 +09003341 * @return Network corresponding to NetworkAgent.
Chalard Jean44689aa2018-05-02 21:14:54 +09003342 */
paulhu44939832020-03-04 09:43:41 +08003343 @RequiresPermission(anyOf = {
3344 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3345 android.Manifest.permission.NETWORK_FACTORY})
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003346 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
Lorenzo Colitticf595362020-01-12 22:28:37 +09003347 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003348 try {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003349 return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
Paul Jensenc2569432015-02-13 14:18:39 -05003350 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003351 throw e.rethrowFromSystemServer();
Paul Jensenc2569432015-02-13 14:18:39 -05003352 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003353 }
3354
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003355 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09003356 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3357 * changes. Should be extended by applications wanting notifications.
3358 *
3359 * A {@code NetworkCallback} is registered by calling
3360 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3361 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichi7665a142018-02-07 21:17:43 +09003362 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichi45a49542017-03-06 09:17:06 +09003363 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3364 * A {@code NetworkCallback} should be registered at most once at any time.
3365 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003366 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003367 public static class NetworkCallback {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003368 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003369 * Called when the framework connects to a new network to evaluate whether it satisfies this
3370 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3371 * callback. There is no guarantee that this new network will satisfy any requests, or that
3372 * the network will stay connected for longer than the time necessary to evaluate it.
3373 * <p>
3374 * Most applications <b>should not</b> act on this callback, and should instead use
3375 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3376 * the framework in properly evaluating the network &mdash; for example, an application that
3377 * can automatically log in to a captive portal without user intervention.
3378 *
3379 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colittia04936a2015-06-11 14:27:17 +09003380 *
3381 * @hide
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003382 */
paulhua9a6e2a2019-03-22 16:35:06 +08003383 public void onPreCheck(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003384
3385 /**
Lorenzo Colitticcf82102015-04-24 12:23:24 +09003386 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003387 * This callback may be called more than once if the {@link Network} that is
3388 * satisfying the request changes.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003389 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003390 * @param network The {@link Network} of the satisfying network.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003391 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3392 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai5ab727b2018-08-07 19:50:45 +08003393 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003394 * @hide
3395 */
paulhua9a6e2a2019-03-22 16:35:06 +08003396 public void onAvailable(@NonNull Network network,
3397 @NonNull NetworkCapabilities networkCapabilities,
3398 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003399 // Internally only this method is called when a new network is available, and
3400 // it calls the callback in the same way and order that older versions used
3401 // to call so as not to change the behavior.
3402 onAvailable(network);
3403 if (!networkCapabilities.hasCapability(
3404 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3405 onNetworkSuspended(network);
3406 }
3407 onCapabilitiesChanged(network, networkCapabilities);
3408 onLinkPropertiesChanged(network, linkProperties);
junyulai5ab727b2018-08-07 19:50:45 +08003409 onBlockedStatusChanged(network, blocked);
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003410 }
3411
3412 /**
3413 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003414 *
3415 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3416 * be available at the same time, and onAvailable will be called for each of these as they
3417 * appear.
3418 *
3419 * <p>For callbacks registered with {@link #requestNetwork} and
3420 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3421 * is the new best network for this request and is now tracked by this callback ; this
3422 * callback will no longer receive method calls about other networks that may have been
3423 * passed to this method previously. The previously-best network may have disconnected, or
3424 * it may still be around and the newly-best network may simply be better.
3425 *
3426 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3427 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3428 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3429 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3430 *
3431 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3432 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3433 * this callback as this is prone to race conditions (there is no guarantee the objects
3434 * returned by these methods will be current). Instead, wait for a call to
3435 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3436 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3437 * to be well-ordered with respect to other callbacks.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003438 *
3439 * @param network The {@link Network} of the satisfying network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003440 */
paulhua9a6e2a2019-03-22 16:35:06 +08003441 public void onAvailable(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003442
3443 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003444 * Called when the network is about to be lost, typically because there are no outstanding
3445 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3446 * with the new replacement network for graceful handover. This method is not guaranteed
3447 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3448 * network is suddenly disconnected.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003449 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003450 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3451 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3452 * this callback as this is prone to race conditions ; calling these methods while in a
3453 * callback may return an outdated or even a null object.
3454 *
3455 * @param network The {@link Network} that is about to be lost.
3456 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3457 * connected for graceful handover; note that the network may still
3458 * suffer a hard loss at any time.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003459 */
paulhua9a6e2a2019-03-22 16:35:06 +08003460 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003461
3462 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003463 * Called when a network disconnects or otherwise no longer satisfies this request or
3464 * callback.
3465 *
3466 * <p>If the callback was registered with requestNetwork() or
3467 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3468 * returned by onAvailable() when that network is lost and no other network satisfies
3469 * the criteria of the request.
3470 *
3471 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3472 * each network which no longer satisfies the criteria of the callback.
3473 *
3474 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3475 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3476 * this callback as this is prone to race conditions ; calling these methods while in a
3477 * callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003478 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003479 * @param network The {@link Network} lost.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003480 */
paulhua9a6e2a2019-03-22 16:35:06 +08003481 public void onLost(@NonNull Network network) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003482
3483 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003484 * Called if no network is found within the timeout time specified in
Etan Cohen06633de2019-01-08 12:09:18 -08003485 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3486 * requested network request cannot be fulfilled (whether or not a timeout was
3487 * specified). When this callback is invoked the associated
Etan Cohen67e58a02017-03-01 12:47:28 -08003488 * {@link NetworkRequest} will have already been removed and released, as if
3489 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003490 */
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003491 public void onUnavailable() {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003492
3493 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003494 * Called when the network corresponding to this request changes capabilities but still
3495 * satisfies the requested criteria.
3496 *
3497 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3498 * to be called immediately after {@link #onAvailable}.
3499 *
3500 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3501 * ConnectivityManager methods in this callback as this is prone to race conditions :
3502 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003503 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003504 * @param network The {@link Network} whose capabilities have changed.
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003505 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3506 * network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003507 */
paulhua9a6e2a2019-03-22 16:35:06 +08003508 public void onCapabilitiesChanged(@NonNull Network network,
3509 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003510
3511 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003512 * Called when the network corresponding to this request changes {@link LinkProperties}.
3513 *
3514 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3515 * to be called immediately after {@link #onAvailable}.
3516 *
3517 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3518 * ConnectivityManager methods in this callback as this is prone to race conditions :
3519 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003520 *
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003521 * @param network The {@link Network} whose link properties have changed.
3522 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003523 */
paulhua9a6e2a2019-03-22 16:35:06 +08003524 public void onLinkPropertiesChanged(@NonNull Network network,
3525 @NonNull LinkProperties linkProperties) {}
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003526
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003527 /**
Chalard Jean7f3a8742019-08-30 16:27:28 +09003528 * Called when the network the framework connected to for this request suspends data
3529 * transmission temporarily.
3530 *
3531 * <p>This generally means that while the TCP connections are still live temporarily
3532 * network data fails to transfer. To give a specific example, this is used on cellular
3533 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3534 * means read operations on sockets on this network will block once the buffers are
3535 * drained, and write operations will block once the buffers are full.
3536 *
3537 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3538 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3539 * this callback as this is prone to race conditions (there is no guarantee the objects
3540 * returned by these methods will be current).
3541 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003542 * @hide
3543 */
paulhua9a6e2a2019-03-22 16:35:06 +08003544 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003545
3546 /**
3547 * Called when the network the framework connected to for this request
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003548 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3549 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean7f3a8742019-08-30 16:27:28 +09003550
3551 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3552 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3553 * this callback as this is prone to race conditions : calling these methods while in a
3554 * callback may return an outdated or even a null object.
3555 *
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003556 * @hide
3557 */
paulhua9a6e2a2019-03-22 16:35:06 +08003558 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003559
junyulai5ab727b2018-08-07 19:50:45 +08003560 /**
3561 * Called when access to the specified network is blocked or unblocked.
3562 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003563 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3564 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3565 * this callback as this is prone to race conditions : calling these methods while in a
3566 * callback may return an outdated or even a null object.
3567 *
junyulai5ab727b2018-08-07 19:50:45 +08003568 * @param network The {@link Network} whose blocked status has changed.
3569 * @param blocked The blocked status of this {@link Network}.
3570 */
junyulai61143782019-03-04 22:45:36 +08003571 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai5ab727b2018-08-07 19:50:45 +08003572
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003573 private NetworkRequest networkRequest;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003574 }
3575
Hugo Benichi145e3792017-05-11 13:16:17 +09003576 /**
3577 * Constant error codes used by ConnectivityService to communicate about failures and errors
3578 * across a Binder boundary.
3579 * @hide
3580 */
3581 public interface Errors {
Chalard Jean73d9db72018-06-04 16:52:49 +09003582 int TOO_MANY_REQUESTS = 1;
Hugo Benichi145e3792017-05-11 13:16:17 +09003583 }
3584
3585 /** @hide */
3586 public static class TooManyRequestsException extends RuntimeException {}
3587
3588 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3589 switch (e.errorCode) {
3590 case Errors.TOO_MANY_REQUESTS:
3591 return new TooManyRequestsException();
3592 default:
3593 Log.w(TAG, "Unknown service error code " + e.errorCode);
3594 return new RuntimeException(e);
3595 }
3596 }
3597
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003598 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003599 /** @hide */
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003600 public static final int CALLBACK_PRECHECK = BASE + 1;
3601 /** @hide */
3602 public static final int CALLBACK_AVAILABLE = BASE + 2;
3603 /** @hide arg1 = TTL */
3604 public static final int CALLBACK_LOSING = BASE + 3;
3605 /** @hide */
3606 public static final int CALLBACK_LOST = BASE + 4;
3607 /** @hide */
3608 public static final int CALLBACK_UNAVAIL = BASE + 5;
3609 /** @hide */
3610 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3611 /** @hide */
3612 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003613 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichi4802c802017-03-23 22:40:44 +09003614 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003615 /** @hide */
Hugo Benichi4802c802017-03-23 22:40:44 +09003616 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003617 /** @hide */
Hugo Benichi4802c802017-03-23 22:40:44 +09003618 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai5ab727b2018-08-07 19:50:45 +08003619 /** @hide */
3620 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003621
Erik Kline66721822015-11-25 12:49:38 +09003622 /** @hide */
3623 public static String getCallbackName(int whichCallback) {
3624 switch (whichCallback) {
3625 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3626 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3627 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3628 case CALLBACK_LOST: return "CALLBACK_LOST";
3629 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3630 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3631 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003632 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3633 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3634 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai5ab727b2018-08-07 19:50:45 +08003635 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline66721822015-11-25 12:49:38 +09003636 default:
3637 return Integer.toString(whichCallback);
3638 }
3639 }
3640
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003641 private class CallbackHandler extends Handler {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003642 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalt9b330772015-09-03 16:41:45 -07003643 private static final boolean DBG = false;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003644
Hugo Benichife3325f2016-07-06 22:53:17 +09003645 CallbackHandler(Looper looper) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003646 super(looper);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003647 }
3648
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003649 CallbackHandler(Handler handler) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003650 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003651 }
3652
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003653 @Override
3654 public void handleMessage(Message message) {
Hugo Benichi3b926992017-05-09 14:36:02 +09003655 if (message.what == EXPIRE_LEGACY_REQUEST) {
3656 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3657 return;
3658 }
3659
3660 final NetworkRequest request = getObject(message, NetworkRequest.class);
3661 final Network network = getObject(message, Network.class);
3662 final NetworkCallback callback;
3663 synchronized (sCallbacks) {
3664 callback = sCallbacks.get(request);
Etan Cohenbc3a4eb2019-05-21 12:06:04 -07003665 if (callback == null) {
3666 Log.w(TAG,
3667 "callback not found for " + getCallbackName(message.what) + " message");
3668 return;
3669 }
Etan Cohene0e2ca92019-04-16 15:07:55 -07003670 if (message.what == CALLBACK_UNAVAIL) {
3671 sCallbacks.remove(request);
3672 callback.networkRequest = ALREADY_UNREGISTERED;
3673 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003674 }
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003675 if (DBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09003676 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colitti7e286832016-03-01 22:56:37 +09003677 }
Hugo Benichi3b926992017-05-09 14:36:02 +09003678
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003679 switch (message.what) {
3680 case CALLBACK_PRECHECK: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003681 callback.onPreCheck(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003682 break;
3683 }
3684 case CALLBACK_AVAILABLE: {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09003685 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3686 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai5ab727b2018-08-07 19:50:45 +08003687 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003688 break;
3689 }
3690 case CALLBACK_LOSING: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003691 callback.onLosing(network, message.arg1);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003692 break;
3693 }
3694 case CALLBACK_LOST: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003695 callback.onLost(network);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003696 break;
3697 }
3698 case CALLBACK_UNAVAIL: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003699 callback.onUnavailable();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003700 break;
3701 }
3702 case CALLBACK_CAP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003703 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3704 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003705 break;
3706 }
3707 case CALLBACK_IP_CHANGED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003708 LinkProperties lp = getObject(message, LinkProperties.class);
3709 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003710 break;
3711 }
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003712 case CALLBACK_SUSPENDED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003713 callback.onNetworkSuspended(network);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07003714 break;
3715 }
3716 case CALLBACK_RESUMED: {
Hugo Benichi3b926992017-05-09 14:36:02 +09003717 callback.onNetworkResumed(network);
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07003718 break;
3719 }
junyulai5ab727b2018-08-07 19:50:45 +08003720 case CALLBACK_BLK_CHANGED: {
3721 boolean blocked = message.arg1 != 0;
3722 callback.onBlockedStatusChanged(network, blocked);
3723 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003724 }
3725 }
3726
Hugo Benichife3325f2016-07-06 22:53:17 +09003727 private <T> T getObject(Message msg, Class<T> c) {
3728 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003729 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003730 }
3731
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003732 private CallbackHandler getDefaultHandler() {
Hugo Benichi3a545552016-07-07 10:15:56 +09003733 synchronized (sCallbacks) {
3734 if (sCallbackHandler == null) {
3735 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003736 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003737 return sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003738 }
3739 }
3740
Hugo Benichiec180d52017-02-03 14:18:44 +09003741 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3742 private static CallbackHandler sCallbackHandler;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003743
Hugo Benichiec180d52017-02-03 14:18:44 +09003744 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
junyulaid1a78162021-01-11 16:53:38 +08003745 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09003746 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09003747 checkCallbackNotNull(callback);
junyulaid1a78162021-01-11 16:53:38 +08003748 Preconditions.checkArgument(
3749 reqType == TRACK_DEFAULT || need != null, "null NetworkCapabilities");
Hugo Benichife3325f2016-07-06 22:53:17 +09003750 final NetworkRequest request;
Roshan Pius34dc4be2020-01-16 12:17:17 -08003751 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003752 try {
Hugo Benichife3325f2016-07-06 22:53:17 +09003753 synchronized(sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09003754 if (callback.networkRequest != null
3755 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichi45a49542017-03-06 09:17:06 +09003756 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3757 // and requests (http://b/20701525).
3758 Log.e(TAG, "NetworkCallback was already registered");
3759 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003760 Messenger messenger = new Messenger(handler);
Hugo Benichife3325f2016-07-06 22:53:17 +09003761 Binder binder = new Binder();
junyulaid1a78162021-01-11 16:53:38 +08003762 if (reqType == LISTEN) {
Roshan Pius34dc4be2020-01-16 12:17:17 -08003763 request = mService.listenForNetwork(
3764 need, messenger, binder, callingPackageName);
Paul Jensenf980a0f2014-06-27 11:05:32 -04003765 } else {
Hugo Benichife3325f2016-07-06 22:53:17 +09003766 request = mService.requestNetwork(
junyulaid1a78162021-01-11 16:53:38 +08003767 need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
3768 callingPackageName, getAttributionTag());
Paul Jensenf980a0f2014-06-27 11:05:32 -04003769 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003770 if (request != null) {
Hugo Benichi3a545552016-07-07 10:15:56 +09003771 sCallbacks.put(request, callback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003772 }
Hugo Benichi3a545552016-07-07 10:15:56 +09003773 callback.networkRequest = request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003774 }
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003775 } catch (RemoteException e) {
3776 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09003777 } catch (ServiceSpecificException e) {
3778 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07003779 }
Hugo Benichife3325f2016-07-06 22:53:17 +09003780 return request;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003781 }
3782
3783 /**
Erik Klinee0aed632016-03-16 15:31:39 +09003784 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003785 *
markchieneddbe2b2020-03-18 21:16:15 +08003786 * This API is only for use in internal system code that requests networks with legacy type and
3787 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchienddd59372020-01-14 00:55:21 +08003788 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003789 *
markchienddd59372020-01-14 00:55:21 +08003790 * @param request {@link NetworkRequest} describing this request.
markchienddd59372020-01-14 00:55:21 +08003791 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3792 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3793 * be a positive value (i.e. >0).
3794 * @param legacyType to specify the network type(#TYPE_*).
3795 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchieneddbe2b2020-03-18 21:16:15 +08003796 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3797 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003798 *
3799 * @hide
3800 */
markchienddd59372020-01-14 00:55:21 +08003801 @SystemApi
markchieneddbe2b2020-03-18 21:16:15 +08003802 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean42a9c292019-01-07 19:26:34 +09003803 public void requestNetwork(@NonNull NetworkRequest request,
markchieneddbe2b2020-03-18 21:16:15 +08003804 int timeoutMs, int legacyType, @NonNull Handler handler,
3805 @NonNull NetworkCallback networkCallback) {
3806 if (legacyType == TYPE_NONE) {
3807 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3808 }
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003809 CallbackHandler cbHandler = new CallbackHandler(handler);
3810 NetworkCapabilities nc = request.networkCapabilities;
3811 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti873f7bb2015-11-25 12:00:52 +09003812 }
3813
3814 /**
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +09003815 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003816 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003817 * <p>This method will attempt to find the best network that matches the passed
3818 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3819 * criteria. The platform will evaluate which network is the best at its own discretion.
3820 * Throughput, latency, cost per byte, policy, user preference and other considerations
3821 * may be factored in the decision of what is considered the best network.
3822 *
3823 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3824 * matching this request, while always attempting to match the request to a better network if
3825 * possible. If a better match is found, the platform will switch this request to the now-best
3826 * network and inform the app of the newly best network by invoking
3827 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3828 * will not try to maintain any other network than the best one currently matching the request:
3829 * a network not matching any network request may be disconnected at any time.
3830 *
3831 * <p>For example, an application could use this method to obtain a connected cellular network
3832 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3833 * radio to consume additional power. Or, an application could inform the system that it wants
3834 * a network supporting sending MMSes and have the system let it know about the currently best
3835 * MMS-supporting network through the provided {@link NetworkCallback}.
3836 *
3837 * <p>The status of the request can be followed by listening to the various callbacks described
3838 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3839 * used to direct traffic to the network (although accessing some networks may be subject to
3840 * holding specific permissions). Callers will learn about the specific characteristics of the
3841 * network through
3842 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3843 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3844 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3845 * matching the request at any given time; therefore when a better network matching the request
3846 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3847 * with the new network after which no further updates are given about the previously-best
3848 * network, unless it becomes the best again at some later time. All callbacks are invoked
3849 * in order on the same thread, which by default is a thread created by the framework running
3850 * in the app.
3851 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3852 * callbacks are invoked.
3853 *
3854 * <p>This{@link NetworkRequest} will live until released via
3855 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3856 * which point the system may let go of the network at any time.
3857 *
3858 * <p>A version of this method which takes a timeout is
3859 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3860 * wait for a limited amount of time for the network to become unavailable.
3861 *
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04003862 * <p>It is presently unsupported to request a network with mutable
3863 * {@link NetworkCapabilities} such as
3864 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3865 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3866 * as these {@code NetworkCapabilities} represent states that a particular
3867 * network may never attain, and whether a network will attain these states
3868 * is unknown prior to bringing up the network so the framework does not
Chalard Jean7f3a8742019-08-30 16:27:28 +09003869 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09003870 *
3871 * <p>This method requires the caller to hold either the
3872 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3873 * or the ability to modify system settings as determined by
3874 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003875 *
Chalard Jean7f06b342020-05-20 16:11:50 +09003876 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
3877 * number of outstanding requests to 100 per app (identified by their UID), shared with
3878 * all variants of this method, of {@link #registerNetworkCallback} as well as
3879 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
3880 * Requesting a network with this method will count toward this limit. If this limit is
3881 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
3882 * make sure to unregister the callbacks with
3883 * {@link #unregisterNetworkCallback(NetworkCallback)}.
3884 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003885 * @param request {@link NetworkRequest} describing this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003886 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3887 * the callback must not be shared - it uniquely specifies this request.
3888 * The callback is invoked on the default internal Handler.
Chalard Jean9f1a7632019-05-13 15:13:58 +09003889 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3890 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09003891 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003892 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003893 public void requestNetwork(@NonNull NetworkRequest request,
3894 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003895 requestNetwork(request, networkCallback, getDefaultHandler());
3896 }
3897
3898 /**
3899 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3900 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003901 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3902 * but runs all the callbacks on the passed Handler.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003903 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003904 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003905 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3906 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003907 *
3908 * @param request {@link NetworkRequest} describing this request.
3909 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3910 * the callback must not be shared - it uniquely specifies this request.
3911 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003912 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003913 public void requestNetwork(@NonNull NetworkRequest request,
3914 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003915 CallbackHandler cbHandler = new CallbackHandler(handler);
markchieneddbe2b2020-03-18 21:16:15 +08003916 NetworkCapabilities nc = request.networkCapabilities;
3917 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003918 }
3919
3920 /**
Etan Cohen67e58a02017-03-01 12:47:28 -08003921 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3922 * by a timeout.
3923 *
3924 * This function behaves identically to the non-timed-out version
3925 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3926 * is not found within the given time (in milliseconds) the
3927 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3928 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3929 * not have to be released if timed-out (it is automatically released). Unregistering a
3930 * request that timed out is not an error.
3931 *
3932 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3933 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3934 * for that purpose. Calling this method will attempt to bring up the requested network.
3935 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003936 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003937 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3938 * and throws the same exceptions in the same conditions.
Etan Cohen67e58a02017-03-01 12:47:28 -08003939 *
3940 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003941 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3942 * the callback must not be shared - it uniquely specifies this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003943 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3944 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3945 * be a positive value (i.e. >0).
Etan Cohen67e58a02017-03-01 12:47:28 -08003946 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003947 public void requestNetwork(@NonNull NetworkRequest request,
3948 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003949 checkTimeout(timeoutMs);
markchieneddbe2b2020-03-18 21:16:15 +08003950 NetworkCapabilities nc = request.networkCapabilities;
3951 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3952 getDefaultHandler());
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003953 }
3954
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003955 /**
3956 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3957 * by a timeout.
3958 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003959 * This method behaves identically to
3960 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3961 * on the passed Handler.
Etan Cohen67e58a02017-03-01 12:47:28 -08003962 *
Chalard Jean7f3a8742019-08-30 16:27:28 +09003963 * <p>This method has the same permission requirements as
Chalard Jean7f06b342020-05-20 16:11:50 +09003964 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
3965 * and throws the same exceptions in the same conditions.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003966 *
3967 * @param request {@link NetworkRequest} describing this request.
Etan Cohen67e58a02017-03-01 12:47:28 -08003968 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3969 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003970 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09003971 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3972 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003973 */
Chalard Jean42a9c292019-01-07 19:26:34 +09003974 public void requestNetwork(@NonNull NetworkRequest request,
3975 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichiff4bf602017-05-09 15:19:01 +09003976 checkTimeout(timeoutMs);
Hugo Benichicd5a0e02017-02-02 17:02:36 +09003977 CallbackHandler cbHandler = new CallbackHandler(handler);
markchieneddbe2b2020-03-18 21:16:15 +08003978 NetworkCapabilities nc = request.networkCapabilities;
3979 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003980 }
3981
3982 /**
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003983 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003984 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003985 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfe76e0e2015-02-11 16:51:13 -08003986 * <p>
Paul Jensen895c3942015-03-10 10:54:12 -04003987 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3988 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003989 */
Erik Klinefb087f12014-11-19 12:12:24 +09003990 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003991
3992 /**
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07003993 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin94c30992014-11-05 10:32:09 -08003994 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003995 * {@link android.content.Intent#getParcelableExtra(String)}.
3996 */
Erik Klinefb087f12014-11-19 12:12:24 +09003997 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07003998
3999
4000 /**
Lorenzo Colitti7cc32c52015-04-23 15:32:42 +09004001 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004002 *
Jeremy Joslin94c30992014-11-05 10:32:09 -08004003 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004004 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004005 * the request may outlive the calling application and get called back when a suitable
4006 * network is found.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004007 * <p>
4008 * The operation is an Intent broadcast that goes to a broadcast receiver that
4009 * you registered with {@link Context#registerReceiver} or through the
4010 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4011 * <p>
4012 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Klinefb087f12014-11-19 12:12:24 +09004013 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4014 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004015 * the original requests parameters. It is important to create a new,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004016 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004017 * Intent to reserve the network or it will be released shortly after the Intent
4018 * is processed.
4019 * <p>
Paul Jensen9ceed862015-06-17 14:15:39 -04004020 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004021 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd0ebdbb2014-05-18 23:07:25 -07004022 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004023 * <p>
Jeremy Joslin94c30992014-11-05 10:32:09 -08004024 * The request may be released normally by calling
4025 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04004026 * <p>It is presently unsupported to request a network with either
4027 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4028 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4029 * as these {@code NetworkCapabilities} represent states that a particular
4030 * network may never attain, and whether a network will attain these states
4031 * is unknown prior to bringing up the network so the framework does not
Chalard Jean73d9db72018-06-04 16:52:49 +09004032 * know how to go about satisfying a request with these capabilities.
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004033 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004034 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4035 * number of outstanding requests to 100 per app (identified by their UID), shared with
4036 * all variants of this method, of {@link #registerNetworkCallback} as well as
4037 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4038 * Requesting a network with this method will count toward this limit. If this limit is
4039 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4040 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4041 * or {@link #releaseNetworkRequest(PendingIntent)}.
4042 *
Lorenzo Colitti91de63b2015-10-15 16:29:00 +09004043 * <p>This method requires the caller to hold either the
4044 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4045 * or the ability to modify system settings as determined by
4046 * {@link android.provider.Settings.System#canWrite}.</p>
4047 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004048 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004049 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004050 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin94c30992014-11-05 10:32:09 -08004051 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean9f1a7632019-05-13 15:13:58 +09004052 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4053 * @throws SecurityException if missing the appropriate permissions.
Chalard Jean7f06b342020-05-20 16:11:50 +09004054 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004055 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004056 public void requestNetwork(@NonNull NetworkRequest request,
4057 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004058 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004059 checkPendingIntentNotNull(operation);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004060 try {
Roshan Pius34dc4be2020-01-16 12:17:17 -08004061 mService.pendingRequestForNetwork(
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07004062 request.networkCapabilities, operation, mContext.getOpPackageName(),
4063 getAttributionTag());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004064 } catch (RemoteException e) {
4065 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004066 } catch (ServiceSpecificException e) {
4067 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004068 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004069 }
4070
4071 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -08004072 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4073 * <p>
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004074 * This method has the same behavior as
4075 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin94c30992014-11-05 10:32:09 -08004076 * releasing network resources and disconnecting.
4077 *
4078 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4079 * PendingIntent passed to
4080 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4081 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4082 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004083 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004084 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004085 checkPendingIntentNotNull(operation);
Jeremy Joslin94c30992014-11-05 10:32:09 -08004086 try {
4087 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004088 } catch (RemoteException e) {
4089 throw e.rethrowFromSystemServer();
4090 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004091 }
4092
Hugo Benichiff4bf602017-05-09 15:19:01 +09004093 private static void checkPendingIntentNotNull(PendingIntent intent) {
4094 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4095 }
4096
4097 private static void checkCallbackNotNull(NetworkCallback callback) {
4098 Preconditions.checkNotNull(callback, "null NetworkCallback");
4099 }
4100
4101 private static void checkTimeout(int timeoutMs) {
4102 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin94c30992014-11-05 10:32:09 -08004103 }
4104
4105 /**
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004106 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004107 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004108 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4109 * called.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004110 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004111 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4112 * number of outstanding requests to 100 per app (identified by their UID), shared with
4113 * all variants of this method, of {@link #requestNetwork} as well as
4114 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4115 * Requesting a network with this method will count toward this limit. If this limit is
4116 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4117 * make sure to unregister the callbacks with
4118 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4119 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004120 * @param request {@link NetworkRequest} describing this request.
4121 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4122 * networks change state.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004123 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004124 * @throws RuntimeException if the app already has too many callbacks registered.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004125 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004126 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004127 public void registerNetworkCallback(@NonNull NetworkRequest request,
4128 @NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004129 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4130 }
4131
4132 /**
4133 * Registers to receive notifications about all networks which satisfy the given
4134 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang0d92d1a2019-02-27 17:14:50 +08004135 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4136 * called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004137 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004138 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4139 * number of outstanding requests to 100 per app (identified by their UID), shared with
4140 * all variants of this method, of {@link #requestNetwork} as well as
4141 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4142 * Requesting a network with this method will count toward this limit. If this limit is
4143 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4144 * make sure to unregister the callbacks with
4145 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4146 *
4147 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004148 * @param request {@link NetworkRequest} describing this request.
4149 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4150 * networks change state.
4151 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004152 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004153 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004154 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004155 public void registerNetworkCallback(@NonNull NetworkRequest request,
4156 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004157 CallbackHandler cbHandler = new CallbackHandler(handler);
4158 NetworkCapabilities nc = request.networkCapabilities;
4159 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004160 }
4161
4162 /**
Paul Jensen9ceed862015-06-17 14:15:39 -04004163 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4164 * {@link NetworkRequest}.
4165 *
4166 * This function behaves identically to the version that takes a NetworkCallback, but instead
4167 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4168 * the request may outlive the calling application and get called back when a suitable
4169 * network is found.
4170 * <p>
4171 * The operation is an Intent broadcast that goes to a broadcast receiver that
4172 * you registered with {@link Context#registerReceiver} or through the
4173 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4174 * <p>
4175 * The operation Intent is delivered with two extras, a {@link Network} typed
4176 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4177 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4178 * the original requests parameters.
4179 * <p>
4180 * If there is already a request for this Intent registered (with the equality of
4181 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4182 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4183 * <p>
4184 * The request may be released normally by calling
Paul Jensen78f6b802015-06-30 14:29:18 -04004185 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Chalard Jean7f06b342020-05-20 16:11:50 +09004186 *
4187 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4188 * number of outstanding requests to 100 per app (identified by their UID), shared with
4189 * all variants of this method, of {@link #requestNetwork} as well as
4190 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4191 * Requesting a network with this method will count toward this limit. If this limit is
4192 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4193 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4194 * or {@link #releaseNetworkRequest(PendingIntent)}.
4195 *
Paul Jensen9ceed862015-06-17 14:15:39 -04004196 * @param request {@link NetworkRequest} describing this request.
4197 * @param operation Action to perform when the network is available (corresponds
4198 * to the {@link NetworkCallback#onAvailable} call. Typically
4199 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean7f06b342020-05-20 16:11:50 +09004200 * @throws RuntimeException if the app already has too many callbacks registered.
Paul Jensen9ceed862015-06-17 14:15:39 -04004201 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004202 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004203 public void registerNetworkCallback(@NonNull NetworkRequest request,
4204 @NonNull PendingIntent operation) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004205 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004206 checkPendingIntentNotNull(operation);
Paul Jensen9ceed862015-06-17 14:15:39 -04004207 try {
Roshan Pius34dc4be2020-01-16 12:17:17 -08004208 mService.pendingListenForNetwork(
Qingxi Libf6bf082020-01-08 12:51:49 -08004209 request.networkCapabilities, operation, mContext.getOpPackageName());
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004210 } catch (RemoteException e) {
4211 throw e.rethrowFromSystemServer();
Hugo Benichi145e3792017-05-11 13:16:17 +09004212 } catch (ServiceSpecificException e) {
4213 throw convertServiceException(e);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004214 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004215 }
4216
4217 /**
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004218 * Registers to receive notifications about changes in the system default network. The callbacks
4219 * will continue to be called until either the application exits or
4220 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinee0aed632016-03-16 15:31:39 +09004221 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004222 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4223 * number of outstanding requests to 100 per app (identified by their UID), shared with
4224 * all variants of this method, of {@link #requestNetwork} as well as
4225 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4226 * Requesting a network with this method will count toward this limit. If this limit is
4227 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4228 * make sure to unregister the callbacks with
4229 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4230 *
Erik Klinee0aed632016-03-16 15:31:39 +09004231 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4232 * system default network changes.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004233 * The callback is invoked on the default internal Handler.
Chalard Jean7f06b342020-05-20 16:11:50 +09004234 * @throws RuntimeException if the app already has too many callbacks registered.
Erik Klinee0aed632016-03-16 15:31:39 +09004235 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004236 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004237 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004238 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4239 }
4240
4241 /**
4242 * Registers to receive notifications about changes in the system default network. The callbacks
4243 * will continue to be called until either the application exits or
4244 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004245 *
Chalard Jean7f06b342020-05-20 16:11:50 +09004246 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4247 * number of outstanding requests to 100 per app (identified by their UID), shared with
4248 * all variants of this method, of {@link #requestNetwork} as well as
4249 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4250 * Requesting a network with this method will count toward this limit. If this limit is
4251 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4252 * make sure to unregister the callbacks with
4253 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4254 *
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004255 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4256 * system default network changes.
4257 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Chalard Jean7f06b342020-05-20 16:11:50 +09004258 * @throws RuntimeException if the app already has too many callbacks registered.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004259 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004260 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004261 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4262 @NonNull Handler handler) {
Erik Klinee0aed632016-03-16 15:31:39 +09004263 // This works because if the NetworkCapabilities are null,
4264 // ConnectivityService takes them from the default request.
4265 //
4266 // Since the capabilities are exactly the same as the default request's
4267 // capabilities, this request is guaranteed, at all times, to be
4268 // satisfied by the same network, if any, that satisfies the default
4269 // request, i.e., the system default network.
Hugo Benichicd5a0e02017-02-02 17:02:36 +09004270 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean73d9db72018-06-04 16:52:49 +09004271 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
junyulaid1a78162021-01-11 16:53:38 +08004272 TRACK_DEFAULT, TYPE_NONE, cbHandler);
Erik Klinee0aed632016-03-16 15:31:39 +09004273 }
4274
4275 /**
fenglu73169332015-04-21 17:12:05 -07004276 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4277 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4278 * network connection for updated bandwidth information. The caller will be notified via
4279 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004280 * method assumes that the caller has previously called
4281 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4282 * changes.
fenglu76564332015-03-20 11:29:56 -07004283 *
fenglu41808e82015-04-27 14:28:04 -07004284 * @param network {@link Network} specifying which network you're interested.
fenglu73169332015-04-21 17:12:05 -07004285 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglu76564332015-03-20 11:29:56 -07004286 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004287 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglu76564332015-03-20 11:29:56 -07004288 try {
fenglu73169332015-04-21 17:12:05 -07004289 return mService.requestBandwidthUpdate(network);
fenglu76564332015-03-20 11:29:56 -07004290 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004291 throw e.rethrowFromSystemServer();
fenglu76564332015-03-20 11:29:56 -07004292 }
4293 }
4294
4295 /**
Hugo Benichi45a49542017-03-06 09:17:06 +09004296 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colittiad458ad2016-04-13 22:00:02 +09004297 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4298 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4299 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colittiefd396e2015-04-24 17:03:31 +09004300 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4301 * will be disconnected.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004302 *
Hugo Benichi45a49542017-03-06 09:17:06 +09004303 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4304 * triggering it as soon as this call returns.
4305 *
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07004306 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004307 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004308 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004309 printStackTrace();
Hugo Benichiff4bf602017-05-09 15:19:01 +09004310 checkCallbackNotNull(networkCallback);
Hugo Benichi45a49542017-03-06 09:17:06 +09004311 final List<NetworkRequest> reqs = new ArrayList<>();
4312 // Find all requests associated to this callback and stop callback triggers immediately.
4313 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4314 synchronized (sCallbacks) {
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004315 Preconditions.checkArgument(networkCallback.networkRequest != null,
4316 "NetworkCallback was not registered");
Etan Cohene0e2ca92019-04-16 15:07:55 -07004317 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4318 Log.d(TAG, "NetworkCallback was already unregistered");
4319 return;
4320 }
Hugo Benichi45a49542017-03-06 09:17:06 +09004321 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4322 if (e.getValue() == networkCallback) {
4323 reqs.add(e.getKey());
4324 }
4325 }
4326 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4327 for (NetworkRequest r : reqs) {
4328 try {
4329 mService.releaseNetworkRequest(r);
4330 } catch (RemoteException e) {
4331 throw e.rethrowFromSystemServer();
4332 }
4333 // Only remove mapping if rpc was successful.
4334 sCallbacks.remove(r);
4335 }
Hugo Benichi1c027fe2017-06-17 13:14:12 +09004336 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004337 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004338 }
Paul Jensene98c6e02014-05-29 10:12:39 -04004339
4340 /**
Paul Jensen78f6b802015-06-30 14:29:18 -04004341 * Unregisters a callback previously registered via
4342 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4343 *
4344 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4345 * PendingIntent passed to
4346 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4347 * Cannot be null.
4348 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004349 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Paul Jensen78f6b802015-06-30 14:29:18 -04004350 releaseNetworkRequest(operation);
4351 }
4352
4353 /**
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004354 * Informs the system whether it should switch to {@code network} regardless of whether it is
4355 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4356 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4357 * the system default network regardless of any other network that's currently connected. If
4358 * {@code always} is true, then the choice is remembered, so that the next time the user
4359 * connects to this network, the system will switch to it.
4360 *
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004361 * @param network The network to accept.
4362 * @param accept Whether to accept the network even if unvalidated.
4363 * @param always Whether to remember this choice in the future.
4364 *
4365 * @hide
4366 */
lucaslin25a50472019-03-12 13:08:03 +08004367 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004368 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4369 try {
4370 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004371 } catch (RemoteException e) {
4372 throw e.rethrowFromSystemServer();
4373 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004374 }
4375
4376 /**
lucaslin25a50472019-03-12 13:08:03 +08004377 * Informs the system whether it should consider the network as validated even if it only has
4378 * partial connectivity. If {@code accept} is true, then the network will be considered as
4379 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4380 * is remembered, so that the next time the user connects to this network, the system will
4381 * switch to it.
4382 *
4383 * @param network The network to accept.
4384 * @param accept Whether to consider the network as validated even if it has partial
4385 * connectivity.
4386 * @param always Whether to remember this choice in the future.
4387 *
4388 * @hide
4389 */
4390 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4391 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4392 try {
4393 mService.setAcceptPartialConnectivity(network, accept, always);
4394 } catch (RemoteException e) {
4395 throw e.rethrowFromSystemServer();
4396 }
4397 }
4398
4399 /**
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004400 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4401 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4402 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4403 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4404 *
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004405 * @param network The network to accept.
4406 *
4407 * @hide
4408 */
lucaslin25a50472019-03-12 13:08:03 +08004409 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004410 public void setAvoidUnvalidated(Network network) {
4411 try {
4412 mService.setAvoidUnvalidated(network);
4413 } catch (RemoteException e) {
4414 throw e.rethrowFromSystemServer();
4415 }
4416 }
4417
4418 /**
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004419 * Requests that the system open the captive portal app on the specified network.
4420 *
4421 * @param network The network to log into.
4422 *
4423 * @hide
4424 */
paulhud70b7dd2019-08-12 16:25:11 +08004425 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004426 public void startCaptivePortalApp(Network network) {
4427 try {
4428 mService.startCaptivePortalApp(network);
4429 } catch (RemoteException e) {
4430 throw e.rethrowFromSystemServer();
4431 }
4432 }
4433
4434 /**
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004435 * Requests that the system open the captive portal app with the specified extras.
4436 *
4437 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4438 * corresponding permission.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004439 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004440 * @param appExtras Extras to include in the app start intent.
4441 * @hide
4442 */
4443 @SystemApi
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004444 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhu9bb04802019-03-08 16:35:20 +08004445 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004446 try {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004447 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004448 } catch (RemoteException e) {
4449 throw e.rethrowFromSystemServer();
4450 }
4451 }
4452
4453 /**
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004454 * Determine whether the device is configured to avoid bad wifi.
4455 * @hide
4456 */
4457 @SystemApi
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004458 @RequiresPermission(anyOf = {
4459 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4460 android.Manifest.permission.NETWORK_STACK})
4461 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004462 try {
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004463 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004464 } catch (RemoteException e) {
4465 throw e.rethrowFromSystemServer();
4466 }
4467 }
4468
4469 /**
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004470 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4471 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti38ea8102017-04-28 00:56:30 +09004472 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4473 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004474 *
4475 * An example of such an operation might be a time-sensitive foreground activity, such as a
4476 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4477 */
4478 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4479
4480 /**
4481 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4482 * a backup channel for traffic that is primarily going over another network.
4483 *
4484 * An example might be maintaining backup connections to peers or servers for the purpose of
4485 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4486 * on backup paths should be negligible compared to the traffic on the main path.
4487 */
4488 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4489
4490 /**
4491 * It is acceptable to use metered data to improve network latency and performance.
4492 */
4493 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4494
4495 /**
4496 * Return value to use for unmetered networks. On such networks we currently set all the flags
4497 * to true.
4498 * @hide
4499 */
4500 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4501 MULTIPATH_PREFERENCE_HANDOVER |
4502 MULTIPATH_PREFERENCE_RELIABILITY |
4503 MULTIPATH_PREFERENCE_PERFORMANCE;
4504
4505 /** @hide */
4506 @Retention(RetentionPolicy.SOURCE)
4507 @IntDef(flag = true, value = {
4508 MULTIPATH_PREFERENCE_HANDOVER,
4509 MULTIPATH_PREFERENCE_RELIABILITY,
4510 MULTIPATH_PREFERENCE_PERFORMANCE,
4511 })
4512 public @interface MultipathPreference {
4513 }
4514
4515 /**
4516 * Provides a hint to the calling application on whether it is desirable to use the
4517 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4518 * for multipath data transfer on this network when it is not the system default network.
4519 * Applications desiring to use multipath network protocols should call this method before
4520 * each such operation.
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004521 *
4522 * @param network The network on which the application desires to use multipath data.
4523 * If {@code null}, this method will return the a preference that will generally
4524 * apply to metered networks.
4525 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4526 */
Jeff Sharkey2ac62992017-04-24 11:18:03 -06004527 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean42a9c292019-01-07 19:26:34 +09004528 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004529 try {
4530 return mService.getMultipathPreference(network);
4531 } catch (RemoteException e) {
4532 throw e.rethrowFromSystemServer();
4533 }
4534 }
4535
4536 /**
Stuart Scottd3bb5082015-03-30 13:17:11 -07004537 * Resets all connectivity manager settings back to factory defaults.
4538 * @hide
4539 */
paulhud70b7dd2019-08-12 16:25:11 +08004540 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scottd3bb5082015-03-30 13:17:11 -07004541 public void factoryReset() {
Stuart Scottd3bb5082015-03-30 13:17:11 -07004542 try {
Stuart Scottca888bf2015-04-02 18:00:02 -07004543 mService.factoryReset();
Amos Bianchiddadca42020-03-04 11:07:38 -08004544 mTetheringManager.stopAllTethering();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004545 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004546 throw e.rethrowFromSystemServer();
Stuart Scottd3bb5082015-03-30 13:17:11 -07004547 }
4548 }
4549
4550 /**
Paul Jensene98c6e02014-05-29 10:12:39 -04004551 * Binds the current process to {@code network}. All Sockets created in the future
4552 * (and not explicitly bound via a bound SocketFactory from
4553 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4554 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4555 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4556 * work and all host name resolutions will fail. This is by design so an application doesn't
4557 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4558 * To clear binding pass {@code null} for {@code network}. Using individually bound
4559 * Sockets created by Network.getSocketFactory().createSocket() and
4560 * performing network-specific host name resolutions via
4561 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen895c3942015-03-10 10:54:12 -04004562 * {@code bindProcessToNetwork}.
Paul Jensene98c6e02014-05-29 10:12:39 -04004563 *
4564 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4565 * the current binding.
4566 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4567 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004568 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean73d9db72018-06-04 16:52:49 +09004569 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen895c3942015-03-10 10:54:12 -04004570 // instantiated.
4571 return setProcessDefaultNetwork(network);
4572 }
4573
4574 /**
4575 * Binds the current process to {@code network}. All Sockets created in the future
4576 * (and not explicitly bound via a bound SocketFactory from
4577 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4578 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4579 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4580 * work and all host name resolutions will fail. This is by design so an application doesn't
4581 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4582 * To clear binding pass {@code null} for {@code network}. Using individually bound
4583 * Sockets created by Network.getSocketFactory().createSocket() and
4584 * performing network-specific host name resolutions via
4585 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4586 * {@code setProcessDefaultNetwork}.
4587 *
4588 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4589 * the current binding.
4590 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4591 * @deprecated This function can throw {@link IllegalStateException}. Use
4592 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4593 * is a direct replacement.
4594 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004595 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004596 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensen99c36662014-08-27 12:38:45 -04004597 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004598 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4599
Lorenzo Colitti580483e2019-01-30 23:04:54 +09004600 if (netId != NETID_UNSET) {
4601 netId = network.getNetIdForResolv();
Paul Jensen99c36662014-08-27 12:38:45 -04004602 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004603
4604 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4605 return false;
4606 }
4607
4608 if (!isSameNetId) {
Paul Jensen12131352014-12-10 15:12:18 -05004609 // Set HTTP proxy system properties to match network.
4610 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colitti40898252015-04-22 11:52:48 +09004611 try {
4612 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4613 } catch (SecurityException e) {
4614 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4615 Log.e(TAG, "Can't set proxy properties", e);
4616 }
Paul Jensen99c36662014-08-27 12:38:45 -04004617 // Must flush DNS cache as new network may have different DNS resolutions.
4618 InetAddress.clearDnsCache();
4619 // Must flush socket pool as idle sockets will be bound to previous network and may
4620 // cause subsequent fetches to be performed on old network.
4621 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensen99c36662014-08-27 12:38:45 -04004622 }
Lorenzo Colitti3fadff92019-01-31 13:08:24 +09004623
4624 return true;
Paul Jensene98c6e02014-05-29 10:12:39 -04004625 }
4626
4627 /**
4628 * Returns the {@link Network} currently bound to this process via
Paul Jensen895c3942015-03-10 10:54:12 -04004629 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensene98c6e02014-05-29 10:12:39 -04004630 *
4631 * @return {@code Network} to which this process is bound, or {@code null}.
4632 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004633 @Nullable
Paul Jensen895c3942015-03-10 10:54:12 -04004634 public Network getBoundNetworkForProcess() {
4635 // Forcing callers to call thru non-static function ensures ConnectivityManager
4636 // instantiated.
4637 return getProcessDefaultNetwork();
4638 }
4639
4640 /**
4641 * Returns the {@link Network} currently bound to this process via
4642 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4643 *
4644 * @return {@code Network} to which this process is bound, or {@code null}.
4645 * @deprecated Using this function can lead to other functions throwing
4646 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4647 * {@code getBoundNetworkForProcess} is a direct replacement.
4648 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004649 @Deprecated
Chalard Jean42a9c292019-01-07 19:26:34 +09004650 @Nullable
Paul Jensene98c6e02014-05-29 10:12:39 -04004651 public static Network getProcessDefaultNetwork() {
Paul Jensen895c3942015-03-10 10:54:12 -04004652 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensen8b6260f2014-07-11 08:17:29 -04004653 if (netId == NETID_UNSET) return null;
Paul Jensene98c6e02014-05-29 10:12:39 -04004654 return new Network(netId);
4655 }
4656
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004657 private void unsupportedStartingFrom(int version) {
4658 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09004659 // The getApplicationInfo() call we make below is not supported in system context. Let
4660 // the call through here, and rely on the fact that ConnectivityService will refuse to
4661 // allow the system to use these APIs anyway.
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004662 return;
4663 }
4664
4665 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4666 throw new UnsupportedOperationException(
4667 "This method is not supported in target SDK version " + version + " and above");
4668 }
4669 }
4670
4671 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4672 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tangae4adaa2016-01-07 23:20:38 -08004673 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004674 // remove these exemptions. Note that this check is not secure, and apps can still access these
4675 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4676 // so is unsupported and may break in the future. http://b/22728205
4677 private void checkLegacyRoutingApiAccess() {
Dianne Hackbornc16abda2015-07-31 10:35:34 -07004678 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colitti9b026fa2015-07-29 11:41:21 +09004679 }
4680
Paul Jensene98c6e02014-05-29 10:12:39 -04004681 /**
4682 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen895c3942015-03-10 10:54:12 -04004683 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensene98c6e02014-05-29 10:12:39 -04004684 *
4685 * @param network The {@link Network} to bind host resolutions from the current process to, or
4686 * {@code null} to clear the current binding.
4687 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4688 * @hide
4689 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4690 */
Aurimas Liutikasa6bb0232016-05-24 15:22:55 -07004691 @Deprecated
Mathew Inwood5a09a712020-11-04 09:29:36 +00004692 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Paul Jensene98c6e02014-05-29 10:12:39 -04004693 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensen8b6260f2014-07-11 08:17:29 -04004694 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef2420792018-04-27 22:48:33 +09004695 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensene98c6e02014-05-29 10:12:39 -04004696 }
Felipe Lemed16384b2016-01-22 09:44:57 -08004697
4698 /**
4699 * Device is not restricting metered network activity while application is running on
4700 * background.
4701 */
4702 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4703
4704 /**
4705 * Device is restricting metered network activity while application is running on background,
4706 * but application is allowed to bypass it.
4707 * <p>
4708 * In this state, application should take action to mitigate metered network access.
4709 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4710 */
4711 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4712
4713 /**
4714 * Device is restricting metered network activity while application is running on background.
Felipe Leme6a5b7692016-01-27 14:46:39 -08004715 * <p>
Felipe Lemed16384b2016-01-22 09:44:57 -08004716 * In this state, application should not try to use the network while running on background,
4717 * because it would be denied.
4718 */
4719 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4720
Felipe Leme6a5b7692016-01-27 14:46:39 -08004721 /**
4722 * A change in the background metered network activity restriction has occurred.
4723 * <p>
4724 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4725 * applies to them.
4726 * <p>
4727 * This is only sent to registered receivers, not manifest receivers.
4728 */
4729 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4730 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4731 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4732
Felipe Leme1b42ef92016-01-25 11:48:04 -08004733 /** @hide */
4734 @Retention(RetentionPolicy.SOURCE)
Felipe Lemed16384b2016-01-22 09:44:57 -08004735 @IntDef(flag = false, value = {
4736 RESTRICT_BACKGROUND_STATUS_DISABLED,
4737 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4738 RESTRICT_BACKGROUND_STATUS_ENABLED,
4739 })
Felipe Lemed16384b2016-01-22 09:44:57 -08004740 public @interface RestrictBackgroundStatus {
4741 }
4742
4743 private INetworkPolicyManager getNetworkPolicyManager() {
4744 synchronized (this) {
4745 if (mNPManager != null) {
4746 return mNPManager;
4747 }
4748 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4749 .getService(Context.NETWORK_POLICY_SERVICE));
4750 return mNPManager;
4751 }
4752 }
4753
4754 /**
4755 * Determines if the calling application is subject to metered network restrictions while
4756 * running on background.
Felipe Leme6bd46fc2016-05-16 13:57:19 -07004757 *
4758 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4759 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4760 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Lemed16384b2016-01-22 09:44:57 -08004761 */
4762 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4763 try {
4764 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4765 } catch (RemoteException e) {
Jeff Sharkeya6066fd2016-03-01 19:27:23 -07004766 throw e.rethrowFromSystemServer();
Felipe Lemed16384b2016-01-22 09:44:57 -08004767 }
4768 }
Ricky Waid53cf002018-01-23 04:09:45 +00004769
4770 /**
4771 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Wai573dcab2018-03-20 14:20:54 +00004772 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4773 * currently used by the system for validation purposes.
Ricky Waid53cf002018-01-23 04:09:45 +00004774 *
4775 * @return Hash of network watchlist config file. Null if config does not exist.
4776 */
Chalard Jean42a9c292019-01-07 19:26:34 +09004777 @Nullable
Ricky Waid53cf002018-01-23 04:09:45 +00004778 public byte[] getNetworkWatchlistConfigHash() {
4779 try {
4780 return mService.getNetworkWatchlistConfigHash();
4781 } catch (RemoteException e) {
4782 Log.e(TAG, "Unable to get watchlist config hash");
4783 throw e.rethrowFromSystemServer();
4784 }
4785 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004786
4787 /**
4788 * Returns the {@code uid} of the owner of a network connection.
4789 *
Benedict Wong8974a1c2020-01-20 22:14:59 -08004790 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4791 * IPPROTO_UDP} currently supported.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004792 * @param local The local {@link InetSocketAddress} of a connection.
4793 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004794 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong8974a1c2020-01-20 22:14:59 -08004795 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4796 * android.os.Process#INVALID_UID} if the connection is not found.
4797 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4798 * user.
4799 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004800 */
Benedict Wong8974a1c2020-01-20 22:14:59 -08004801 public int getConnectionOwnerUid(
4802 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07004803 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4804 try {
4805 return mService.getConnectionOwnerUid(connectionInfo);
4806 } catch (RemoteException e) {
4807 throw e.rethrowFromSystemServer();
4808 }
4809 }
Soi, Yoshinari99efcbd2015-11-12 12:09:02 +09004810
4811 private void printStackTrace() {
4812 if (DEBUG) {
4813 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4814 final StringBuffer sb = new StringBuffer();
4815 for (int i = 3; i < callStack.length; i++) {
4816 final String stackTrace = callStack[i].toString();
4817 if (stackTrace == null || stackTrace.contains("android.os")) {
4818 break;
4819 }
4820 sb.append(" [").append(stackTrace).append("]");
4821 }
4822 Log.d(TAG, "StackLog:" + sb.toString());
4823 }
4824 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004825
Remi NGUYEN VANfe97b482021-01-15 23:02:47 +09004826 /** @hide */
4827 public TestNetworkManager startOrGetTestNetworkManager() {
4828 final IBinder tnBinder;
4829 try {
4830 tnBinder = mService.startOrGetTestNetworkService();
4831 } catch (RemoteException e) {
4832 throw e.rethrowFromSystemServer();
4833 }
4834
4835 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
4836 }
4837
4838 /** @hide */
4839 public VpnManager createVpnManager() {
4840 return new VpnManager(mContext, mService);
4841 }
4842
4843 /** @hide */
4844 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
4845 return new ConnectivityDiagnosticsManager(mContext, mService);
4846 }
4847
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004848 /**
4849 * Simulates a Data Stall for the specified Network.
4850 *
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004851 * <p>This method should only be used for tests.
4852 *
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004853 * <p>The caller must be the owner of the specified Network.
4854 *
4855 * @param detectionMethod The detection method used to identify the Data Stall.
4856 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4857 * @param network The Network for which a Data Stall is being simluated.
4858 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4859 * @throws SecurityException if the caller is not the owner of the given network.
4860 * @hide
4861 */
Remi NGUYEN VAN7d4530b2021-01-12 18:40:04 +09004862 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
Cody Kestingb5c7abd2020-04-15 12:33:28 -07004863 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4864 android.Manifest.permission.NETWORK_STACK})
4865 public void simulateDataStall(int detectionMethod, long timestampMillis,
4866 @NonNull Network network, @NonNull PersistableBundle extras) {
4867 try {
4868 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4869 } catch (RemoteException e) {
4870 e.rethrowFromSystemServer();
4871 }
4872 }
James Mattisdcea9fb2020-10-28 21:48:54 -07004873
4874 private void setOemNetworkPreference(@NonNull OemNetworkPreferences preference) {
4875 Log.d(TAG, "setOemNetworkPreference called with preference: "
4876 + preference.toString());
4877 }
Daniel Bright60f02ed2020-06-15 16:10:01 -07004878
4879 @NonNull
4880 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
4881
4882 /**
4883 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
4884 * receive available QoS events related to the {@link Network} and local ip + port
4885 * specified within socketInfo.
4886 * <p/>
4887 * The same {@link QosCallback} must be unregistered before being registered a second time,
4888 * otherwise {@link QosCallbackRegistrationException} is thrown.
4889 * <p/>
4890 * This API does not, in itself, require any permission if called with a network that is not
4891 * restricted. However, the underlying implementation currently only supports the IMS network,
4892 * which is always restricted. That means non-preinstalled callers can't possibly find this API
4893 * useful, because they'd never be called back on networks that they would have access to.
4894 *
4895 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
4896 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
4897 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
4898 * @throws RuntimeException if the app already has too many callbacks registered.
4899 *
4900 * Exceptions after the time of registration is passed through
4901 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
4902 *
4903 * @param socketInfo the socket information used to match QoS events
4904 * @param callback receives qos events that satisfy socketInfo
4905 * @param executor The executor on which the callback will be invoked. The provided
4906 * {@link Executor} must run callback sequentially, otherwise the order of
4907 * callbacks cannot be guaranteed.
4908 *
4909 * @hide
4910 */
4911 @SystemApi
4912 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
4913 @NonNull final QosCallback callback,
4914 @CallbackExecutor @NonNull final Executor executor) {
4915 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
4916 Objects.requireNonNull(callback, "callback must be non-null");
4917 Objects.requireNonNull(executor, "executor must be non-null");
4918
4919 try {
4920 synchronized (mQosCallbackConnections) {
4921 if (getQosCallbackConnection(callback) == null) {
4922 final QosCallbackConnection connection =
4923 new QosCallbackConnection(this, callback, executor);
4924 mQosCallbackConnections.add(connection);
4925 mService.registerQosSocketCallback(socketInfo, connection);
4926 } else {
4927 Log.e(TAG, "registerQosCallback: Callback already registered");
4928 throw new QosCallbackRegistrationException();
4929 }
4930 }
4931 } catch (final RemoteException e) {
4932 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4933
4934 // The same unregister method method is called for consistency even though nothing
4935 // will be sent to the ConnectivityService since the callback was never successfully
4936 // registered.
4937 unregisterQosCallback(callback);
4938 e.rethrowFromSystemServer();
4939 } catch (final ServiceSpecificException e) {
4940 Log.e(TAG, "registerQosCallback: Error while registering ", e);
4941 unregisterQosCallback(callback);
4942 throw convertServiceException(e);
4943 }
4944 }
4945
4946 /**
4947 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
4948 * events once unregistered and can be registered a second time.
4949 * <p/>
4950 * If the {@link QosCallback} does not have an active registration, it is a no-op.
4951 *
4952 * @param callback the callback being unregistered
4953 *
4954 * @hide
4955 */
4956 @SystemApi
4957 public void unregisterQosCallback(@NonNull final QosCallback callback) {
4958 Objects.requireNonNull(callback, "The callback must be non-null");
4959 try {
4960 synchronized (mQosCallbackConnections) {
4961 final QosCallbackConnection connection = getQosCallbackConnection(callback);
4962 if (connection != null) {
4963 connection.stopReceivingMessages();
4964 mService.unregisterQosCallback(connection);
4965 mQosCallbackConnections.remove(connection);
4966 } else {
4967 Log.d(TAG, "unregisterQosCallback: Callback not registered");
4968 }
4969 }
4970 } catch (final RemoteException e) {
4971 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
4972 e.rethrowFromSystemServer();
4973 }
4974 }
4975
4976 /**
4977 * Gets the connection related to the callback.
4978 *
4979 * @param callback the callback to look up
4980 * @return the related connection
4981 */
4982 @Nullable
4983 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
4984 for (final QosCallbackConnection connection : mQosCallbackConnections) {
4985 // Checking by reference here is intentional
4986 if (connection.getCallback() == callback) {
4987 return connection;
4988 }
4989 }
4990 return null;
4991 }
Junyu Lai23568a42021-01-19 11:10:56 +00004992
4993 /**
4994 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, but
4995 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
4996 * be used to request that the system provide a network without causing the network to be
4997 * in the foreground.
4998 *
4999 * <p>This method will attempt to find the best network that matches the passed
5000 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5001 * criteria. The platform will evaluate which network is the best at its own discretion.
5002 * Throughput, latency, cost per byte, policy, user preference and other considerations
5003 * may be factored in the decision of what is considered the best network.
5004 *
5005 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5006 * matching this request, while always attempting to match the request to a better network if
5007 * possible. If a better match is found, the platform will switch this request to the now-best
5008 * network and inform the app of the newly best network by invoking
5009 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5010 * will not try to maintain any other network than the best one currently matching the request:
5011 * a network not matching any network request may be disconnected at any time.
5012 *
5013 * <p>For example, an application could use this method to obtain a connected cellular network
5014 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5015 * radio to consume additional power. Or, an application could inform the system that it wants
5016 * a network supporting sending MMSes and have the system let it know about the currently best
5017 * MMS-supporting network through the provided {@link NetworkCallback}.
5018 *
5019 * <p>The status of the request can be followed by listening to the various callbacks described
5020 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5021 * used to direct traffic to the network (although accessing some networks may be subject to
5022 * holding specific permissions). Callers will learn about the specific characteristics of the
5023 * network through
5024 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5025 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5026 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5027 * matching the request at any given time; therefore when a better network matching the request
5028 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5029 * with the new network after which no further updates are given about the previously-best
5030 * network, unless it becomes the best again at some later time. All callbacks are invoked
5031 * in order on the same thread, which by default is a thread created by the framework running
5032 * in the app.
5033 *
5034 * <p>This{@link NetworkRequest} will live until released via
5035 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5036 * which point the system may let go of the network at any time.
5037 *
5038 * <p>It is presently unsupported to request a network with mutable
5039 * {@link NetworkCapabilities} such as
5040 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5041 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5042 * as these {@code NetworkCapabilities} represent states that a particular
5043 * network may never attain, and whether a network will attain these states
5044 * is unknown prior to bringing up the network so the framework does not
5045 * know how to go about satisfying a request with these capabilities.
5046 *
5047 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5048 * number of outstanding requests to 100 per app (identified by their UID), shared with
5049 * all variants of this method, of {@link #registerNetworkCallback} as well as
5050 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5051 * Requesting a network with this method will count toward this limit. If this limit is
5052 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5053 * make sure to unregister the callbacks with
5054 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5055 *
5056 * @param request {@link NetworkRequest} describing this request.
5057 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5058 * If null, the callback is invoked on the default internal Handler.
5059 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5060 * the callback must not be shared - it uniquely specifies this request.
5061 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5062 * @throws SecurityException if missing the appropriate permissions.
5063 * @throws RuntimeException if the app already has too many callbacks registered.
5064 *
5065 * @hide
5066 */
5067 @SystemApi(client = MODULE_LIBRARIES)
5068 @SuppressLint("ExecutorRegistration")
5069 @RequiresPermission(anyOf = {
5070 android.Manifest.permission.NETWORK_SETTINGS,
5071 android.Manifest.permission.NETWORK_STACK,
5072 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5073 })
5074 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
5075 @Nullable Handler handler, @NonNull NetworkCallback networkCallback) {
5076 final NetworkCapabilities nc = request.networkCapabilities;
5077 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
5078 TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
5079 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005080}