blob: 36ffe50ef82dcbfe00da39d490fe412109a93d6a [file] [log] [blame]
The Android Open Source Project9066cfe2009-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 Project9066cfe2009-03-03 19:31:44 -080016package android.net;
17
junyulai215b8772019-01-15 11:32:44 +080018import static android.net.IpSecManager.INVALID_RESOURCE_ID;
19
junyulai48eac1d42018-12-27 17:25:29 +080020import android.annotation.CallbackExecutor;
Felipe Leme1b103232016-01-22 09:44:57 -080021import android.annotation.IntDef;
Chalard Jean50bea3d2019-01-07 19:26:34 +090022import android.annotation.NonNull;
Robin Lee244ce8e2016-01-05 18:03:46 +000023import android.annotation.Nullable;
Jeff Sharkey30e06bb2017-04-24 11:18:03 -060024import android.annotation.RequiresPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.annotation.SdkConstant;
26import android.annotation.SdkConstant.SdkConstantType;
Udam Sainib7c24872016-01-04 12:16:14 -080027import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060028import android.annotation.SystemService;
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +090029import android.annotation.TestApi;
Robert Greenwalt9258c642014-03-26 16:47:06 -070030import android.app.PendingIntent;
Artur Satayev26958002019-12-10 17:47:52 +000031import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070032import android.content.Context;
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070033import android.content.Intent;
junyulai48eac1d42018-12-27 17:25:29 +080034import android.net.IpSecManager.UdpEncapsulationSocket;
35import android.net.SocketKeepalive.Callback;
markchiene8b9d752020-01-20 19:31:56 +080036import android.net.TetheringManager.StartTetheringCallback;
markchien40898ca2020-01-21 13:11:06 +080037import android.net.TetheringManager.TetheringEventCallback;
markchiene8b9d752020-01-20 19:31:56 +080038import android.net.TetheringManager.TetheringRequest;
Robert Greenwalt42acef32009-08-12 16:08:25 -070039import android.os.Binder;
Mathew Inwood55418ea2018-12-20 15:30:45 +000040import android.os.Build;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070041import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080042import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070043import android.os.Handler;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080044import android.os.IBinder;
45import android.os.INetworkActivityListener;
46import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070047import android.os.Looper;
48import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070049import android.os.Messenger;
junyulai0c666972019-03-04 22:45:36 +080050import android.os.ParcelFileDescriptor;
Automerger Merge Worker42f81352020-05-12 18:48:04 +000051import android.os.PersistableBundle;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090052import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080054import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080055import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090056import android.os.ServiceSpecificException;
Jeff Sharkey961e3042011-08-29 16:02:57 -070057import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080058import android.telephony.SubscriptionManager;
Meng Wanga73bed82019-11-18 17:10:00 -080059import android.telephony.TelephonyManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080060import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070061import android.util.Log;
Erik Kline35bf06c2017-01-26 18:08:28 +090062import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063
markchien40898ca2020-01-21 13:11:06 +080064import com.android.internal.annotations.GuardedBy;
Hugo Benichidafed3d2017-03-06 09:17:06 +090065import com.android.internal.util.Preconditions;
66import com.android.internal.util.Protocol;
Robert Greenwaltafa05c02014-05-21 20:04:36 -070067
Paul Jensenc91b5342014-08-27 12:38:45 -040068import libcore.net.event.NetworkEventDispatcher;
69
junyulai215b8772019-01-15 11:32:44 +080070import java.io.FileDescriptor;
junyulai0c666972019-03-04 22:45:36 +080071import java.io.IOException;
72import java.io.UncheckedIOException;
Felipe Leme1b103232016-01-22 09:44:57 -080073import java.lang.annotation.Retention;
74import java.lang.annotation.RetentionPolicy;
Jeremy Kleind42209d2015-12-28 15:11:58 -080075import java.net.InetAddress;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070076import java.net.InetSocketAddress;
junyulai352dc2f2019-01-08 20:04:33 +080077import java.net.Socket;
Hugo Benichidafed3d2017-03-06 09:17:06 +090078import java.util.ArrayList;
Jeremy Kleind42209d2015-12-28 15:11:58 -080079import java.util.HashMap;
Hugo Benichidafed3d2017-03-06 09:17:06 +090080import java.util.List;
81import java.util.Map;
markchien40898ca2020-01-21 13:11:06 +080082import java.util.Objects;
junyulai48eac1d42018-12-27 17:25:29 +080083import java.util.concurrent.Executor;
junyulai7c469172019-01-16 20:23:34 +080084import java.util.concurrent.ExecutorService;
85import java.util.concurrent.Executors;
86import java.util.concurrent.RejectedExecutionException;
Jeremy Kleind42209d2015-12-28 15:11:58 -080087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088/**
89 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060090 * notifies applications when network connectivity changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 * <p>
92 * The primary responsibilities of this class are to:
93 * <ol>
94 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
95 * <li>Send broadcast intents when network connectivity changes</li>
96 * <li>Attempt to "fail over" to another network when connectivity to a network
97 * is lost</li>
98 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
99 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700100 * <li>Provide an API that allows applications to request and select networks for their data
101 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 * </ol>
103 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -0600104@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700105public class ConnectivityManager {
106 private static final String TAG = "ConnectivityManager";
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +0900107 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700110 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 * been established or lost. The NetworkInfo for the affected network is
112 * sent as an extra; it should be consulted to see what kind of
113 * connectivity event occurred.
114 * <p/>
Mark Lu33ec1062016-12-05 10:57:55 -0800115 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
116 * broadcast if they declare the broadcast receiver in their manifest. Apps
117 * will still receive broadcasts if they register their
118 * {@link android.content.BroadcastReceiver} with
119 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
120 * and that context is still valid.
121 * <p/>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 * If this is a connection that was the result of failing over from a
123 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
124 * set to true.
125 * <p/>
126 * For a loss of connectivity, if the connectivity manager is attempting
127 * to connect (or has already connected) to another network, the
128 * NetworkInfo for the new network is also passed as an extra. This lets
129 * any receivers of the broadcast know that they should not necessarily
130 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800131 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 * the failover attempt succeeded (and so there is still overall data
133 * connectivity), or that the failover attempt failed, meaning that all
134 * connectivity has been lost.
135 * <p/>
136 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
137 * is set to {@code true} if there are no connected networks at all.
Chalard Jean054cd162018-02-10 05:33:50 +0900138 *
139 * @deprecated apps should use the more versatile {@link #requestNetwork},
140 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
141 * functions instead for faster and more detailed updates about the network
142 * changes they care about.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800144 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean054cd162018-02-10 05:33:50 +0900145 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500149 * The device has connected to a network that has presented a captive
150 * portal, which is blocking Internet connectivity. The user was presented
151 * with a notification that network sign in is required,
152 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400153 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500154 * facilitate signing in to the network. This action includes a
155 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
156 * the network presenting the captive portal; all communication with the
157 * captive portal must be done using this {@code Network} object.
158 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400159 * This activity includes a {@link CaptivePortal} extra named
160 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
161 * outcomes of the captive portal sign in to the system:
162 * <ul>
163 * <li> When the app handling this action believes the user has signed in to
164 * the network and the captive portal has been dismissed, the app should
165 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
166 * reevaluate the network. If reevaluation finds the network no longer
167 * subject to a captive portal, the network may become the default active
Chalard Jean4d660112018-06-04 16:52:49 +0900168 * data network.</li>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400169 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500170 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400171 * {@link CaptivePortal#ignoreNetwork}. </li>
172 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500173 */
174 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
175 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
176
177 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 * The lookup key for a {@link NetworkInfo} object. Retrieve with
179 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700180 *
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900181 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
182 * can't accurately represent modern network characteristics.
183 * Please obtain information about networks from the {@link NetworkCapabilities}
184 * or {@link LinkProperties} objects instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700186 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700190 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700191 *
192 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900193 * @deprecated The network type is not rich enough to represent the characteristics
194 * of modern networks. Please use {@link NetworkCapabilities} instead,
195 * in particular the transports.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700196 */
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900197 @Deprecated
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700198 public static final String EXTRA_NETWORK_TYPE = "networkType";
199
200 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 * The lookup key for a boolean that indicates whether a connect event
202 * is for a network to which the connectivity manager was failing over
203 * following a disconnect on another network.
204 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai3822c8a2018-12-13 12:47:51 +0800205 *
206 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 */
junyulai3822c8a2018-12-13 12:47:51 +0800208 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 public static final String EXTRA_IS_FAILOVER = "isFailover";
210 /**
211 * The lookup key for a {@link NetworkInfo} object. This is supplied when
212 * there is another network that it may be possible to connect to. Retrieve with
213 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800214 *
215 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 */
junyulai3822c8a2018-12-13 12:47:51 +0800217 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
219 /**
220 * The lookup key for a boolean that indicates whether there is a
221 * complete lack of connectivity, i.e., no network is available.
222 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
223 */
224 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
225 /**
226 * The lookup key for a string that indicates why an attempt to connect
227 * to a network failed. The string has no particular structure. It is
228 * intended to be used in notifications presented to users. Retrieve
229 * it with {@link android.content.Intent#getStringExtra(String)}.
230 */
231 public static final String EXTRA_REASON = "reason";
232 /**
233 * The lookup key for a string that provides optionally supplied
234 * extra information about the network state. The information
235 * may be passed up from the lower networking layers, and its
236 * meaning may be specific to a particular network type. Retrieve
237 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800238 *
239 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 */
junyulai3822c8a2018-12-13 12:47:51 +0800241 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700243 /**
244 * The lookup key for an int that provides information about
245 * our connection to the internet at large. 0 indicates no connection,
246 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700247 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700248 * {@hide}
249 */
250 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400252 * The lookup key for a {@link CaptivePortal} object included with the
253 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
254 * object can be used to either indicate to the system that the captive
255 * portal has been dismissed or that the user does not want to pursue
256 * signing in to captive portal. Retrieve it with
257 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500258 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400259 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700260
261 /**
262 * Key for passing a URL to the captive portal login activity.
263 */
264 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
265
Paul Jensen25a217c2015-02-27 22:55:47 -0500266 /**
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900267 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
268 * portal login activity.
269 * {@hide}
270 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900271 @SystemApi
272 @TestApi
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900273 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
274 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
275
276 /**
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900277 * Key for passing a user agent string to the captive portal login activity.
278 * {@hide}
279 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900280 @SystemApi
281 @TestApi
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900282 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
283 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
284
285 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700286 * Broadcast action to indicate the change of data activity status
287 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800288 * The network becomes active when data transmission is started, or
289 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700290 * {@hide}
291 */
292 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean4d660112018-06-04 16:52:49 +0900293 public static final String ACTION_DATA_ACTIVITY_CHANGE =
294 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700295 /**
296 * The lookup key for an enum that indicates the network device type on which this data activity
297 * change happens.
298 * {@hide}
299 */
300 public static final String EXTRA_DEVICE_TYPE = "deviceType";
301 /**
302 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
303 * it is actively sending or receiving data and {@code false} means it is idle.
304 * {@hide}
305 */
306 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700307 /**
308 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
309 * {@hide}
310 */
311 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700312
313 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 * Broadcast Action: The setting for background data usage has changed
315 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
316 * <p>
317 * If an application uses the network in the background, it should listen
318 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700319 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800320 * <p>
321 *
322 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
323 * of background data depends on several combined factors, and
324 * this broadcast is no longer sent. Instead, when background
325 * data is unavailable, {@link #getActiveNetworkInfo()} will now
326 * appear disconnected. During first boot after a platform
327 * upgrade, this broadcast will be sent once if
328 * {@link #getBackgroundDataSetting()} was {@code false} before
329 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 */
331 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800332 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
334 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
335
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700336 /**
337 * Broadcast Action: The network connection may not be good
338 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
339 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
340 * the network and it's condition.
341 * @hide
342 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800343 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100344 @UnsupportedAppUsage
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700345 public static final String INET_CONDITION_ACTION =
346 "android.net.conn.INET_CONDITION_ACTION";
347
Robert Greenwalt42acef32009-08-12 16:08:25 -0700348 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800349 * Broadcast Action: A tetherable connection has come or gone.
350 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline8351faa2017-04-17 16:47:23 +0900351 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
352 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800353 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
354 * the current state of tethering. Each include a list of
355 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800356 * @hide
357 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800358 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100359 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800360 public static final String ACTION_TETHER_STATE_CHANGED =
markchien9e44cde2019-12-25 19:40:32 +0800361 TetheringManager.ACTION_TETHER_STATE_CHANGED;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800362
363 /**
364 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800365 * gives a String[] listing all the interfaces configured for
366 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800367 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100368 @UnsupportedAppUsage
markchien9e44cde2019-12-25 19:40:32 +0800369 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800370
371 /**
372 * @hide
Erik Kline8351faa2017-04-17 16:47:23 +0900373 * gives a String[] listing all the interfaces currently in local-only
374 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800375 */
markchien9e44cde2019-12-25 19:40:32 +0800376 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
Erik Kline8351faa2017-04-17 16:47:23 +0900377
378 /**
379 * @hide
380 * gives a String[] listing all the interfaces currently tethered
381 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
382 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100383 @UnsupportedAppUsage
markchien9e44cde2019-12-25 19:40:32 +0800384 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800385
386 /**
387 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800388 * gives a String[] listing all the interfaces we tried to tether and
389 * failed. Use {@link #getLastTetherError} to find the error code
390 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800391 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100392 @UnsupportedAppUsage
markchien9e44cde2019-12-25 19:40:32 +0800393 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800394
395 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800396 * Broadcast Action: The captive portal tracker has finished its test.
397 * Sent only while running Setup Wizard, in lieu of showing a user
398 * notification.
399 * @hide
400 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800401 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800402 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
403 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
404 /**
405 * The lookup key for a boolean that indicates whether a captive portal was detected.
406 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
407 * @hide
408 */
409 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
410
411 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900412 * Action used to display a dialog that asks the user whether to connect to a network that is
413 * not validated. This intent is used to start the dialog in settings via startActivity.
414 *
415 * @hide
416 */
417 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
418
419 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900420 * Action used to display a dialog that asks the user whether to avoid a network that is no
421 * longer validated. This intent is used to start the dialog in settings via startActivity.
422 *
423 * @hide
424 */
425 public static final String ACTION_PROMPT_LOST_VALIDATION =
426 "android.net.conn.PROMPT_LOST_VALIDATION";
427
428 /**
lucasline252a742019-03-12 13:08:03 +0800429 * Action used to display a dialog that asks the user whether to stay connected to a network
430 * that has not validated. This intent is used to start the dialog in settings via
431 * startActivity.
432 *
433 * @hide
434 */
435 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
436 "android.net.conn.PROMPT_PARTIAL_CONNECTIVITY";
437
438 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800439 * Invalid tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900440 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800441 * @hide
442 */
markchien9e44cde2019-12-25 19:40:32 +0800443 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800444
445 /**
446 * Wifi tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900447 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800448 * @hide
449 */
450 @SystemApi
markchien9e44cde2019-12-25 19:40:32 +0800451 public static final int TETHERING_WIFI = TetheringManager.TETHERING_WIFI;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800452
453 /**
454 * USB tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900455 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800456 * @hide
457 */
458 @SystemApi
markchien9e44cde2019-12-25 19:40:32 +0800459 public static final int TETHERING_USB = TetheringManager.TETHERING_USB;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800460
461 /**
462 * Bluetooth tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900463 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800464 * @hide
465 */
466 @SystemApi
markchien9e44cde2019-12-25 19:40:32 +0800467 public static final int TETHERING_BLUETOOTH = TetheringManager.TETHERING_BLUETOOTH;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800468
469 /**
Jimmy Chenbcd86d02019-07-15 18:03:23 +0800470 * Wifi P2p tethering type.
471 * Wifi P2p tethering is set through events automatically, and don't
472 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
473 * @hide
474 */
markchien9e44cde2019-12-25 19:40:32 +0800475 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
Jimmy Chenbcd86d02019-07-15 18:03:23 +0800476
477 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800478 * Extra used for communicating with the TetherService. Includes the type of tethering to
479 * enable if any.
480 * @hide
481 */
markchien40898ca2020-01-21 13:11:06 +0800482 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800483
484 /**
485 * Extra used for communicating with the TetherService. Includes the type of tethering for
486 * which to cancel provisioning.
487 * @hide
488 */
markchien40898ca2020-01-21 13:11:06 +0800489 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800490
491 /**
492 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
493 * provisioning.
494 * @hide
495 */
markchien40898ca2020-01-21 13:11:06 +0800496 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800497
498 /**
499 * Tells the TetherService to run a provision check now.
500 * @hide
501 */
markchien40898ca2020-01-21 13:11:06 +0800502 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800503
504 /**
505 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
506 * which will receive provisioning results. Can be left empty.
507 * @hide
508 */
markchien40898ca2020-01-21 13:11:06 +0800509 public static final String EXTRA_PROVISION_CALLBACK =
510 TetheringConstants.EXTRA_PROVISION_CALLBACK;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800511
512 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800513 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700514 * @hide
515 */
paulhu4dc238b52020-01-13 16:46:45 +0800516 @SystemApi
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700517 public static final int TYPE_NONE = -1;
518
519 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900520 * A Mobile data connection. Devices may support more than one.
521 *
522 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
523 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
524 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700525 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900526 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700527 public static final int TYPE_MOBILE = 0;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900528
Robert Greenwalt42acef32009-08-12 16:08:25 -0700529 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900530 * A WIFI data connection. Devices may support more than one.
531 *
532 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
533 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
534 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700535 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900536 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700537 public static final int TYPE_WIFI = 1;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900538
Robert Greenwalt42acef32009-08-12 16:08:25 -0700539 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800540 * An MMS-specific Mobile data connection. This network type may use the
541 * same network interface as {@link #TYPE_MOBILE} or it may use a different
542 * one. This is used by applications needing to talk to the carrier's
543 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900544 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900545 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900546 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900547 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700548 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700549 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700550 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900551
Robert Greenwalt42acef32009-08-12 16:08:25 -0700552 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800553 * A SUPL-specific Mobile data connection. This network type may use the
554 * same network interface as {@link #TYPE_MOBILE} or it may use a different
555 * one. This is used by applications needing to talk to the carrier's
556 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900557 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900558 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900559 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900560 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700561 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700562 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700563 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900564
Robert Greenwalt42acef32009-08-12 16:08:25 -0700565 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800566 * A DUN-specific Mobile data connection. This network type may use the
567 * same network interface as {@link #TYPE_MOBILE} or it may use a different
568 * one. This is sometimes by the system when setting up an upstream connection
569 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900570 *
571 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
572 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
573 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700574 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900575 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700576 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900577
Robert Greenwalt42acef32009-08-12 16:08:25 -0700578 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800579 * A High Priority Mobile data connection. This network type uses the
580 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900581 * is different.
582 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900583 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
584 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
585 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700586 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700587 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700588 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900589
jsh8214deb2010-03-11 15:04:43 -0800590 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900591 * A WiMAX data connection.
592 *
593 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
594 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
595 * appropriate network. {@see NetworkCapabilities} for supported transports.
jsh8214deb2010-03-11 15:04:43 -0800596 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900597 @Deprecated
jsh8214deb2010-03-11 15:04:43 -0800598 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800599
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800600 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900601 * A Bluetooth data connection.
602 *
603 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
604 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
605 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800606 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900607 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800608 public static final int TYPE_BLUETOOTH = 7;
609
Robert Greenwalt60810842011-04-22 15:28:18 -0700610 /**
611 * Dummy data connection. This should not be used on shipping devices.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900612 * @deprecated This is not used any more.
Robert Greenwalt60810842011-04-22 15:28:18 -0700613 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900614 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800615 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800616
Robert Greenwalt60810842011-04-22 15:28:18 -0700617 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900618 * An Ethernet data connection.
619 *
620 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
621 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
622 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt60810842011-04-22 15:28:18 -0700623 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900624 @Deprecated
Robert Greenwalte12aec92011-01-28 14:48:37 -0800625 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700626
Wink Saville9d7d6282011-03-12 14:52:01 -0800627 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800628 * Over the air Administration.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900629 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800630 * {@hide}
631 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900632 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900633 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Saville9d7d6282011-03-12 14:52:01 -0800634 public static final int TYPE_MOBILE_FOTA = 10;
635
636 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800637 * IP Multimedia Subsystem.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900638 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800639 * {@hide}
640 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900641 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100642 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800643 public static final int TYPE_MOBILE_IMS = 11;
644
645 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800646 * Carrier Branded Services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900647 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800648 * {@hide}
649 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900650 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900651 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Wink Saville9d7d6282011-03-12 14:52:01 -0800652 public static final int TYPE_MOBILE_CBS = 12;
653
repo syncaea743a2011-07-29 23:55:49 -0700654 /**
655 * A Wi-Fi p2p connection. Only requesting processes will have access to
656 * the peers connected.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900657 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncaea743a2011-07-29 23:55:49 -0700658 * {@hide}
659 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900660 @Deprecated
paulhu5ae1d2c2020-01-15 15:38:23 +0800661 @SystemApi
repo syncaea743a2011-07-29 23:55:49 -0700662 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800663
Wink Saville5e56bc52013-07-29 15:00:57 -0700664 /**
665 * The network to use for initially attaching to the network
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900666 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville5e56bc52013-07-29 15:00:57 -0700667 * {@hide}
668 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900669 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100670 @UnsupportedAppUsage
Wink Saville5e56bc52013-07-29 15:00:57 -0700671 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700672
Lorenzo Colittie285b432015-04-23 15:32:42 +0900673 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700674 * Emergency PDN connection for emergency services. This
675 * may include IMS and MMS in emergency situations.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900676 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram3e0e3bc2014-06-26 11:03:44 -0700677 * {@hide}
678 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900679 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900680 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Ram3e0e3bc2014-06-26 11:03:44 -0700681 public static final int TYPE_MOBILE_EMERGENCY = 15;
682
Hui Lu1c5624a2014-01-15 11:05:36 -0500683 /**
684 * The network that uses proxy to achieve connectivity.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900685 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu1c5624a2014-01-15 11:05:36 -0500686 * {@hide}
687 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900688 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100689 @UnsupportedAppUsage
Hui Lu1c5624a2014-01-15 11:05:36 -0500690 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700691
Robert Greenwalt8283f882014-07-07 17:09:01 -0700692 /**
693 * A virtual network using one or more native bearers.
694 * It may or may not be providing security services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900695 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700696 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900697 @Deprecated
Robert Greenwalt8283f882014-07-07 17:09:01 -0700698 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500699
Benedict Wong89ce5e32018-11-14 17:40:55 -0800700 /**
701 * A network that is exclusively meant to be used for testing
702 *
703 * @deprecated Use {@link NetworkCapabilities} instead.
704 * @hide
705 */
706 @Deprecated
707 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700708
Chalard Jean1d2d35d2020-03-25 01:24:04 +0900709 /**
710 * @deprecated Use {@link NetworkCapabilities} instead.
711 * @hide
712 */
713 @Deprecated
714 @Retention(RetentionPolicy.SOURCE)
715 @IntDef(prefix = { "TYPE_" }, value = {
716 TYPE_NONE,
717 TYPE_MOBILE,
718 TYPE_WIFI,
719 TYPE_MOBILE_MMS,
720 TYPE_MOBILE_SUPL,
721 TYPE_MOBILE_DUN,
722 TYPE_MOBILE_HIPRI,
723 TYPE_WIMAX,
724 TYPE_BLUETOOTH,
725 TYPE_DUMMY,
726 TYPE_ETHERNET,
727 TYPE_MOBILE_FOTA,
728 TYPE_MOBILE_IMS,
729 TYPE_MOBILE_CBS,
730 TYPE_WIFI_P2P,
731 TYPE_MOBILE_IA,
732 TYPE_MOBILE_EMERGENCY,
733 TYPE_PROXY,
734 TYPE_VPN,
735 TYPE_TEST
736 })
737 public @interface LegacyNetworkType {}
738
Chalard Jeanc06d7882019-11-21 14:48:00 +0900739 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
740 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
741 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
742 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
743 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
744
Robert Greenwalt8283f882014-07-07 17:09:01 -0700745 /** {@hide} */
Benedict Wong89ce5e32018-11-14 17:40:55 -0800746 public static final int MAX_RADIO_TYPE = TYPE_TEST;
747
748 /** {@hide} */
749 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750
Hugo Benichi16f0a942017-06-20 14:07:59 +0900751 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
752
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800753 /**
754 * If you want to set the default network preference,you can directly
755 * change the networkAttributes array in framework's config.xml.
756 *
757 * @deprecated Since we support so many more networks now, the single
758 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800759 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800760 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800761 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800762 * from an App.
763 */
764 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
766
Jeff Sharkey625239a2012-09-26 22:03:49 -0700767 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700768 * @hide
769 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900770 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700771
Paul Jensen5d59e782014-07-11 12:28:19 -0400772 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900773 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
774 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean4d660112018-06-04 16:52:49 +0900775 * registered from those that were already unregistered.
Hugo Benichi31c176d2017-06-17 13:14:12 +0900776 * @hide
777 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900778 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900779 new NetworkRequest.Builder().clearCapabilities().build();
780
781 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400782 * A NetID indicating no Network is selected.
783 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
784 * @hide
785 */
786 public static final int NETID_UNSET = 0;
787
Erik Kline4d092232017-10-30 15:29:44 +0900788 /**
789 * Private DNS Mode values.
790 *
791 * The "private_dns_mode" global setting stores a String value which is
792 * expected to be one of the following.
793 */
794
795 /**
796 * @hide
797 */
798 public static final String PRIVATE_DNS_MODE_OFF = "off";
799 /**
800 * @hide
801 */
802 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
803 /**
804 * @hide
805 */
806 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
807 /**
808 * The default Private DNS mode.
809 *
810 * This may change from release to release or may become dependent upon
811 * the capabilities of the underlying platform.
812 *
813 * @hide
814 */
Erik Kline19841792018-05-16 16:41:57 +0900815 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline4d092232017-10-30 15:29:44 +0900816
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900817 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700818 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500819 /**
820 * A kludge to facilitate static access where a Context pointer isn't available, like in the
821 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
822 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
823 * methods that take a Context argument.
824 */
825 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900827 private final Context mContext;
828
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800829 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800830 private INetworkPolicyManager mNPManager;
Automerger Merge Worker6112c822020-03-06 00:38:43 +0000831 private final TetheringManager mTetheringManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800832
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800833 /**
834 * Tests if a given integer represents a valid network type.
835 * @param networkType the type to be tested
836 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400837 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
838 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800839 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700840 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700841 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900842 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
844
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800845 /**
846 * Returns a non-localized string representing a given network type.
847 * ONLY used for debugging output.
848 * @param type the type needing naming
849 * @return a String for the given type, or a string version of the type ("87")
850 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900851 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800852 * {@hide}
853 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900854 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100855 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700856 public static String getNetworkTypeName(int type) {
857 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900858 case TYPE_NONE:
859 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700860 case TYPE_MOBILE:
861 return "MOBILE";
862 case TYPE_WIFI:
863 return "WIFI";
864 case TYPE_MOBILE_MMS:
865 return "MOBILE_MMS";
866 case TYPE_MOBILE_SUPL:
867 return "MOBILE_SUPL";
868 case TYPE_MOBILE_DUN:
869 return "MOBILE_DUN";
870 case TYPE_MOBILE_HIPRI:
871 return "MOBILE_HIPRI";
872 case TYPE_WIMAX:
873 return "WIMAX";
874 case TYPE_BLUETOOTH:
875 return "BLUETOOTH";
876 case TYPE_DUMMY:
877 return "DUMMY";
878 case TYPE_ETHERNET:
879 return "ETHERNET";
880 case TYPE_MOBILE_FOTA:
881 return "MOBILE_FOTA";
882 case TYPE_MOBILE_IMS:
883 return "MOBILE_IMS";
884 case TYPE_MOBILE_CBS:
885 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700886 case TYPE_WIFI_P2P:
887 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700888 case TYPE_MOBILE_IA:
889 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700890 case TYPE_MOBILE_EMERGENCY:
891 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500892 case TYPE_PROXY:
893 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900894 case TYPE_VPN:
895 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700896 default:
897 return Integer.toString(type);
898 }
899 }
900
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800901 /**
902 * Checks if a given type uses the cellular data connection.
903 * This should be replaced in the future by a network property.
904 * @param networkType the type to check
905 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900906 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800907 * {@hide}
908 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900909 @Deprecated
Chalard Jean0bb53dbb2019-04-09 15:46:21 +0900910 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700911 public static boolean isNetworkTypeMobile(int networkType) {
912 switch (networkType) {
913 case TYPE_MOBILE:
914 case TYPE_MOBILE_MMS:
915 case TYPE_MOBILE_SUPL:
916 case TYPE_MOBILE_DUN:
917 case TYPE_MOBILE_HIPRI:
918 case TYPE_MOBILE_FOTA:
919 case TYPE_MOBILE_IMS:
920 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700921 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700922 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700923 return true;
924 default:
925 return false;
926 }
927 }
928
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800929 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700930 * Checks if the given network type is backed by a Wi-Fi radio.
931 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900932 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700933 * @hide
934 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900935 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700936 public static boolean isNetworkTypeWifi(int networkType) {
937 switch (networkType) {
938 case TYPE_WIFI:
939 case TYPE_WIFI_P2P:
940 return true;
941 default:
942 return false;
943 }
944 }
945
946 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800947 * Specifies the preferred network type. When the device has more
948 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800949 *
950 * @param preference the network type to prefer over all others. It is
951 * unspecified what happens to the old preferred network in the
952 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700953 * @deprecated Functionality has been removed as it no longer makes sense,
954 * with many more than two networks - we'd need an array to express
955 * preference. Instead we use dynamic network properties of
956 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800957 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700958 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 }
961
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800962 /**
963 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800964 *
965 * @return an integer representing the preferred network type
966 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700967 * @deprecated Functionality has been removed as it no longer makes sense,
968 * with many more than two networks - we'd need an array to express
969 * preference. Instead we use dynamic network properties of
970 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800971 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700972 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600973 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700975 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
977
Scott Main671644c2011-10-06 19:02:28 -0700978 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800979 * Returns details about the currently active default data network. When
980 * connected, this network is the default route for outgoing connections.
981 * You should always check {@link NetworkInfo#isConnected()} before initiating
982 * network traffic. This may return {@code null} when there is no default
983 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900984 * Note that if the default network is a VPN, this method will return the
985 * NetworkInfo for one of its underlying networks instead, or null if the
986 * VPN agent did not specify any. Apps interested in learning about VPNs
987 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800988 *
989 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500990 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800991 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700992 */
junyulai3822c8a2018-12-13 12:47:51 +0800993 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600994 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900995 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 public NetworkInfo getActiveNetworkInfo() {
997 try {
998 return mService.getActiveNetworkInfo();
999 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001000 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
1002 }
1003
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001004 /**
Paul Jensen31a94f42015-02-13 14:18:39 -05001005 * Returns a {@link Network} object corresponding to the currently active
1006 * default data network. In the event that the current active default data
1007 * network disconnects, the returned {@code Network} object will no longer
1008 * be usable. This will return {@code null} when there is no default
1009 * network.
1010 *
1011 * @return a {@link Network} object for the current default network or
1012 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -05001013 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001014 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001015 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -05001016 public Network getActiveNetwork() {
1017 try {
1018 return mService.getActiveNetwork();
1019 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001020 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05001021 }
1022 }
1023
1024 /**
Robin Leed2baf792016-03-24 12:07:00 +00001025 * Returns a {@link Network} object corresponding to the currently active
1026 * default data network for a specific UID. In the event that the default data
1027 * network disconnects, the returned {@code Network} object will no longer
1028 * be usable. This will return {@code null} when there is no default
1029 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +00001030 *
1031 * @return a {@link Network} object for the current default network for the
1032 * given UID or {@code null} if no default network is currently active
1033 *
1034 * @hide
1035 */
paulhua6af6b62019-08-12 16:25:11 +08001036 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001037 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +00001038 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001039 return getActiveNetworkForUid(uid, false);
1040 }
1041
1042 /** {@hide} */
1043 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001044 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001045 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001046 } catch (RemoteException e) {
1047 throw e.rethrowFromSystemServer();
1048 }
1049 }
1050
1051 /**
Charles He36738632017-05-15 17:07:18 +01001052 * Checks if a VPN app supports always-on mode.
1053 *
1054 * In order to support the always-on feature, an app has to
1055 * <ul>
1056 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +01001057 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
1058 * meta-data field.
Charles He36738632017-05-15 17:07:18 +01001059 * </ul>
1060 *
1061 * @param userId The identifier of the user for whom the VPN app is installed.
1062 * @param vpnPackage The canonical package name of the VPN app.
1063 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
1064 * @hide
1065 */
1066 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1067 try {
1068 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1069 } catch (RemoteException e) {
1070 throw e.rethrowFromSystemServer();
1071 }
1072 }
1073
1074 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001075 * Configures an always-on VPN connection through a specific application.
1076 * This connection is automatically granted and persisted after a reboot.
1077 *
1078 * <p>The designated package should declare a {@link VpnService} in its
1079 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1080 * otherwise the call will fail.
1081 *
1082 * @param userId The identifier of the user to set an always-on VPN for.
1083 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1084 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001085 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1086 * {@code false} otherwise.
Pavel Grafova462bcb2019-01-25 08:50:06 +00001087 * @param lockdownWhitelist The list of packages that are allowed to access network directly
1088 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
1089 * this method must be called when a package that should be whitelisted is installed or
1090 * uninstalled.
Robin Lee244ce8e2016-01-05 18:03:46 +00001091 * @return {@code true} if the package is set as always-on VPN controller;
1092 * {@code false} otherwise.
1093 * @hide
1094 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001095 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leedc679712016-05-03 13:23:03 +01001096 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001097 boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001098 try {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001099 return mService.setAlwaysOnVpnPackage(
1100 userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
Robin Lee244ce8e2016-01-05 18:03:46 +00001101 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001102 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001103 }
1104 }
1105
Pavel Grafova462bcb2019-01-25 08:50:06 +00001106 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001107 * Returns the package name of the currently set always-on VPN application.
1108 * If there is no always-on VPN set, or the VPN is provided by the system instead
1109 * of by an app, {@code null} will be returned.
1110 *
1111 * @return Package name of VPN controller responsible for always-on VPN,
1112 * or {@code null} if none is set.
1113 * @hide
1114 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001115 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee244ce8e2016-01-05 18:03:46 +00001116 public String getAlwaysOnVpnPackageForUser(int userId) {
1117 try {
1118 return mService.getAlwaysOnVpnPackage(userId);
1119 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001120 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001121 }
1122 }
1123
1124 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001125 * @return whether always-on VPN is in lockdown mode.
1126 *
1127 * @hide
1128 **/
1129 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1130 public boolean isVpnLockdownEnabled(int userId) {
1131 try {
1132 return mService.isVpnLockdownEnabled(userId);
1133 } catch (RemoteException e) {
1134 throw e.rethrowFromSystemServer();
1135 }
1136
1137 }
1138
1139 /**
1140 * @return the list of packages that are allowed to access network when always-on VPN is in
1141 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1142 *
1143 * @hide
1144 **/
1145 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1146 public List<String> getVpnLockdownWhitelist(int userId) {
1147 try {
1148 return mService.getVpnLockdownWhitelist(userId);
1149 } catch (RemoteException e) {
1150 throw e.rethrowFromSystemServer();
1151 }
1152 }
1153
1154 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001155 * Returns details about the currently active default data network
1156 * for a given uid. This is for internal use only to avoid spying
1157 * other apps.
1158 *
1159 * @return a {@link NetworkInfo} object for the current default network
1160 * for the given uid or {@code null} if no default network is
1161 * available for the specified uid.
1162 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001163 * {@hide}
1164 */
paulhua6af6b62019-08-12 16:25:11 +08001165 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001166 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001167 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001168 return getActiveNetworkInfoForUid(uid, false);
1169 }
1170
1171 /** {@hide} */
1172 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001173 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001174 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001175 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001176 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001177 }
1178 }
1179
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001180 /**
1181 * Returns connection status information about a particular
1182 * network type.
1183 *
1184 * @param networkType integer specifying which networkType in
1185 * which you're interested.
1186 * @return a {@link NetworkInfo} object for the requested
1187 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001188 * supported by the device. If {@code networkType} is
1189 * TYPE_VPN and a VPN is active for the calling app,
1190 * then this method will try to return one of the
1191 * underlying networks for the VPN or null if the
1192 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001193 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001194 * @deprecated This method does not support multiple connected networks
1195 * of the same type. Use {@link #getAllNetworks} and
1196 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001197 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001198 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001199 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001200 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 public NetworkInfo getNetworkInfo(int networkType) {
1202 try {
1203 return mService.getNetworkInfo(networkType);
1204 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001205 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
1207 }
1208
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001209 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001210 * Returns connection status information about a particular
1211 * Network.
1212 *
1213 * @param network {@link Network} specifying which network
1214 * in which you're interested.
1215 * @return a {@link NetworkInfo} object for the requested
1216 * network or {@code null} if the {@code Network}
1217 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001218 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001219 */
junyulai3822c8a2018-12-13 12:47:51 +08001220 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001221 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001222 @Nullable
1223 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001224 return getNetworkInfoForUid(network, Process.myUid(), false);
1225 }
1226
1227 /** {@hide} */
1228 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001229 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001230 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001231 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001232 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001233 }
1234 }
1235
1236 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001237 * Returns connection status information about all network
1238 * types supported by the device.
1239 *
1240 * @return an array of {@link NetworkInfo} objects. Check each
1241 * {@link NetworkInfo#getType} for which type each applies.
1242 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001243 * @deprecated This method does not support multiple connected networks
1244 * of the same type. Use {@link #getAllNetworks} and
1245 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001246 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001247 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001248 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001249 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 public NetworkInfo[] getAllNetworkInfo() {
1251 try {
1252 return mService.getAllNetworkInfo();
1253 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001254 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
1256 }
1257
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001258 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001259 * Returns the {@link Network} object currently serving a given type, or
1260 * null if the given type is not connected.
1261 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001262 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001263 * @deprecated This method does not support multiple connected networks
1264 * of the same type. Use {@link #getAllNetworks} and
1265 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001266 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001267 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001268 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001269 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001270 public Network getNetworkForType(int networkType) {
1271 try {
1272 return mService.getNetworkForType(networkType);
1273 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001274 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001275 }
1276 }
1277
1278 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001279 * Returns an array of all {@link Network} currently tracked by the
1280 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001281 *
1282 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001283 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001284 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001285 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001286 public Network[] getAllNetworks() {
1287 try {
1288 return mService.getAllNetworks();
1289 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001290 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001291 }
1292 }
1293
1294 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001295 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001296 * the Networks that applications run by the given user will use by default.
1297 * @hide
1298 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001299 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001300 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1301 try {
Qingxi Li9c5d8b92020-01-08 12:51:49 -08001302 return mService.getDefaultNetworkCapabilitiesForUser(
1303 userId, mContext.getOpPackageName());
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001304 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001305 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001306 }
1307 }
1308
1309 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001310 * Returns the IP information for the current default network.
1311 *
1312 * @return a {@link LinkProperties} object describing the IP info
1313 * for the current default network, or {@code null} if there
1314 * is no current default network.
1315 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001316 * {@hide}
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001317 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1318 * value of {@link #getActiveNetwork()} instead. In particular,
1319 * this method will return non-null LinkProperties even if the
1320 * app is blocked by policy from using this network.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001321 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001322 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001323 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001324 public LinkProperties getActiveLinkProperties() {
1325 try {
1326 return mService.getActiveLinkProperties();
1327 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001328 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001329 }
1330 }
1331
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001332 /**
1333 * Returns the IP information for a given network type.
1334 *
1335 * @param networkType the network type of interest.
1336 * @return a {@link LinkProperties} object describing the IP info
1337 * for the given networkType, or {@code null} if there is
1338 * no current default network.
1339 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001340 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001341 * @deprecated This method does not support multiple connected networks
1342 * of the same type. Use {@link #getAllNetworks},
1343 * {@link #getNetworkInfo(android.net.Network)}, and
1344 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001345 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001346 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001347 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09001348 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001349 public LinkProperties getLinkProperties(int networkType) {
1350 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001351 return mService.getLinkPropertiesForType(networkType);
1352 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001353 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001354 }
1355 }
1356
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001357 /**
1358 * Get the {@link LinkProperties} for the given {@link Network}. This
1359 * will return {@code null} if the network is unknown.
1360 *
1361 * @param network The {@link Network} object identifying the network in question.
1362 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001363 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001364 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001365 @Nullable
1366 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001367 try {
1368 return mService.getLinkProperties(network);
1369 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001370 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001371 }
1372 }
1373
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001374 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001375 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001376 * will return {@code null} if the network is unknown.
1377 *
1378 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001379 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001380 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001381 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001382 @Nullable
1383 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001384 try {
Qingxi Li9c5d8b92020-01-08 12:51:49 -08001385 return mService.getNetworkCapabilities(network, mContext.getOpPackageName());
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001386 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001387 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001388 }
1389 }
1390
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001391 /**
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001392 * Gets a URL that can be used for resolving whether a captive portal is present.
Udam Sainib7c24872016-01-04 12:16:14 -08001393 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1394 * portal is present.
1395 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1396 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1397 *
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09001398 * The system network validation may be using different strategies to detect captive portals,
1399 * so this method does not necessarily return a URL used by the system. It only returns a URL
1400 * that may be relevant for other components trying to detect captive portals.
paulhua6af6b62019-08-12 16:25:11 +08001401 *
Udam Sainib7c24872016-01-04 12:16:14 -08001402 * @hide
paulhua6af6b62019-08-12 16:25:11 +08001403 * @deprecated This API returns URL which is not guaranteed to be one of the URLs used by the
1404 * system.
Udam Sainib7c24872016-01-04 12:16:14 -08001405 */
paulhua6af6b62019-08-12 16:25:11 +08001406 @Deprecated
Udam Sainib7c24872016-01-04 12:16:14 -08001407 @SystemApi
paulhua6af6b62019-08-12 16:25:11 +08001408 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Udam Sainib7c24872016-01-04 12:16:14 -08001409 public String getCaptivePortalServerUrl() {
1410 try {
1411 return mService.getCaptivePortalServerUrl();
1412 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001413 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001414 }
1415 }
1416
1417 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 * Tells the underlying networking system that the caller wants to
1419 * begin using the named feature. The interpretation of {@code feature}
1420 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001421 *
1422 * <p>This method requires the caller to hold either the
1423 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1424 * or the ability to modify system settings as determined by
1425 * {@link android.provider.Settings.System#canWrite}.</p>
1426 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 * @param networkType specifies which network the request pertains to
1428 * @param feature the name of the feature to be used
1429 * @return an integer value representing the outcome of the request.
1430 * The interpretation of this value is specific to each networking
1431 * implementation+feature combination, except that the value {@code -1}
1432 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001433 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001434 * @deprecated Deprecated in favor of the cleaner
1435 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001436 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001437 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001438 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001440 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001442 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001443 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1444 if (netCap == null) {
1445 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1446 feature);
Chalard Jeanc06d7882019-11-21 14:48:00 +09001447 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001448 }
1449
1450 NetworkRequest request = null;
1451 synchronized (sLegacyRequests) {
1452 LegacyRequest l = sLegacyRequests.get(netCap);
1453 if (l != null) {
1454 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1455 renewRequestLocked(l);
1456 if (l.currentNetwork != null) {
Chalard Jeanc06d7882019-11-21 14:48:00 +09001457 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001458 } else {
Chalard Jeanc06d7882019-11-21 14:48:00 +09001459 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001460 }
1461 }
1462
1463 request = requestNetworkForFeatureLocked(netCap);
1464 }
1465 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001466 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Chalard Jeanc06d7882019-11-21 14:48:00 +09001467 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001468 } else {
1469 Log.d(TAG, " request Failed");
Chalard Jeanc06d7882019-11-21 14:48:00 +09001470 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 }
1472 }
1473
1474 /**
1475 * Tells the underlying networking system that the caller is finished
1476 * using the named feature. The interpretation of {@code feature}
1477 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001478 *
1479 * <p>This method requires the caller to hold either the
1480 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1481 * or the ability to modify system settings as determined by
1482 * {@link android.provider.Settings.System#canWrite}.</p>
1483 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 * @param networkType specifies which network the request pertains to
1485 * @param feature the name of the feature that is no longer needed
1486 * @return an integer value representing the outcome of the request.
1487 * The interpretation of this value is specific to each networking
1488 * implementation+feature combination, except that the value {@code -1}
1489 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001490 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001491 * @deprecated Deprecated in favor of the cleaner
1492 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001493 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001494 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001495 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001497 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001499 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001500 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1501 if (netCap == null) {
1502 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1503 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 return -1;
1505 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001506
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001507 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001508 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001509 }
1510 return 1;
1511 }
1512
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001513 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001514 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1515 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001516 switch (feature) {
1517 case "enableCBS":
1518 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1519 case "enableDUN":
1520 case "enableDUNAlways":
1521 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1522 case "enableFOTA":
1523 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1524 case "enableHIPRI":
1525 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1526 case "enableIMS":
1527 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1528 case "enableMMS":
1529 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1530 case "enableSUPL":
1531 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1532 default:
1533 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001534 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001535 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1536 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001537 }
1538 return null;
1539 }
1540
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001541 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001542 if (netCap == null) return TYPE_NONE;
1543 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1544 return TYPE_MOBILE_CBS;
1545 }
1546 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1547 return TYPE_MOBILE_IMS;
1548 }
1549 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1550 return TYPE_MOBILE_FOTA;
1551 }
1552 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1553 return TYPE_MOBILE_DUN;
1554 }
1555 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1556 return TYPE_MOBILE_SUPL;
1557 }
1558 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1559 return TYPE_MOBILE_MMS;
1560 }
1561 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1562 return TYPE_MOBILE_HIPRI;
1563 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001564 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1565 return TYPE_WIFI_P2P;
1566 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001567 return TYPE_NONE;
1568 }
1569
1570 private static class LegacyRequest {
1571 NetworkCapabilities networkCapabilities;
1572 NetworkRequest networkRequest;
1573 int expireSequenceNumber;
1574 Network currentNetwork;
1575 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001576
1577 private void clearDnsBinding() {
1578 if (currentNetwork != null) {
1579 currentNetwork = null;
1580 setProcessDefaultNetworkForHostResolution(null);
1581 }
1582 }
1583
Robert Greenwalt6078b502014-06-11 16:05:07 -07001584 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001585 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001586 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001587 currentNetwork = network;
1588 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001589 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001590 }
1591 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001592 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001593 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001594 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1595 }
1596 };
1597 }
1598
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001599 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001600 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1601 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001602
1603 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1604 synchronized (sLegacyRequests) {
1605 LegacyRequest l = sLegacyRequests.get(netCap);
1606 if (l != null) return l.networkRequest;
1607 }
1608 return null;
1609 }
1610
1611 private void renewRequestLocked(LegacyRequest l) {
1612 l.expireSequenceNumber++;
1613 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1614 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1615 }
1616
1617 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1618 int ourSeqNum = -1;
1619 synchronized (sLegacyRequests) {
1620 LegacyRequest l = sLegacyRequests.get(netCap);
1621 if (l == null) return;
1622 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001623 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001624 }
1625 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1626 }
1627
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001628 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001629 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1630 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001631 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001632 try {
1633 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001634 } catch (RemoteException e) {
1635 throw e.rethrowFromSystemServer();
1636 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001637 LegacyRequest l = new LegacyRequest();
1638 l.networkCapabilities = netCap;
1639 l.delay = delay;
1640 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001641 l.networkRequest = sendRequestForNetwork(
1642 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001643 if (l.networkRequest == null) return null;
1644 sLegacyRequests.put(netCap, l);
1645 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1646 return l.networkRequest;
1647 }
1648
1649 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1650 if (delay >= 0) {
1651 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001652 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001653 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1654 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001655 }
1656 }
1657
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001658 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001659 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1660 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001661 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001662 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001663 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001664 if (l == null) return false;
1665 unregisterNetworkCallback(l.networkCallback);
1666 l.clearDnsBinding();
1667 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
1669
Erik Kline35bf06c2017-01-26 18:08:28 +09001670 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1671 static {
1672 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1673 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1674 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1675 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1676 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1677 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1678 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1679 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1680 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1681 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1682 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1683 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1684 }
1685
1686 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1687 static {
1688 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1689 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1690 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1691 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1692 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1693 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1694 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1695 }
1696
1697 /**
1698 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1699 * instance suitable for registering a request or callback. Throws an
1700 * IllegalArgumentException if no mapping from the legacy type to
1701 * NetworkCapabilities is known.
1702 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001703 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1704 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001705 * @hide
1706 */
1707 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1708 final NetworkCapabilities nc = new NetworkCapabilities();
1709
1710 // Map from type to transports.
1711 final int NOT_FOUND = -1;
1712 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001713 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001714 nc.addTransportType(transport);
1715
1716 // Map from type to capabilities.
1717 nc.addCapability(sLegacyTypeToCapability.get(
1718 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1719 nc.maybeMarkCapabilitiesRestricted();
1720 return nc;
1721 }
1722
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001723 /** @hide */
1724 public static class PacketKeepaliveCallback {
Artur Satayev751e5512019-11-15 19:12:49 +00001725 @UnsupportedAppUsage
1726 public PacketKeepaliveCallback() {
1727 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001728 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001729 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001730 public void onStarted() {}
1731 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001732 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001733 public void onStopped() {}
1734 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001735 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001736 public void onError(int error) {}
1737 }
1738
1739 /**
1740 * Allows applications to request that the system periodically send specific packets on their
1741 * behalf, using hardware offload to save battery power.
1742 *
1743 * To request that the system send keepalives, call one of the methods that return a
1744 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1745 * passing in a non-null callback. If the callback is successfully started, the callback's
1746 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1747 * specifying one of the {@code ERROR_*} constants in this class.
1748 *
Chalard Jean4d660112018-06-04 16:52:49 +09001749 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1750 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1751 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001752 *
junyulai48eac1d42018-12-27 17:25:29 +08001753 * @deprecated Use {@link SocketKeepalive} instead.
1754 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001755 * @hide
1756 */
1757 public class PacketKeepalive {
1758
1759 private static final String TAG = "PacketKeepalive";
1760
1761 /** @hide */
1762 public static final int SUCCESS = 0;
1763
1764 /** @hide */
1765 public static final int NO_KEEPALIVE = -1;
1766
1767 /** @hide */
1768 public static final int BINDER_DIED = -10;
1769
1770 /** The specified {@code Network} is not connected. */
1771 public static final int ERROR_INVALID_NETWORK = -20;
1772 /** The specified IP addresses are invalid. For example, the specified source IP address is
1773 * not configured on the specified {@code Network}. */
1774 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1775 /** The requested port is invalid. */
1776 public static final int ERROR_INVALID_PORT = -22;
1777 /** The packet length is invalid (e.g., too long). */
1778 public static final int ERROR_INVALID_LENGTH = -23;
1779 /** The packet transmission interval is invalid (e.g., too short). */
1780 public static final int ERROR_INVALID_INTERVAL = -24;
1781
1782 /** The hardware does not support this request. */
1783 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001784 /** The hardware returned an error. */
1785 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001786
Nathan Harold63dd8132018-02-14 13:09:45 -08001787 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001788 public static final int NATT_PORT = 4500;
1789
Nathan Harold63dd8132018-02-14 13:09:45 -08001790 /** The minimum interval in seconds between keepalive packet transmissions */
1791 public static final int MIN_INTERVAL = 10;
1792
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001793 private final Network mNetwork;
junyulai7c469172019-01-16 20:23:34 +08001794 private final ISocketKeepaliveCallback mCallback;
1795 private final ExecutorService mExecutor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001796
1797 private volatile Integer mSlot;
1798
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001799 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001800 public void stop() {
1801 try {
junyulai7c469172019-01-16 20:23:34 +08001802 mExecutor.execute(() -> {
1803 try {
1804 if (mSlot != null) {
1805 mService.stopKeepalive(mNetwork, mSlot);
1806 }
1807 } catch (RemoteException e) {
1808 Log.e(TAG, "Error stopping packet keepalive: ", e);
1809 throw e.rethrowFromSystemServer();
1810 }
1811 });
1812 } catch (RejectedExecutionException e) {
1813 // The internal executor has already stopped due to previous event.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001814 }
1815 }
1816
1817 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001818 Preconditions.checkNotNull(network, "network cannot be null");
1819 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001820 mNetwork = network;
junyulai7c469172019-01-16 20:23:34 +08001821 mExecutor = Executors.newSingleThreadExecutor();
1822 mCallback = new ISocketKeepaliveCallback.Stub() {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001823 @Override
junyulai7c469172019-01-16 20:23:34 +08001824 public void onStarted(int slot) {
1825 Binder.withCleanCallingIdentity(() ->
1826 mExecutor.execute(() -> {
1827 mSlot = slot;
1828 callback.onStarted();
1829 }));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001830 }
junyulai7c469172019-01-16 20:23:34 +08001831
1832 @Override
1833 public void onStopped() {
1834 Binder.withCleanCallingIdentity(() ->
1835 mExecutor.execute(() -> {
1836 mSlot = null;
1837 callback.onStopped();
1838 }));
1839 mExecutor.shutdown();
1840 }
1841
1842 @Override
1843 public void onError(int error) {
1844 Binder.withCleanCallingIdentity(() ->
1845 mExecutor.execute(() -> {
1846 mSlot = null;
1847 callback.onError(error);
1848 }));
1849 mExecutor.shutdown();
1850 }
1851
1852 @Override
1853 public void onDataReceived() {
1854 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
1855 // this callback when data is received.
1856 }
1857 };
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001858 }
1859 }
1860
1861 /**
1862 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1863 *
junyulai48eac1d42018-12-27 17:25:29 +08001864 * @deprecated Use {@link #createSocketKeepalive} instead.
1865 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001866 * @hide
1867 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001868 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001869 public PacketKeepalive startNattKeepalive(
1870 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1871 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1872 final PacketKeepalive k = new PacketKeepalive(network, callback);
1873 try {
junyulai7c469172019-01-16 20:23:34 +08001874 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001875 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1876 } catch (RemoteException e) {
1877 Log.e(TAG, "Error starting packet keepalive: ", e);
junyulai7c469172019-01-16 20:23:34 +08001878 throw e.rethrowFromSystemServer();
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001879 }
1880 return k;
1881 }
1882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 /**
junyulai48eac1d42018-12-27 17:25:29 +08001884 * Request that keepalives be started on a IPsec NAT-T socket.
1885 *
1886 * @param network The {@link Network} the socket is on.
1887 * @param socket The socket that needs to be kept alive.
1888 * @param source The source address of the {@link UdpEncapsulationSocket}.
1889 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1890 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1891 * must run callback sequentially, otherwise the order of callbacks cannot be
1892 * guaranteed.
1893 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1894 * changes. Must be extended by applications that use this API.
1895 *
junyulai352dc2f2019-01-08 20:04:33 +08001896 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1897 * given socket.
junyulai48eac1d42018-12-27 17:25:29 +08001898 **/
junyulai0c666972019-03-04 22:45:36 +08001899 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai48eac1d42018-12-27 17:25:29 +08001900 @NonNull UdpEncapsulationSocket socket,
1901 @NonNull InetAddress source,
1902 @NonNull InetAddress destination,
1903 @NonNull @CallbackExecutor Executor executor,
1904 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001905 ParcelFileDescriptor dup;
1906 try {
junyulai15178152019-03-27 11:00:37 +08001907 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
1908 // which cannot be obtained by the app process.
junyulai0c666972019-03-04 22:45:36 +08001909 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
1910 } catch (IOException ignored) {
1911 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1912 // ERROR_INVALID_SOCKET.
1913 dup = new ParcelFileDescriptor(new FileDescriptor());
1914 }
1915 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
1916 destination, executor, callback);
junyulai215b8772019-01-15 11:32:44 +08001917 }
1918
1919 /**
1920 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1921 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1922 *
1923 * @param network The {@link Network} the socket is on.
junyulai0c666972019-03-04 22:45:36 +08001924 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
1925 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
1926 * from that port.
junyulai215b8772019-01-15 11:32:44 +08001927 * @param source The source address of the {@link UdpEncapsulationSocket}.
1928 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1929 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1930 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1931 * must run callback sequentially, otherwise the order of callbacks cannot be
1932 * guaranteed.
1933 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1934 * changes. Must be extended by applications that use this API.
1935 *
junyulai352dc2f2019-01-08 20:04:33 +08001936 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1937 * given socket.
junyulai215b8772019-01-15 11:32:44 +08001938 * @hide
1939 */
1940 @SystemApi
1941 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08001942 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
1943 @NonNull ParcelFileDescriptor pfd,
junyulai215b8772019-01-15 11:32:44 +08001944 @NonNull InetAddress source,
1945 @NonNull InetAddress destination,
1946 @NonNull @CallbackExecutor Executor executor,
1947 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001948 ParcelFileDescriptor dup;
1949 try {
junyulai15178152019-03-27 11:00:37 +08001950 // TODO: Consider remove unnecessary dup.
junyulai0c666972019-03-04 22:45:36 +08001951 dup = pfd.dup();
1952 } catch (IOException ignored) {
1953 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1954 // ERROR_INVALID_SOCKET.
1955 dup = new ParcelFileDescriptor(new FileDescriptor());
1956 }
1957 return new NattSocketKeepalive(mService, network, dup,
1958 INVALID_RESOURCE_ID /* Unused */, source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08001959 }
1960
1961 /**
junyulai352dc2f2019-01-08 20:04:33 +08001962 * Request that keepalives be started on a TCP socket.
1963 * The socket must be established.
1964 *
1965 * @param network The {@link Network} the socket is on.
1966 * @param socket The socket that needs to be kept alive.
1967 * @param executor The executor on which callback will be invoked. This implementation assumes
1968 * the provided {@link Executor} runs the callbacks in sequence with no
1969 * concurrency. Failing this, no guarantee of correctness can be made. It is
1970 * the responsibility of the caller to ensure the executor provides this
1971 * guarantee. A simple way of creating such an executor is with the standard
1972 * tool {@code Executors.newSingleThreadExecutor}.
1973 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1974 * changes. Must be extended by applications that use this API.
1975 *
1976 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1977 * given socket.
1978 * @hide
1979 */
1980 @SystemApi
1981 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
junyulai0c666972019-03-04 22:45:36 +08001982 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
junyulai352dc2f2019-01-08 20:04:33 +08001983 @NonNull Socket socket,
1984 @NonNull Executor executor,
1985 @NonNull Callback callback) {
junyulai0c666972019-03-04 22:45:36 +08001986 ParcelFileDescriptor dup;
1987 try {
1988 dup = ParcelFileDescriptor.fromSocket(socket);
1989 } catch (UncheckedIOException ignored) {
1990 // Construct an invalid fd, so that if the user later calls start(), it will fail with
1991 // ERROR_INVALID_SOCKET.
1992 dup = new ParcelFileDescriptor(new FileDescriptor());
1993 }
1994 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
junyulai352dc2f2019-01-08 20:04:33 +08001995 }
1996
1997 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 * Ensure that a network route exists to deliver traffic to the specified
1999 * host via the specified network interface. An attempt to add a route that
2000 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002001 *
2002 * <p>This method requires the caller to hold either the
2003 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2004 * or the ability to modify system settings as determined by
2005 * {@link android.provider.Settings.System#canWrite}.</p>
2006 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 * @param networkType the type of the network over which traffic to the specified
2008 * host is to be routed
2009 * @param hostAddress the IP address of the host to which the route is desired
2010 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002011 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002012 * @deprecated Deprecated in favor of the
2013 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2014 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07002015 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002016 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09002017 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002019 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002021 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002022 }
2023
2024 /**
2025 * Ensure that a network route exists to deliver traffic to the specified
2026 * host via the specified network interface. An attempt to add a route that
2027 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002028 *
2029 * <p>This method requires the caller to hold either the
2030 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2031 * or the ability to modify system settings as determined by
2032 * {@link android.provider.Settings.System#canWrite}.</p>
2033 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002034 * @param networkType the type of the network over which traffic to the specified
2035 * host is to be routed
2036 * @param hostAddress the IP address of the host to which the route is desired
2037 * @return {@code true} on success, {@code false} on failure
2038 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002039 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002040 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002041 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002042 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002043 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002044 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002045 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002047 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002049 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 }
2051 }
2052
2053 /**
2054 * Returns the value of the setting for background data usage. If false,
2055 * applications should not use the network if the application is not in the
2056 * foreground. Developers should respect this setting, and check the value
2057 * of this before performing any background data operations.
2058 * <p>
2059 * All applications that have background services that use the network
2060 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002061 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002062 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002063 * background data depends on several combined factors, and this method will
2064 * always return {@code true}. Instead, when background data is unavailable,
2065 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002066 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 * @return Whether background data usage is allowed.
2068 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002069 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002071 // assume that background data is allowed; final authority is
2072 // NetworkInfo which may be blocked.
2073 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 }
2075
2076 /**
2077 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002078 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 * @param allowBackgroundData Whether an application should use data while
2080 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002081 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2083 * @see #getBackgroundDataSetting()
2084 * @hide
2085 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002086 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002087 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002089 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002091
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002092 /** {@hide} */
2093 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002094 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002095 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2096 try {
2097 return mService.getActiveNetworkQuotaInfo();
2098 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002099 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002100 }
2101 }
2102
2103 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002104 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002105 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002106 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002107 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002108 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002109 public boolean getMobileDataEnabled() {
Meng Wanga73bed82019-11-18 17:10:00 -08002110 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2111 if (tm != null) {
2112 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2113 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2114 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2115 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2116 + " retVal=" + retVal);
2117 return retVal;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002118 }
Wink Saville36ffb042014-12-05 11:10:30 -08002119 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002120 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002121 }
2122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002124 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002125 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002126 */
2127 public interface OnNetworkActiveListener {
2128 /**
2129 * Called on the main thread of the process to report that the current data network
2130 * has become active, and it is now a good time to perform any pending network
2131 * operations. Note that this listener only tells you when the network becomes
2132 * active; if at any other time you want to know whether it is active (and thus okay
2133 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002134 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002135 */
Chalard Jean4d660112018-06-04 16:52:49 +09002136 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002137 }
2138
2139 private INetworkManagementService getNetworkManagementService() {
2140 synchronized (this) {
2141 if (mNMService != null) {
2142 return mNMService;
2143 }
2144 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2145 mNMService = INetworkManagementService.Stub.asInterface(b);
2146 return mNMService;
2147 }
2148 }
2149
2150 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002151 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002152
2153 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002154 * Start listening to reports when the system's default data network is active, meaning it is
2155 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2156 * to determine the current state of the system's default network after registering the
2157 * listener.
2158 * <p>
2159 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002160 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002161 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002162 *
2163 * @param l The listener to be told when the network is active.
2164 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002165 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002166 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2167 @Override
2168 public void onNetworkActive() throws RemoteException {
2169 l.onNetworkActive();
2170 }
2171 };
2172
2173 try {
2174 getNetworkManagementService().registerNetworkActivityListener(rl);
2175 mNetworkActivityListeners.put(l, rl);
2176 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002177 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002178 }
2179 }
2180
2181 /**
2182 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002183 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002184 *
2185 * @param l Previously registered listener.
2186 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002187 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002188 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002189 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002190 try {
2191 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2192 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002193 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002194 }
2195 }
2196
2197 /**
2198 * Return whether the data network is currently active. An active network means that
2199 * it is currently in a high power state for performing data transmission. On some
2200 * types of networks, it may be expensive to move and stay in such a state, so it is
2201 * more power efficient to batch network traffic together when the radio is already in
2202 * this state. This method tells you whether right now is currently a good time to
2203 * initiate network traffic, as the network is already active.
2204 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002205 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002206 try {
2207 return getNetworkManagementService().isNetworkActive();
2208 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002209 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002210 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002211 }
2212
2213 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 * {@hide}
2215 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002216 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002217 mContext = Preconditions.checkNotNull(context, "missing context");
2218 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002219 mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
Paul Jensene0bef712014-12-10 15:12:18 -05002220 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002222
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002223 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002224 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002225 public static ConnectivityManager from(Context context) {
2226 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2227 }
2228
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002229 /** @hide */
2230 public NetworkRequest getDefaultRequest() {
2231 try {
2232 // This is not racy as the default request is final in ConnectivityService.
2233 return mService.getDefaultRequest();
2234 } catch (RemoteException e) {
2235 throw e.rethrowFromSystemServer();
2236 }
2237 }
2238
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002239 /* TODO: These permissions checks don't belong in client-side code. Move them to
2240 * services.jar, possibly in com.android.server.net. */
2241
2242 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002243 public static final void enforceChangePermission(Context context) {
2244 int uid = Binder.getCallingUid();
2245 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2246 .getPackageNameForUid(context, uid), true /* throwException */);
2247 }
2248
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002249 /** {@hide} */
2250 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002251 Preconditions.checkNotNull(context, "Context cannot be null");
2252 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002253
Robert Greenwaltedb47662014-09-16 17:54:19 -07002254 if (context.getResources().getStringArray(
2255 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2256 // Have a provisioning app - must only let system apps (which check this app)
2257 // turn on tethering
2258 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002259 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002260 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002261 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002262 // If callingPkg's uid is not same as Binder.getCallingUid(),
2263 // AppOpsService throws SecurityException.
2264 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2265 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002266 }
2267 }
2268
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002269 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002270 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2271 * situations where a Context pointer is unavailable.
2272 * @hide
2273 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002274 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002275 static ConnectivityManager getInstanceOrNull() {
2276 return sInstance;
2277 }
2278
2279 /**
2280 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2281 * situations where a Context pointer is unavailable.
2282 * @hide
2283 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002284 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002285 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002286 private static ConnectivityManager getInstance() {
2287 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002288 throw new IllegalStateException("No ConnectivityManager yet constructed");
2289 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002290 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002291 }
2292
2293 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002294 * Get the set of tetherable, available interfaces. This list is limited by
2295 * device configuration and current interface existence.
2296 *
2297 * @return an array of 0 or more Strings of tetherable interface names.
2298 *
markchien40898ca2020-01-21 13:11:06 +08002299 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002300 * {@hide}
2301 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002302 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002303 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002304 @Deprecated
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002305 public String[] getTetherableIfaces() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002306 return mTetheringManager.getTetherableIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002307 }
2308
2309 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002310 * Get the set of tethered interfaces.
2311 *
2312 * @return an array of 0 or more String of currently tethered interface names.
2313 *
markchien40898ca2020-01-21 13:11:06 +08002314 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002315 * {@hide}
2316 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002317 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002318 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002319 @Deprecated
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002320 public String[] getTetheredIfaces() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002321 return mTetheringManager.getTetheredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002322 }
2323
2324 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002325 * Get the set of interface names which attempted to tether but
2326 * failed. Re-attempting to tether may cause them to reset to the Tethered
2327 * state. Alternatively, causing the interface to be destroyed and recreated
2328 * may cause them to reset to the available state.
2329 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2330 * information on the cause of the errors.
2331 *
2332 * @return an array of 0 or more String indicating the interface names
2333 * which failed to tether.
2334 *
markchien40898ca2020-01-21 13:11:06 +08002335 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002336 * {@hide}
2337 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002338 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002339 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002340 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002341 public String[] getTetheringErroredIfaces() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002342 return mTetheringManager.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002343 }
2344
2345 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002346 * Get the set of tethered dhcp ranges.
2347 *
markchien2c153702020-02-06 19:23:26 +08002348 * @deprecated This method is not supported.
2349 * TODO: remove this function when all of clients are removed.
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002350 * {@hide}
2351 */
paulhua6af6b62019-08-12 16:25:11 +08002352 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
markchien40898ca2020-01-21 13:11:06 +08002353 @Deprecated
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002354 public String[] getTetheredDhcpRanges() {
markchien2c153702020-02-06 19:23:26 +08002355 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002356 }
2357
2358 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002359 * Attempt to tether the named interface. This will setup a dhcp server
2360 * on the interface, forward and NAT IP packets and forward DNS requests
2361 * to the best active upstream network interface. Note that if no upstream
2362 * IP network interface is available, dhcp will still run and traffic will be
2363 * allowed between the tethered devices and this device, though upstream net
2364 * access will of course fail until an upstream network interface becomes
2365 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002366 *
2367 * <p>This method requires the caller to hold either the
2368 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2369 * or the ability to modify system settings as determined by
2370 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002371 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002372 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2373 * and WifiStateMachine which need direct access. All other clients should use
2374 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2375 * logic.</p>
2376 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002377 * @param iface the interface name to tether.
2378 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiene8b9d752020-01-20 19:31:56 +08002379 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002380 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002381 * {@hide}
2382 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002383 @UnsupportedAppUsage
markchiene8b9d752020-01-20 19:31:56 +08002384 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002385 public int tether(String iface) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002386 return mTetheringManager.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002387 }
2388
2389 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002390 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002391 *
2392 * <p>This method requires the caller to hold either the
2393 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2394 * or the ability to modify system settings as determined by
2395 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002396 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002397 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2398 * and WifiStateMachine which need direct access. All other clients should use
2399 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2400 * logic.</p>
2401 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002402 * @param iface the interface name to untether.
2403 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2404 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002405 * {@hide}
2406 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002407 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002408 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002409 public int untether(String iface) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002410 return mTetheringManager.untether(iface);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002411 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002412
2413 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002414 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002415 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002416 * due to device configuration.
2417 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002418 * <p>If this app does not have permission to use this API, it will always
2419 * return false rather than throw an exception.</p>
2420 *
2421 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2422 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2423 *
2424 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2425 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2426 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002427 * @return a boolean - {@code true} indicating Tethering is supported.
2428 *
markchien40898ca2020-01-21 13:11:06 +08002429 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002430 * {@hide}
2431 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002432 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002433 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2434 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002435 public boolean isTetheringSupported() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002436 return mTetheringManager.isTetheringSupported();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002437 }
2438
2439 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002440 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
markchiene8b9d752020-01-20 19:31:56 +08002441 *
2442 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002443 * @hide
2444 */
2445 @SystemApi
markchiene8b9d752020-01-20 19:31:56 +08002446 @Deprecated
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002447 public static abstract class OnStartTetheringCallback {
2448 /**
2449 * Called when tethering has been successfully started.
2450 */
Chalard Jean4d660112018-06-04 16:52:49 +09002451 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002452
2453 /**
2454 * Called when starting tethering failed.
2455 */
Chalard Jean4d660112018-06-04 16:52:49 +09002456 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002457 }
2458
2459 /**
2460 * Convenient overload for
2461 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2462 * handler to run on the current thread's {@link Looper}.
markchiene8b9d752020-01-20 19:31:56 +08002463 *
2464 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002465 * @hide
2466 */
2467 @SystemApi
markchiene8b9d752020-01-20 19:31:56 +08002468 @Deprecated
Udam Saini0e94c362017-06-07 12:06:28 -07002469 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002470 public void startTethering(int type, boolean showProvisioningUi,
2471 final OnStartTetheringCallback callback) {
2472 startTethering(type, showProvisioningUi, callback, null);
2473 }
2474
2475 /**
2476 * Runs tether provisioning for the given type if needed and then starts tethering if
2477 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2478 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2479 * schedules tether provisioning re-checks if appropriate.
2480 *
2481 * @param type The type of tethering to start. Must be one of
2482 * {@link ConnectivityManager.TETHERING_WIFI},
2483 * {@link ConnectivityManager.TETHERING_USB}, or
2484 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2485 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2486 * is one. This should be true the first time this function is called and also any time
2487 * the user can see this UI. It gives users information from their carrier about the
2488 * check failing and how they can sign up for tethering if possible.
2489 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2490 * of the result of trying to tether.
2491 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchiene8b9d752020-01-20 19:31:56 +08002492 *
2493 * @deprecated Use {@link TetheringManager#startTethering} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002494 * @hide
2495 */
2496 @SystemApi
markchiene8b9d752020-01-20 19:31:56 +08002497 @Deprecated
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002498 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002499 public void startTethering(int type, boolean showProvisioningUi,
2500 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002501 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002502
markchiene8b9d752020-01-20 19:31:56 +08002503 final Executor executor = new Executor() {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002504 @Override
markchiene8b9d752020-01-20 19:31:56 +08002505 public void execute(Runnable command) {
2506 if (handler == null) {
2507 command.run();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002508 } else {
markchiene8b9d752020-01-20 19:31:56 +08002509 handler.post(command);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002510 }
2511 }
2512 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002513
markchiene8b9d752020-01-20 19:31:56 +08002514 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
2515 @Override
2516 public void onTetheringStarted() {
2517 callback.onTetheringStarted();
2518 }
2519
2520 @Override
markchien62a625d2020-03-19 13:37:43 +08002521 public void onTetheringFailed(final int error) {
markchiene8b9d752020-01-20 19:31:56 +08002522 callback.onTetheringFailed();
2523 }
2524 };
2525
2526 final TetheringRequest request = new TetheringRequest.Builder(type)
markchien62a625d2020-03-19 13:37:43 +08002527 .setShouldShowEntitlementUi(showProvisioningUi).build();
markchiene8b9d752020-01-20 19:31:56 +08002528
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002529 mTetheringManager.startTethering(request, executor, tetheringCallback);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002530 }
2531
2532 /**
2533 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2534 * applicable.
2535 *
2536 * @param type The type of tethering to stop. Must be one of
2537 * {@link ConnectivityManager.TETHERING_WIFI},
2538 * {@link ConnectivityManager.TETHERING_USB}, or
2539 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
markchien40898ca2020-01-21 13:11:06 +08002540 *
2541 * @deprecated Use {@link TetheringManager#stopTethering} instead.
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002542 * @hide
2543 */
2544 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002545 @Deprecated
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002546 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002547 public void stopTethering(int type) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002548 mTetheringManager.stopTethering(type);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002549 }
2550
2551 /**
markchien26299ed2019-02-27 14:56:11 +08002552 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2553 * upstream status.
2554 *
Nathan Haroldedf6b3d2020-01-23 18:03:46 -08002555 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
markchien40898ca2020-01-21 13:11:06 +08002556 * @hide
markchien26299ed2019-02-27 14:56:11 +08002557 */
2558 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002559 @Deprecated
markchien26299ed2019-02-27 14:56:11 +08002560 public abstract static class OnTetheringEventCallback {
2561
2562 /**
2563 * Called when tethering upstream changed. This can be called multiple times and can be
2564 * called any time.
2565 *
2566 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2567 * have any upstream.
2568 */
2569 public void onUpstreamChanged(@Nullable Network network) {}
2570 }
2571
markchien40898ca2020-01-21 13:11:06 +08002572 @GuardedBy("mTetheringEventCallbacks")
2573 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
2574 mTetheringEventCallbacks = new ArrayMap<>();
2575
markchien26299ed2019-02-27 14:56:11 +08002576 /**
2577 * Start listening to tethering change events. Any new added callback will receive the last
markchien9f246bd2019-04-03 10:43:09 +08002578 * tethering status right away. If callback is registered when tethering has no upstream or
markchien26299ed2019-02-27 14:56:11 +08002579 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2580 * with a null argument. The same callback object cannot be registered twice.
2581 *
2582 * @param executor the executor on which callback will be invoked.
2583 * @param callback the callback to be called when tethering has change events.
markchien40898ca2020-01-21 13:11:06 +08002584 *
Nathan Haroldedf6b3d2020-01-23 18:03:46 -08002585 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
markchien26299ed2019-02-27 14:56:11 +08002586 * @hide
2587 */
2588 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002589 @Deprecated
markchien26299ed2019-02-27 14:56:11 +08002590 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2591 public void registerTetheringEventCallback(
2592 @NonNull @CallbackExecutor Executor executor,
2593 @NonNull final OnTetheringEventCallback callback) {
2594 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2595
markchien40898ca2020-01-21 13:11:06 +08002596 final TetheringEventCallback tetherCallback =
2597 new TetheringEventCallback() {
2598 @Override
2599 public void onUpstreamChanged(@Nullable Network network) {
2600 callback.onUpstreamChanged(network);
2601 }
2602 };
2603
2604 synchronized (mTetheringEventCallbacks) {
2605 mTetheringEventCallbacks.put(callback, tetherCallback);
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002606 mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
markchien40898ca2020-01-21 13:11:06 +08002607 }
markchien26299ed2019-02-27 14:56:11 +08002608 }
2609
2610 /**
2611 * Remove tethering event callback previously registered with
2612 * {@link #registerTetheringEventCallback}.
2613 *
2614 * @param callback previously registered callback.
markchien40898ca2020-01-21 13:11:06 +08002615 *
2616 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
markchien26299ed2019-02-27 14:56:11 +08002617 * @hide
2618 */
2619 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002620 @Deprecated
markchien26299ed2019-02-27 14:56:11 +08002621 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2622 public void unregisterTetheringEventCallback(
2623 @NonNull final OnTetheringEventCallback callback) {
markchien40898ca2020-01-21 13:11:06 +08002624 Objects.requireNonNull(callback, "The callback must be non-null");
2625 synchronized (mTetheringEventCallbacks) {
2626 final TetheringEventCallback tetherCallback =
2627 mTetheringEventCallbacks.remove(callback);
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002628 mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
markchien40898ca2020-01-21 13:11:06 +08002629 }
markchien26299ed2019-02-27 14:56:11 +08002630 }
2631
2632
2633 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002634 * Get the list of regular expressions that define any tetherable
2635 * USB network interfaces. If USB tethering is not supported by the
2636 * device, this list should be empty.
2637 *
2638 * @return an array of 0 or more regular expression Strings defining
2639 * what interfaces are considered tetherable usb interfaces.
2640 *
markchien40898ca2020-01-21 13:11:06 +08002641 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002642 * {@hide}
2643 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002644 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002645 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002646 @Deprecated
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002647 public String[] getTetherableUsbRegexs() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002648 return mTetheringManager.getTetherableUsbRegexs();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002649 }
2650
2651 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002652 * Get the list of regular expressions that define any tetherable
2653 * Wifi network interfaces. If Wifi tethering is not supported by the
2654 * device, this list should be empty.
2655 *
2656 * @return an array of 0 or more regular expression Strings defining
2657 * what interfaces are considered tetherable wifi interfaces.
2658 *
markchien40898ca2020-01-21 13:11:06 +08002659 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002660 * {@hide}
2661 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002662 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002663 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002664 @Deprecated
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002665 public String[] getTetherableWifiRegexs() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002666 return mTetheringManager.getTetherableWifiRegexs();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002667 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002668
Danica Chang6fdd0c62010-08-11 14:54:43 -07002669 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002670 * Get the list of regular expressions that define any tetherable
2671 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2672 * device, this list should be empty.
2673 *
2674 * @return an array of 0 or more regular expression Strings defining
2675 * what interfaces are considered tetherable bluetooth interfaces.
2676 *
markchien40898ca2020-01-21 13:11:06 +08002677 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
2678 *TetheringManager.TetheringInterfaceRegexps)} instead.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002679 * {@hide}
2680 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002681 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002682 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002683 @Deprecated
Danica Chang6fdd0c62010-08-11 14:54:43 -07002684 public String[] getTetherableBluetoothRegexs() {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002685 return mTetheringManager.getTetherableBluetoothRegexs();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002686 }
2687
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002688 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002689 * Attempt to both alter the mode of USB and Tethering of USB. A
2690 * utility method to deal with some of the complexity of USB - will
2691 * attempt to switch to Rndis and subsequently tether the resulting
2692 * interface on {@code true} or turn off tethering and switch off
2693 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002694 *
2695 * <p>This method requires the caller to hold either the
2696 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2697 * or the ability to modify system settings as determined by
2698 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002699 *
2700 * @param enable a boolean - {@code true} to enable tethering
2701 * @return error a {@code TETHER_ERROR} value indicating success or failure type
markchiene8b9d752020-01-20 19:31:56 +08002702 * @deprecated Use {@link TetheringManager#startTethering} instead
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002703 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002704 * {@hide}
2705 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002706 @UnsupportedAppUsage
markchiene8b9d752020-01-20 19:31:56 +08002707 @Deprecated
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002708 public int setUsbTethering(boolean enable) {
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002709 return mTetheringManager.setUsbTethering(enable);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002710 }
2711
markchien40898ca2020-01-21 13:11:06 +08002712 /**
2713 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
2714 * {@hide}
2715 */
markchienf2731272019-01-16 17:44:13 +08002716 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002717 @Deprecated
2718 public static final int TETHER_ERROR_NO_ERROR = TetheringManager.TETHER_ERROR_NO_ERROR;
2719 /**
2720 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
2721 * {@hide}
2722 */
2723 @Deprecated
2724 public static final int TETHER_ERROR_UNKNOWN_IFACE =
2725 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2726 /**
2727 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
2728 * {@hide}
2729 */
2730 @Deprecated
2731 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
2732 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
2733 /**
2734 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
2735 * {@hide}
2736 */
2737 @Deprecated
2738 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
2739 /**
2740 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
2741 * {@hide}
2742 */
2743 @Deprecated
2744 public static final int TETHER_ERROR_UNAVAIL_IFACE =
2745 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
2746 /**
markchien62a625d2020-03-19 13:37:43 +08002747 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
markchien40898ca2020-01-21 13:11:06 +08002748 * {@hide}
2749 */
2750 @Deprecated
markchien62a625d2020-03-19 13:37:43 +08002751 public static final int TETHER_ERROR_MASTER_ERROR =
2752 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien40898ca2020-01-21 13:11:06 +08002753 /**
2754 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
2755 * {@hide}
2756 */
2757 @Deprecated
2758 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
2759 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
2760 /**
2761 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
2762 * {@hide}
2763 */
2764 @Deprecated
2765 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
2766 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
2767 /**
markchien62a625d2020-03-19 13:37:43 +08002768 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
markchien40898ca2020-01-21 13:11:06 +08002769 * {@hide}
2770 */
2771 @Deprecated
2772 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
markchien62a625d2020-03-19 13:37:43 +08002773 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien40898ca2020-01-21 13:11:06 +08002774 /**
markchien62a625d2020-03-19 13:37:43 +08002775 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
markchien40898ca2020-01-21 13:11:06 +08002776 * {@hide}
2777 */
2778 @Deprecated
2779 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
markchien62a625d2020-03-19 13:37:43 +08002780 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
markchien40898ca2020-01-21 13:11:06 +08002781 /**
2782 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
2783 * {@hide}
2784 */
2785 @Deprecated
2786 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
2787 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
2788 /**
markchien62a625d2020-03-19 13:37:43 +08002789 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
markchien40898ca2020-01-21 13:11:06 +08002790 * {@hide}
2791 */
markchienf2731272019-01-16 17:44:13 +08002792 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002793 @Deprecated
2794 public static final int TETHER_ERROR_PROVISION_FAILED =
markchien62a625d2020-03-19 13:37:43 +08002795 TetheringManager.TETHER_ERROR_PROVISIONING_FAILED;
markchien40898ca2020-01-21 13:11:06 +08002796 /**
2797 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
2798 * {@hide}
2799 */
2800 @Deprecated
2801 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
2802 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
2803 /**
2804 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
2805 * {@hide}
2806 */
markchienf2731272019-01-16 17:44:13 +08002807 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002808 @Deprecated
2809 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN =
2810 TetheringManager.TETHER_ERROR_ENTITLEMENT_UNKNOWN;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002811
2812 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002813 * Get a more detailed error code after a Tethering or Untethering
2814 * request asynchronously failed.
2815 *
2816 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002817 * @return error The error code of the last error tethering or untethering the named
2818 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002819 *
markchien40898ca2020-01-21 13:11:06 +08002820 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
Robert Greenwalt5a735062010-03-02 17:25:02 -08002821 * {@hide}
2822 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002823 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002824 @UnsupportedAppUsage
markchien40898ca2020-01-21 13:11:06 +08002825 @Deprecated
Robert Greenwalt5a735062010-03-02 17:25:02 -08002826 public int getLastTetherError(String iface) {
markchien62a625d2020-03-19 13:37:43 +08002827 int error = mTetheringManager.getLastTetherError(iface);
2828 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
2829 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
2830 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
2831 // instead.
2832 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
2833 }
2834 return error;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002835 }
2836
markchien9554abf2019-03-06 16:25:00 +08002837 /** @hide */
2838 @Retention(RetentionPolicy.SOURCE)
2839 @IntDef(value = {
2840 TETHER_ERROR_NO_ERROR,
2841 TETHER_ERROR_PROVISION_FAILED,
2842 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2843 })
2844 public @interface EntitlementResultCode {
2845 }
2846
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002847 /**
markchien9554abf2019-03-06 16:25:00 +08002848 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchienf2731272019-01-16 17:44:13 +08002849 * entitlement succeeded.
markchien40898ca2020-01-21 13:11:06 +08002850 *
2851 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
markchienf2731272019-01-16 17:44:13 +08002852 * @hide
2853 */
2854 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002855 @Deprecated
markchien9554abf2019-03-06 16:25:00 +08002856 public interface OnTetheringEntitlementResultListener {
2857 /**
2858 * Called to notify entitlement result.
2859 *
2860 * @param resultCode an int value of entitlement result. It may be one of
2861 * {@link #TETHER_ERROR_NO_ERROR},
2862 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2863 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2864 */
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002865 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
markchien9554abf2019-03-06 16:25:00 +08002866 }
2867
2868 /**
markchienf2731272019-01-16 17:44:13 +08002869 * Get the last value of the entitlement check on this downstream. If the cached value is
2870 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2871 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2872 * guaranteed that the UI-based entitlement check will complete in any specific time period
2873 * and may in fact never complete. Any successful entitlement check the platform performs for
2874 * any reason will update the cached value.
2875 *
2876 * @param type the downstream type of tethering. Must be one of
2877 * {@link #TETHERING_WIFI},
2878 * {@link #TETHERING_USB}, or
2879 * {@link #TETHERING_BLUETOOTH}.
2880 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchien9554abf2019-03-06 16:25:00 +08002881 * @param executor the executor on which callback will be invoked.
2882 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2883 * notify the caller of the result of entitlement check. The listener may be called zero
2884 * or one time.
markchien40898ca2020-01-21 13:11:06 +08002885 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
markchienf2731272019-01-16 17:44:13 +08002886 * {@hide}
2887 */
2888 @SystemApi
markchien40898ca2020-01-21 13:11:06 +08002889 @Deprecated
markchienf2731272019-01-16 17:44:13 +08002890 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchien9554abf2019-03-06 16:25:00 +08002891 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2892 @NonNull @CallbackExecutor Executor executor,
2893 @NonNull final OnTetheringEntitlementResultListener listener) {
2894 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2895 ResultReceiver wrappedListener = new ResultReceiver(null) {
2896 @Override
2897 protected void onReceiveResult(int resultCode, Bundle resultData) {
2898 Binder.withCleanCallingIdentity(() ->
2899 executor.execute(() -> {
Jeremy Klein9f2e0f02019-03-12 13:32:08 -07002900 listener.onTetheringEntitlementResult(resultCode);
markchien9554abf2019-03-06 16:25:00 +08002901 }));
2902 }
2903 };
2904
Automerger Merge Worker6112c822020-03-06 00:38:43 +00002905 mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
markchienae8aa642019-12-16 20:15:20 +08002906 showEntitlementUi);
markchien9554abf2019-03-06 16:25:00 +08002907 }
2908
2909 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002910 * Report network connectivity status. This is currently used only
2911 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002912 * <p>This method requires the caller to hold the permission
2913 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002914 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002915 * @param networkType The type of network you want to report on
2916 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002917 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002918 * {@hide}
2919 */
2920 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002921 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002922 try {
2923 mService.reportInetCondition(networkType, percentage);
2924 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002925 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002926 }
2927 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002928
2929 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002930 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002931 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002932 * the framework to re-evaluate network connectivity and/or switch to another
2933 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002934 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002935 * @param network The {@link Network} the application was attempting to use
2936 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002937 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2938 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002939 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002940 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002941 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002942 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002943 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002944 // One of these will be ignored because it matches system's current state.
2945 // The other will trigger the necessary reevaluation.
2946 mService.reportNetworkConnectivity(network, true);
2947 mService.reportNetworkConnectivity(network, false);
2948 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002949 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002950 }
2951 }
2952
2953 /**
2954 * Report to the framework whether a network has working connectivity.
2955 * This provides a hint to the system that a particular network is providing
2956 * working connectivity or not. In response the framework may re-evaluate
2957 * the network's connectivity and might take further action thereafter.
2958 *
2959 * @param network The {@link Network} the application was attempting to use
2960 * or {@code null} to indicate the current default network.
2961 * @param hasConnectivity {@code true} if the application was able to successfully access the
2962 * Internet using {@code network} or {@code false} if not.
2963 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002964 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002965 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002966 try {
2967 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002968 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002969 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002970 }
2971 }
2972
2973 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002974 * Set a network-independent global http proxy. This is not normally what you want
2975 * for typical HTTP proxies - they are general network dependent. However if you're
2976 * doing something unusual like general internal filtering this may be useful. On
2977 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002978 *
2979 * @param p A {@link ProxyInfo} object defining the new global
2980 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002981 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002982 */
paulhua6af6b62019-08-12 16:25:11 +08002983 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Jason Monk207900c2014-04-25 15:00:09 -04002984 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002985 try {
2986 mService.setGlobalProxy(p);
2987 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002988 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002989 }
2990 }
2991
2992 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002993 * Retrieve any network-independent global HTTP proxy.
2994 *
Jason Monk207900c2014-04-25 15:00:09 -04002995 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002996 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002997 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002998 */
Jason Monk207900c2014-04-25 15:00:09 -04002999 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003000 try {
3001 return mService.getGlobalProxy();
3002 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003003 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003004 }
3005 }
3006
3007 /**
Paul Jensencee9b512015-05-06 07:32:40 -04003008 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3009 * network-specific HTTP proxy. If {@code network} is null, the
3010 * network-specific proxy returned is the proxy of the default active
3011 * network.
3012 *
3013 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3014 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3015 * or when {@code network} is {@code null},
3016 * the {@code ProxyInfo} for the default active network. Returns
3017 * {@code null} when no proxy applies or the caller doesn't have
3018 * permission to use {@code network}.
3019 * @hide
3020 */
3021 public ProxyInfo getProxyForNetwork(Network network) {
3022 try {
3023 return mService.getProxyForNetwork(network);
3024 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003025 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04003026 }
3027 }
3028
3029 /**
Paul Jensene0bef712014-12-10 15:12:18 -05003030 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3031 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04003032 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05003033 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003034 *
Jason Monk207900c2014-04-25 15:00:09 -04003035 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003036 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07003037 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003038 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05003039 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04003040 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07003041 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003042
3043 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003044 * Returns true if the hardware supports the given network type
3045 * else it returns false. This doesn't indicate we have coverage
3046 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003047 * hardware supports it. For example a GSM phone without a SIM
3048 * should still return {@code true} for mobile data, but a wifi only
3049 * tablet would return {@code false}.
3050 *
3051 * @param networkType The network type we'd like to check
3052 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003053 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003054 * @hide
3055 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003056 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003057 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean0bb53dbb2019-04-09 15:46:21 +09003058 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003059 public boolean isNetworkSupported(int networkType) {
3060 try {
3061 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003062 } catch (RemoteException e) {
3063 throw e.rethrowFromSystemServer();
3064 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003065 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003066
3067 /**
3068 * Returns if the currently active data network is metered. A network is
3069 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003070 * that connection due to monetary costs, data limitations or
3071 * battery/performance issues. You should check this before doing large
3072 * data transfers, and warn the user or delay the operation until another
3073 * network is available.
3074 *
3075 * @return {@code true} if large transfers should be avoided, otherwise
3076 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003077 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003078 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003079 public boolean isActiveNetworkMetered() {
3080 try {
3081 return mService.isActiveNetworkMetered();
3082 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003083 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003084 }
3085 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003086
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003087 /**
3088 * If the LockdownVpn mechanism is enabled, updates the vpn
3089 * with a reload of its profile.
3090 *
3091 * @return a boolean with {@code} indicating success
3092 *
3093 * <p>This method can only be called by the system UID
3094 * {@hide}
3095 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003096 public boolean updateLockdownVpn() {
3097 try {
3098 return mService.updateLockdownVpn();
3099 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003100 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003101 }
3102 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07003103
3104 /**
Wink Saville948282b2013-08-29 08:55:16 -07003105 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07003106 *
Wink Savilleab9321d2013-06-29 21:10:57 -07003107 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07003108 *
3109 * @return time out that will be used, maybe less that suggestedTimeOutMs
3110 * -1 if an error.
3111 *
3112 * {@hide}
3113 */
Wink Saville948282b2013-08-29 08:55:16 -07003114 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003115 int timeOutMs = -1;
3116 try {
Wink Saville948282b2013-08-29 08:55:16 -07003117 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07003118 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003119 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07003120 }
3121 return timeOutMs;
3122 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003123
3124 /**
Wink Saville42d4f082013-07-20 20:31:59 -07003125 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003126 * {@hide}
3127 */
paulhua6af6b62019-08-12 16:25:11 +08003128 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003129 public String getMobileProvisioningUrl() {
3130 try {
3131 return mService.getMobileProvisioningUrl();
3132 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003133 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003134 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003135 }
Wink Saville42d4f082013-07-20 20:31:59 -07003136
3137 /**
Wink Saville948282b2013-08-29 08:55:16 -07003138 * Set sign in error notification to visible or in visible
3139 *
Wink Saville948282b2013-08-29 08:55:16 -07003140 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04003141 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07003142 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003143 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07003144 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003145 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003146 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04003147 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07003148 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003149 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07003150 }
3151 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003152
3153 /**
3154 * Set the value for enabling/disabling airplane mode
3155 *
3156 * @param enable whether to enable airplane mode or not
3157 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003158 * @hide
3159 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003160 @RequiresPermission(anyOf = {
Edward Savage-Jonesaffb2292019-11-26 13:18:08 +01003161 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003162 android.Manifest.permission.NETWORK_SETTINGS,
3163 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3164 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09003165 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003166 public void setAirplaneMode(boolean enable) {
3167 try {
3168 mService.setAirplaneMode(enable);
3169 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003170 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003171 }
3172 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003173
Chalard Jean05ab6812018-05-02 21:14:54 +09003174 /** {@hide} - returns the factory serial number */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003175 @UnsupportedAppUsage
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003176 @RequiresPermission(anyOf = {
3177 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3178 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean05ab6812018-05-02 21:14:54 +09003179 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003180 try {
Chalard Jean05ab6812018-05-02 21:14:54 +09003181 return mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003182 } catch (RemoteException e) {
3183 throw e.rethrowFromSystemServer();
3184 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003185 }
3186
3187 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00003188 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003189 @RequiresPermission(anyOf = {
3190 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3191 android.Manifest.permission.NETWORK_FACTORY})
Robert Greenwalta67be032014-05-16 15:49:14 -07003192 public void unregisterNetworkFactory(Messenger messenger) {
3193 try {
3194 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003195 } catch (RemoteException e) {
3196 throw e.rethrowFromSystemServer();
3197 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003198 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003199
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003200 /**
3201 * Registers the specified {@link NetworkProvider}.
3202 * Each listener must only be registered once. The listener can be unregistered with
3203 * {@link #unregisterNetworkProvider}.
3204 *
3205 * @param provider the provider to register
3206 * @return the ID of the provider. This ID must be used by the provider when registering
3207 * {@link android.net.NetworkAgent}s.
3208 * @hide
3209 */
3210 @SystemApi
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003211 @RequiresPermission(anyOf = {
3212 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3213 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003214 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3215 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003216 throw new IllegalStateException("NetworkProviders can only be registered once");
3217 }
3218
3219 try {
3220 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3221 provider.getName());
3222 provider.setProviderId(providerId);
3223 } catch (RemoteException e) {
3224 throw e.rethrowFromSystemServer();
3225 }
3226 return provider.getProviderId();
3227 }
3228
3229 /**
3230 * Unregisters the specified NetworkProvider.
3231 *
3232 * @param provider the provider to unregister
3233 * @hide
3234 */
3235 @SystemApi
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003236 @RequiresPermission(anyOf = {
3237 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3238 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003239 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3240 try {
3241 mService.unregisterNetworkProvider(provider.getMessenger());
3242 } catch (RemoteException e) {
3243 throw e.rethrowFromSystemServer();
3244 }
3245 provider.setProviderId(NetworkProvider.ID_NONE);
3246 }
3247
3248
3249 /** @hide exposed via the NetworkProvider class. */
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003250 @RequiresPermission(anyOf = {
3251 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3252 android.Manifest.permission.NETWORK_FACTORY})
Lorenzo Colittiae5cb712020-01-08 00:04:09 +09003253 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3254 try {
3255 mService.declareNetworkRequestUnfulfillable(request);
3256 } catch (RemoteException e) {
3257 throw e.rethrowFromSystemServer();
3258 }
3259 }
3260
Chalard Jean05ab6812018-05-02 21:14:54 +09003261 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3262 // of dependent changes that would conflict throughout the automerger graph. Having this
3263 // temporarily helps with the process of going through with all these dependent changes across
3264 // the entire tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05003265 /**
3266 * @hide
3267 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003268 * @return Network corresponding to NetworkAgent.
Paul Jensen31a94f42015-02-13 14:18:39 -05003269 */
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003270 @RequiresPermission(anyOf = {
3271 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3272 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003273 public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Lorenzo Colittid9696562020-01-12 22:28:37 +09003274 NetworkCapabilities nc, int score, NetworkAgentConfig config) {
Chalard Jeana11593c2020-02-21 19:37:21 +09003275 return registerNetworkAgent(messenger, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
Chalard Jean05ab6812018-05-02 21:14:54 +09003276 }
3277
3278 /**
3279 * @hide
3280 * Register a NetworkAgent with ConnectivityService.
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003281 * @return Network corresponding to NetworkAgent.
Chalard Jean05ab6812018-05-02 21:14:54 +09003282 */
Automerger Merge Worker8a8e8a12020-03-04 18:04:01 +00003283 @RequiresPermission(anyOf = {
3284 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3285 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeana0e2aa122019-12-13 19:47:12 +09003286 public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Chalard Jeana11593c2020-02-21 19:37:21 +09003287 NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003288 try {
Lorenzo Colittid9696562020-01-12 22:28:37 +09003289 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, config, providerId);
Paul Jensen31a94f42015-02-13 14:18:39 -05003290 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003291 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05003292 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003293 }
3294
Robert Greenwalt9258c642014-03-26 16:47:06 -07003295 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003296 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3297 * changes. Should be extended by applications wanting notifications.
3298 *
3299 * A {@code NetworkCallback} is registered by calling
3300 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3301 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09003302 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09003303 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3304 * A {@code NetworkCallback} should be registered at most once at any time.
3305 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003306 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003307 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003308 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003309 * Called when the framework connects to a new network to evaluate whether it satisfies this
3310 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3311 * callback. There is no guarantee that this new network will satisfy any requests, or that
3312 * the network will stay connected for longer than the time necessary to evaluate it.
3313 * <p>
3314 * Most applications <b>should not</b> act on this callback, and should instead use
3315 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3316 * the framework in properly evaluating the network &mdash; for example, an application that
3317 * can automatically log in to a captive portal without user intervention.
3318 *
3319 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09003320 *
3321 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07003322 */
paulhu3d67f532019-03-22 16:35:06 +08003323 public void onPreCheck(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003324
3325 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003326 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003327 * This callback may be called more than once if the {@link Network} that is
3328 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003329 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003330 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003331 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3332 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08003333 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003334 * @hide
3335 */
paulhu3d67f532019-03-22 16:35:06 +08003336 public void onAvailable(@NonNull Network network,
3337 @NonNull NetworkCapabilities networkCapabilities,
3338 @NonNull LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003339 // Internally only this method is called when a new network is available, and
3340 // it calls the callback in the same way and order that older versions used
3341 // to call so as not to change the behavior.
3342 onAvailable(network);
3343 if (!networkCapabilities.hasCapability(
3344 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3345 onNetworkSuspended(network);
3346 }
3347 onCapabilitiesChanged(network, networkCapabilities);
3348 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003349 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003350 }
3351
3352 /**
3353 * Called when the framework connects and has declared a new network ready for use.
Chalard Jean599ce752019-08-30 16:27:28 +09003354 *
3355 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3356 * be available at the same time, and onAvailable will be called for each of these as they
3357 * appear.
3358 *
3359 * <p>For callbacks registered with {@link #requestNetwork} and
3360 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
3361 * is the new best network for this request and is now tracked by this callback ; this
3362 * callback will no longer receive method calls about other networks that may have been
3363 * passed to this method previously. The previously-best network may have disconnected, or
3364 * it may still be around and the newly-best network may simply be better.
3365 *
3366 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
3367 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
3368 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
3369 * to {@link #onBlockedStatusChanged(Network, boolean)}.
3370 *
3371 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3372 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3373 * this callback as this is prone to race conditions (there is no guarantee the objects
3374 * returned by these methods will be current). Instead, wait for a call to
3375 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
3376 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
3377 * to be well-ordered with respect to other callbacks.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003378 *
3379 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003380 */
paulhu3d67f532019-03-22 16:35:06 +08003381 public void onAvailable(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003382
3383 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003384 * Called when the network is about to be lost, typically because there are no outstanding
3385 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
3386 * with the new replacement network for graceful handover. This method is not guaranteed
3387 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
3388 * network is suddenly disconnected.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003389 *
Chalard Jean599ce752019-08-30 16:27:28 +09003390 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3391 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3392 * this callback as this is prone to race conditions ; calling these methods while in a
3393 * callback may return an outdated or even a null object.
3394 *
3395 * @param network The {@link Network} that is about to be lost.
3396 * @param maxMsToLive The time in milliseconds the system intends to keep the network
3397 * connected for graceful handover; note that the network may still
3398 * suffer a hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003399 */
paulhu3d67f532019-03-22 16:35:06 +08003400 public void onLosing(@NonNull Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003401
3402 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003403 * Called when a network disconnects or otherwise no longer satisfies this request or
3404 * callback.
3405 *
3406 * <p>If the callback was registered with requestNetwork() or
3407 * registerDefaultNetworkCallback(), it will only be invoked against the last network
3408 * returned by onAvailable() when that network is lost and no other network satisfies
3409 * the criteria of the request.
3410 *
3411 * <p>If the callback was registered with registerNetworkCallback() it will be called for
3412 * each network which no longer satisfies the criteria of the callback.
3413 *
3414 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3415 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3416 * this callback as this is prone to race conditions ; calling these methods while in a
3417 * callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003418 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003419 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003420 */
paulhu3d67f532019-03-22 16:35:06 +08003421 public void onLost(@NonNull Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003422
3423 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003424 * Called if no network is found within the timeout time specified in
Etan Cohenddb720a2019-01-08 12:09:18 -08003425 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3426 * requested network request cannot be fulfilled (whether or not a timeout was
3427 * specified). When this callback is invoked the associated
Etan Cohenaebf17e2017-03-01 12:47:28 -08003428 * {@link NetworkRequest} will have already been removed and released, as if
3429 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003430 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003431 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003432
3433 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003434 * Called when the network corresponding to this request changes capabilities but still
3435 * satisfies the requested criteria.
3436 *
3437 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3438 * to be called immediately after {@link #onAvailable}.
3439 *
3440 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
3441 * ConnectivityManager methods in this callback as this is prone to race conditions :
3442 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003443 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003444 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003445 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3446 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003447 */
paulhu3d67f532019-03-22 16:35:06 +08003448 public void onCapabilitiesChanged(@NonNull Network network,
3449 @NonNull NetworkCapabilities networkCapabilities) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003450
3451 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003452 * Called when the network corresponding to this request changes {@link LinkProperties}.
3453 *
3454 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
3455 * to be called immediately after {@link #onAvailable}.
3456 *
3457 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
3458 * ConnectivityManager methods in this callback as this is prone to race conditions :
3459 * calling these methods while in a callback may return an outdated or even a null object.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003460 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003461 * @param network The {@link Network} whose link properties have changed.
3462 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003463 */
paulhu3d67f532019-03-22 16:35:06 +08003464 public void onLinkPropertiesChanged(@NonNull Network network,
3465 @NonNull LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003466
Robert Greenwalt8d482522015-06-24 13:23:42 -07003467 /**
Chalard Jean599ce752019-08-30 16:27:28 +09003468 * Called when the network the framework connected to for this request suspends data
3469 * transmission temporarily.
3470 *
3471 * <p>This generally means that while the TCP connections are still live temporarily
3472 * network data fails to transfer. To give a specific example, this is used on cellular
3473 * networks to mask temporary outages when driving through a tunnel, etc. In general this
3474 * means read operations on sockets on this network will block once the buffers are
3475 * drained, and write operations will block once the buffers are full.
3476 *
3477 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3478 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3479 * this callback as this is prone to race conditions (there is no guarantee the objects
3480 * returned by these methods will be current).
3481 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003482 * @hide
3483 */
paulhu3d67f532019-03-22 16:35:06 +08003484 public void onNetworkSuspended(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003485
3486 /**
3487 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003488 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3489 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Chalard Jean599ce752019-08-30 16:27:28 +09003490
3491 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3492 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3493 * this callback as this is prone to race conditions : calling these methods while in a
3494 * callback may return an outdated or even a null object.
3495 *
Robert Greenwalt8d482522015-06-24 13:23:42 -07003496 * @hide
3497 */
paulhu3d67f532019-03-22 16:35:06 +08003498 public void onNetworkResumed(@NonNull Network network) {}
Robert Greenwalt8d482522015-06-24 13:23:42 -07003499
junyulai05986c62018-08-07 19:50:45 +08003500 /**
3501 * Called when access to the specified network is blocked or unblocked.
3502 *
Chalard Jean599ce752019-08-30 16:27:28 +09003503 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
3504 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
3505 * this callback as this is prone to race conditions : calling these methods while in a
3506 * callback may return an outdated or even a null object.
3507 *
junyulai05986c62018-08-07 19:50:45 +08003508 * @param network The {@link Network} whose blocked status has changed.
3509 * @param blocked The blocked status of this {@link Network}.
3510 */
junyulai0c666972019-03-04 22:45:36 +08003511 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
junyulai05986c62018-08-07 19:50:45 +08003512
Robert Greenwalt6078b502014-06-11 16:05:07 -07003513 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003514 }
3515
Hugo Benichicb883232017-05-11 13:16:17 +09003516 /**
3517 * Constant error codes used by ConnectivityService to communicate about failures and errors
3518 * across a Binder boundary.
3519 * @hide
3520 */
3521 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003522 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003523 }
3524
3525 /** @hide */
3526 public static class TooManyRequestsException extends RuntimeException {}
3527
3528 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3529 switch (e.errorCode) {
3530 case Errors.TOO_MANY_REQUESTS:
3531 return new TooManyRequestsException();
3532 default:
3533 Log.w(TAG, "Unknown service error code " + e.errorCode);
3534 return new RuntimeException(e);
3535 }
3536 }
3537
Robert Greenwalt9258c642014-03-26 16:47:06 -07003538 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003539 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003540 public static final int CALLBACK_PRECHECK = BASE + 1;
3541 /** @hide */
3542 public static final int CALLBACK_AVAILABLE = BASE + 2;
3543 /** @hide arg1 = TTL */
3544 public static final int CALLBACK_LOSING = BASE + 3;
3545 /** @hide */
3546 public static final int CALLBACK_LOST = BASE + 4;
3547 /** @hide */
3548 public static final int CALLBACK_UNAVAIL = BASE + 5;
3549 /** @hide */
3550 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3551 /** @hide */
3552 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003553 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003554 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003555 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003556 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003557 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003558 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003559 /** @hide */
3560 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003561
Erik Kline57faba92015-11-25 12:49:38 +09003562 /** @hide */
3563 public static String getCallbackName(int whichCallback) {
3564 switch (whichCallback) {
3565 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3566 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3567 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3568 case CALLBACK_LOST: return "CALLBACK_LOST";
3569 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3570 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3571 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003572 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3573 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3574 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003575 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003576 default:
3577 return Integer.toString(whichCallback);
3578 }
3579 }
3580
Robert Greenwalt562cc542014-05-15 18:07:26 -07003581 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003582 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003583 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003584
Hugo Benichid42650f2016-07-06 22:53:17 +09003585 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003586 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003587 }
3588
Hugo Benichi2583ef02017-02-02 17:02:36 +09003589 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003590 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003591 }
3592
Robert Greenwalt9258c642014-03-26 16:47:06 -07003593 @Override
3594 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003595 if (message.what == EXPIRE_LEGACY_REQUEST) {
3596 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3597 return;
3598 }
3599
3600 final NetworkRequest request = getObject(message, NetworkRequest.class);
3601 final Network network = getObject(message, Network.class);
3602 final NetworkCallback callback;
3603 synchronized (sCallbacks) {
3604 callback = sCallbacks.get(request);
Etan Cohen4a62d1d2019-05-21 12:06:04 -07003605 if (callback == null) {
3606 Log.w(TAG,
3607 "callback not found for " + getCallbackName(message.what) + " message");
3608 return;
3609 }
Etan Cohen9b09a162019-04-16 15:07:55 -07003610 if (message.what == CALLBACK_UNAVAIL) {
3611 sCallbacks.remove(request);
3612 callback.networkRequest = ALREADY_UNREGISTERED;
3613 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003614 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003615 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003616 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003617 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003618
Robert Greenwalt9258c642014-03-26 16:47:06 -07003619 switch (message.what) {
3620 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003621 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003622 break;
3623 }
3624 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003625 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3626 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003627 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003628 break;
3629 }
3630 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003631 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003632 break;
3633 }
3634 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003635 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003636 break;
3637 }
3638 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003639 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003640 break;
3641 }
3642 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003643 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3644 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003645 break;
3646 }
3647 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003648 LinkProperties lp = getObject(message, LinkProperties.class);
3649 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003650 break;
3651 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003652 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003653 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003654 break;
3655 }
3656 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003657 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003658 break;
3659 }
junyulai05986c62018-08-07 19:50:45 +08003660 case CALLBACK_BLK_CHANGED: {
3661 boolean blocked = message.arg1 != 0;
3662 callback.onBlockedStatusChanged(network, blocked);
3663 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003664 }
3665 }
3666
Hugo Benichid42650f2016-07-06 22:53:17 +09003667 private <T> T getObject(Message msg, Class<T> c) {
3668 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003669 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003670 }
3671
Hugo Benichi2583ef02017-02-02 17:02:36 +09003672 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003673 synchronized (sCallbacks) {
3674 if (sCallbackHandler == null) {
3675 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003676 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003677 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003678 }
3679 }
3680
Hugo Benichi6f260f32017-02-03 14:18:44 +09003681 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3682 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003683
Hugo Benichi6f260f32017-02-03 14:18:44 +09003684 private static final int LISTEN = 1;
3685 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003686
Hugo Benichi6f260f32017-02-03 14:18:44 +09003687 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3688 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003689 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003690 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003691 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003692 final NetworkRequest request;
Roshan Piuse38acab2020-01-16 12:17:17 -08003693 final String callingPackageName = mContext.getOpPackageName();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003694 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003695 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003696 if (callback.networkRequest != null
3697 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003698 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3699 // and requests (http://b/20701525).
3700 Log.e(TAG, "NetworkCallback was already registered");
3701 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003702 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003703 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003704 if (action == LISTEN) {
Roshan Piuse38acab2020-01-16 12:17:17 -08003705 request = mService.listenForNetwork(
3706 need, messenger, binder, callingPackageName);
Paul Jensen7221cc32014-06-27 11:05:32 -04003707 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003708 request = mService.requestNetwork(
Roshan Piuse38acab2020-01-16 12:17:17 -08003709 need, messenger, timeoutMs, binder, legacyType, callingPackageName);
Paul Jensen7221cc32014-06-27 11:05:32 -04003710 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003711 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003712 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003713 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003714 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003715 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003716 } catch (RemoteException e) {
3717 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003718 } catch (ServiceSpecificException e) {
3719 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003720 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003721 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003722 }
3723
3724 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003725 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003726 *
markchien97c029e2020-03-18 21:16:15 +08003727 * This API is only for use in internal system code that requests networks with legacy type and
3728 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
markchienace1d342020-01-14 12:54:40 +08003729 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003730 *
markchienace1d342020-01-14 12:54:40 +08003731 * @param request {@link NetworkRequest} describing this request.
markchienace1d342020-01-14 12:54:40 +08003732 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3733 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3734 * be a positive value (i.e. >0).
3735 * @param legacyType to specify the network type(#TYPE_*).
3736 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
markchien97c029e2020-03-18 21:16:15 +08003737 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3738 * the callback must not be shared - it uniquely specifies this request.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003739 *
3740 * @hide
3741 */
markchienace1d342020-01-14 12:54:40 +08003742 @SystemApi
markchien97c029e2020-03-18 21:16:15 +08003743 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003744 public void requestNetwork(@NonNull NetworkRequest request,
markchien97c029e2020-03-18 21:16:15 +08003745 int timeoutMs, int legacyType, @NonNull Handler handler,
3746 @NonNull NetworkCallback networkCallback) {
3747 if (legacyType == TYPE_NONE) {
3748 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
3749 }
Hugo Benichi2583ef02017-02-02 17:02:36 +09003750 CallbackHandler cbHandler = new CallbackHandler(handler);
3751 NetworkCapabilities nc = request.networkCapabilities;
3752 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003753 }
3754
3755 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003756 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003757 *
Chalard Jean599ce752019-08-30 16:27:28 +09003758 * <p>This method will attempt to find the best network that matches the passed
3759 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
3760 * criteria. The platform will evaluate which network is the best at its own discretion.
3761 * Throughput, latency, cost per byte, policy, user preference and other considerations
3762 * may be factored in the decision of what is considered the best network.
3763 *
3764 * <p>As long as this request is outstanding, the platform will try to maintain the best network
3765 * matching this request, while always attempting to match the request to a better network if
3766 * possible. If a better match is found, the platform will switch this request to the now-best
3767 * network and inform the app of the newly best network by invoking
3768 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
3769 * will not try to maintain any other network than the best one currently matching the request:
3770 * a network not matching any network request may be disconnected at any time.
3771 *
3772 * <p>For example, an application could use this method to obtain a connected cellular network
3773 * even if the device currently has a data connection over Ethernet. This may cause the cellular
3774 * radio to consume additional power. Or, an application could inform the system that it wants
3775 * a network supporting sending MMSes and have the system let it know about the currently best
3776 * MMS-supporting network through the provided {@link NetworkCallback}.
3777 *
3778 * <p>The status of the request can be followed by listening to the various callbacks described
3779 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
3780 * used to direct traffic to the network (although accessing some networks may be subject to
3781 * holding specific permissions). Callers will learn about the specific characteristics of the
3782 * network through
3783 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
3784 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
3785 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
3786 * matching the request at any given time; therefore when a better network matching the request
3787 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
3788 * with the new network after which no further updates are given about the previously-best
3789 * network, unless it becomes the best again at some later time. All callbacks are invoked
3790 * in order on the same thread, which by default is a thread created by the framework running
3791 * in the app.
3792 * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
3793 * callbacks are invoked.
3794 *
3795 * <p>This{@link NetworkRequest} will live until released via
3796 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
3797 * which point the system may let go of the network at any time.
3798 *
3799 * <p>A version of this method which takes a timeout is
3800 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
3801 * wait for a limited amount of time for the network to become unavailable.
3802 *
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003803 * <p>It is presently unsupported to request a network with mutable
3804 * {@link NetworkCapabilities} such as
3805 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3806 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3807 * as these {@code NetworkCapabilities} represent states that a particular
3808 * network may never attain, and whether a network will attain these states
3809 * is unknown prior to bringing up the network so the framework does not
Chalard Jean599ce752019-08-30 16:27:28 +09003810 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003811 *
3812 * <p>This method requires the caller to hold either the
3813 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3814 * or the ability to modify system settings as determined by
3815 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003816 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003817 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003818 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3819 * the callback must not be shared - it uniquely specifies this request.
3820 * The callback is invoked on the default internal Handler.
Chalard Jean92c8b672019-05-13 15:13:58 +09003821 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3822 * @throws SecurityException if missing the appropriate permissions.
3823 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003824 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003825 public void requestNetwork(@NonNull NetworkRequest request,
3826 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003827 requestNetwork(request, networkCallback, getDefaultHandler());
3828 }
3829
3830 /**
3831 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3832 *
Chalard Jean599ce752019-08-30 16:27:28 +09003833 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
3834 * but runs all the callbacks on the passed Handler.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003835 *
Chalard Jean599ce752019-08-30 16:27:28 +09003836 * <p>This method has the same permission requirements as
3837 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3838 * the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003839 *
3840 * @param request {@link NetworkRequest} describing this request.
3841 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3842 * the callback must not be shared - it uniquely specifies this request.
3843 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003844 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003845 public void requestNetwork(@NonNull NetworkRequest request,
3846 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003847 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien97c029e2020-03-18 21:16:15 +08003848 NetworkCapabilities nc = request.networkCapabilities;
3849 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003850 }
3851
3852 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003853 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3854 * by a timeout.
3855 *
3856 * This function behaves identically to the non-timed-out version
3857 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3858 * is not found within the given time (in milliseconds) the
3859 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3860 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3861 * not have to be released if timed-out (it is automatically released). Unregistering a
3862 * request that timed out is not an error.
3863 *
3864 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3865 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3866 * for that purpose. Calling this method will attempt to bring up the requested network.
3867 *
Chalard Jean599ce752019-08-30 16:27:28 +09003868 * <p>This method has the same permission requirements as
3869 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and throws the same exceptions in
3870 * the same conditions.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003871 *
3872 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003873 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3874 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003875 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3876 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3877 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003878 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003879 public void requestNetwork(@NonNull NetworkRequest request,
3880 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003881 checkTimeout(timeoutMs);
markchien97c029e2020-03-18 21:16:15 +08003882 NetworkCapabilities nc = request.networkCapabilities;
3883 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
3884 getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003885 }
3886
Hugo Benichi2583ef02017-02-02 17:02:36 +09003887 /**
3888 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3889 * by a timeout.
3890 *
Chalard Jean599ce752019-08-30 16:27:28 +09003891 * This method behaves identically to
3892 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
3893 * on the passed Handler.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003894 *
Chalard Jean599ce752019-08-30 16:27:28 +09003895 * <p>This method has the same permission requirements as
3896 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} and throws the same exceptions
3897 * in the same conditions.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003898 *
3899 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003900 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3901 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003902 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003903 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3904 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003905 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003906 public void requestNetwork(@NonNull NetworkRequest request,
3907 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003908 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003909 CallbackHandler cbHandler = new CallbackHandler(handler);
markchien97c029e2020-03-18 21:16:15 +08003910 NetworkCapabilities nc = request.networkCapabilities;
3911 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003912 }
3913
3914 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003915 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003916 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003917 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003918 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003919 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3920 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003921 */
Erik Kline90e93072014-11-19 12:12:24 +09003922 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003923
3924 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003925 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003926 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003927 * {@link android.content.Intent#getParcelableExtra(String)}.
3928 */
Erik Kline90e93072014-11-19 12:12:24 +09003929 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003930
3931
3932 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003933 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003934 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003935 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003936 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003937 * the request may outlive the calling application and get called back when a suitable
3938 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003939 * <p>
3940 * The operation is an Intent broadcast that goes to a broadcast receiver that
3941 * you registered with {@link Context#registerReceiver} or through the
3942 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3943 * <p>
3944 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003945 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3946 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003947 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003948 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003949 * Intent to reserve the network or it will be released shortly after the Intent
3950 * is processed.
3951 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003952 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003953 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003954 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003955 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003956 * The request may be released normally by calling
3957 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003958 * <p>It is presently unsupported to request a network with either
3959 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3960 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3961 * as these {@code NetworkCapabilities} represent states that a particular
3962 * network may never attain, and whether a network will attain these states
3963 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003964 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003965 *
3966 * <p>This method requires the caller to hold either the
3967 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3968 * or the ability to modify system settings as determined by
3969 * {@link android.provider.Settings.System#canWrite}.</p>
3970 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003971 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003972 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003973 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003974 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Chalard Jean92c8b672019-05-13 15:13:58 +09003975 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
3976 * @throws SecurityException if missing the appropriate permissions.
3977 * @throws RuntimeException if request limit per UID is exceeded.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003978 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003979 public void requestNetwork(@NonNull NetworkRequest request,
3980 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003981 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003982 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003983 try {
Roshan Piuse38acab2020-01-16 12:17:17 -08003984 mService.pendingRequestForNetwork(
Qingxi Li9c5d8b92020-01-08 12:51:49 -08003985 request.networkCapabilities, operation, mContext.getOpPackageName());
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003986 } catch (RemoteException e) {
3987 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003988 } catch (ServiceSpecificException e) {
3989 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003990 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003991 }
3992
3993 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003994 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3995 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003996 * This method has the same behavior as
3997 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003998 * releasing network resources and disconnecting.
3999 *
4000 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4001 * PendingIntent passed to
4002 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4003 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4004 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004005 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004006 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004007 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004008 try {
4009 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004010 } catch (RemoteException e) {
4011 throw e.rethrowFromSystemServer();
4012 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004013 }
4014
Hugo Benichie7678512017-05-09 15:19:01 +09004015 private static void checkPendingIntentNotNull(PendingIntent intent) {
4016 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
4017 }
4018
4019 private static void checkCallbackNotNull(NetworkCallback callback) {
4020 Preconditions.checkNotNull(callback, "null NetworkCallback");
4021 }
4022
4023 private static void checkTimeout(int timeoutMs) {
4024 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004025 }
4026
4027 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07004028 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07004029 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08004030 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4031 * called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004032 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07004033 * @param request {@link NetworkRequest} describing this request.
4034 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4035 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004036 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004037 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004038 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004039 public void registerNetworkCallback(@NonNull NetworkRequest request,
4040 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004041 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4042 }
4043
4044 /**
4045 * Registers to receive notifications about all networks which satisfy the given
4046 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08004047 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4048 * called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004049 *
4050 * @param request {@link NetworkRequest} describing this request.
4051 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4052 * networks change state.
4053 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004054 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004055 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004056 public void registerNetworkCallback(@NonNull NetworkRequest request,
4057 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004058 CallbackHandler cbHandler = new CallbackHandler(handler);
4059 NetworkCapabilities nc = request.networkCapabilities;
4060 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004061 }
4062
4063 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04004064 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4065 * {@link NetworkRequest}.
4066 *
4067 * This function behaves identically to the version that takes a NetworkCallback, but instead
4068 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4069 * the request may outlive the calling application and get called back when a suitable
4070 * network is found.
4071 * <p>
4072 * The operation is an Intent broadcast that goes to a broadcast receiver that
4073 * you registered with {@link Context#registerReceiver} or through the
4074 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4075 * <p>
4076 * The operation Intent is delivered with two extras, a {@link Network} typed
4077 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4078 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4079 * the original requests parameters.
4080 * <p>
4081 * If there is already a request for this Intent registered (with the equality of
4082 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4083 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4084 * <p>
4085 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004086 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04004087 * @param request {@link NetworkRequest} describing this request.
4088 * @param operation Action to perform when the network is available (corresponds
4089 * to the {@link NetworkCallback#onAvailable} call. Typically
4090 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4091 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004092 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004093 public void registerNetworkCallback(@NonNull NetworkRequest request,
4094 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004095 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004096 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04004097 try {
Roshan Piuse38acab2020-01-16 12:17:17 -08004098 mService.pendingListenForNetwork(
Qingxi Li9c5d8b92020-01-08 12:51:49 -08004099 request.networkCapabilities, operation, mContext.getOpPackageName());
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004100 } catch (RemoteException e) {
4101 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09004102 } catch (ServiceSpecificException e) {
4103 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004104 }
Paul Jensen694f2b82015-06-17 14:15:39 -04004105 }
4106
4107 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004108 * Registers to receive notifications about changes in the system default network. The callbacks
4109 * will continue to be called until either the application exits or
4110 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09004111 *
4112 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4113 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004114 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09004115 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004116 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004117 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09004118 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4119 }
4120
4121 /**
4122 * Registers to receive notifications about changes in the system default network. The callbacks
4123 * will continue to be called until either the application exits or
4124 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004125 *
4126 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4127 * system default network changes.
4128 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004129 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004130 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004131 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4132 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09004133 // This works because if the NetworkCapabilities are null,
4134 // ConnectivityService takes them from the default request.
4135 //
4136 // Since the capabilities are exactly the same as the default request's
4137 // capabilities, this request is guaranteed, at all times, to be
4138 // satisfied by the same network, if any, that satisfies the default
4139 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09004140 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09004141 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
4142 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09004143 }
4144
4145 /**
fengludb571472015-04-21 17:12:05 -07004146 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4147 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4148 * network connection for updated bandwidth information. The caller will be notified via
4149 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004150 * method assumes that the caller has previously called
4151 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4152 * changes.
fenglub15e72b2015-03-20 11:29:56 -07004153 *
fengluae519192015-04-27 14:28:04 -07004154 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07004155 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07004156 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004157 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004158 try {
fengludb571472015-04-21 17:12:05 -07004159 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07004160 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004161 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07004162 }
4163 }
4164
4165 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09004166 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09004167 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
4168 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
4169 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09004170 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
4171 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004172 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09004173 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
4174 * triggering it as soon as this call returns.
4175 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07004176 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004177 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004178 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004179 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09004180 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09004181 final List<NetworkRequest> reqs = new ArrayList<>();
4182 // Find all requests associated to this callback and stop callback triggers immediately.
4183 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
4184 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09004185 Preconditions.checkArgument(networkCallback.networkRequest != null,
4186 "NetworkCallback was not registered");
Etan Cohen9b09a162019-04-16 15:07:55 -07004187 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
4188 Log.d(TAG, "NetworkCallback was already unregistered");
4189 return;
4190 }
Hugo Benichidafed3d2017-03-06 09:17:06 +09004191 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
4192 if (e.getValue() == networkCallback) {
4193 reqs.add(e.getKey());
4194 }
4195 }
4196 // TODO: throw exception if callback was registered more than once (http://b/20701525).
4197 for (NetworkRequest r : reqs) {
4198 try {
4199 mService.releaseNetworkRequest(r);
4200 } catch (RemoteException e) {
4201 throw e.rethrowFromSystemServer();
4202 }
4203 // Only remove mapping if rpc was successful.
4204 sCallbacks.remove(r);
4205 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09004206 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004207 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004208 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004209
4210 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004211 * Unregisters a callback previously registered via
4212 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4213 *
4214 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4215 * PendingIntent passed to
4216 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4217 * Cannot be null.
4218 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004219 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09004220 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004221 releaseNetworkRequest(operation);
4222 }
4223
4224 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004225 * Informs the system whether it should switch to {@code network} regardless of whether it is
4226 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4227 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4228 * the system default network regardless of any other network that's currently connected. If
4229 * {@code always} is true, then the choice is remembered, so that the next time the user
4230 * connects to this network, the system will switch to it.
4231 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004232 * @param network The network to accept.
4233 * @param accept Whether to accept the network even if unvalidated.
4234 * @param always Whether to remember this choice in the future.
4235 *
4236 * @hide
4237 */
lucasline252a742019-03-12 13:08:03 +08004238 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004239 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4240 try {
4241 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004242 } catch (RemoteException e) {
4243 throw e.rethrowFromSystemServer();
4244 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004245 }
4246
4247 /**
lucasline252a742019-03-12 13:08:03 +08004248 * Informs the system whether it should consider the network as validated even if it only has
4249 * partial connectivity. If {@code accept} is true, then the network will be considered as
4250 * validated even if connectivity is only partial. If {@code always} is true, then the choice
4251 * is remembered, so that the next time the user connects to this network, the system will
4252 * switch to it.
4253 *
4254 * @param network The network to accept.
4255 * @param accept Whether to consider the network as validated even if it has partial
4256 * connectivity.
4257 * @param always Whether to remember this choice in the future.
4258 *
4259 * @hide
4260 */
4261 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
4262 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4263 try {
4264 mService.setAcceptPartialConnectivity(network, accept, always);
4265 } catch (RemoteException e) {
4266 throw e.rethrowFromSystemServer();
4267 }
4268 }
4269
4270 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004271 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4272 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4273 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4274 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4275 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004276 * @param network The network to accept.
4277 *
4278 * @hide
4279 */
lucasline252a742019-03-12 13:08:03 +08004280 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004281 public void setAvoidUnvalidated(Network network) {
4282 try {
4283 mService.setAvoidUnvalidated(network);
4284 } catch (RemoteException e) {
4285 throw e.rethrowFromSystemServer();
4286 }
4287 }
4288
4289 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004290 * Requests that the system open the captive portal app on the specified network.
4291 *
4292 * @param network The network to log into.
4293 *
4294 * @hide
4295 */
paulhua6af6b62019-08-12 16:25:11 +08004296 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004297 public void startCaptivePortalApp(Network network) {
4298 try {
4299 mService.startCaptivePortalApp(network);
4300 } catch (RemoteException e) {
4301 throw e.rethrowFromSystemServer();
4302 }
4303 }
4304
4305 /**
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004306 * Requests that the system open the captive portal app with the specified extras.
4307 *
4308 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4309 * corresponding permission.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004310 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004311 * @param appExtras Extras to include in the app start intent.
4312 * @hide
4313 */
4314 @SystemApi
4315 @TestApi
4316 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
paulhud9736de2019-03-08 16:35:20 +08004317 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004318 try {
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09004319 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004320 } catch (RemoteException e) {
4321 throw e.rethrowFromSystemServer();
4322 }
4323 }
4324
4325 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004326 * Determine whether the device is configured to avoid bad wifi.
4327 * @hide
4328 */
4329 @SystemApi
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004330 @RequiresPermission(anyOf = {
4331 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4332 android.Manifest.permission.NETWORK_STACK})
4333 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004334 try {
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09004335 return mService.shouldAvoidBadWifi();
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004336 } catch (RemoteException e) {
4337 throw e.rethrowFromSystemServer();
4338 }
4339 }
4340
4341 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004342 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4343 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09004344 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4345 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004346 *
4347 * An example of such an operation might be a time-sensitive foreground activity, such as a
4348 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4349 */
4350 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4351
4352 /**
4353 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4354 * a backup channel for traffic that is primarily going over another network.
4355 *
4356 * An example might be maintaining backup connections to peers or servers for the purpose of
4357 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4358 * on backup paths should be negligible compared to the traffic on the main path.
4359 */
4360 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4361
4362 /**
4363 * It is acceptable to use metered data to improve network latency and performance.
4364 */
4365 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4366
4367 /**
4368 * Return value to use for unmetered networks. On such networks we currently set all the flags
4369 * to true.
4370 * @hide
4371 */
4372 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4373 MULTIPATH_PREFERENCE_HANDOVER |
4374 MULTIPATH_PREFERENCE_RELIABILITY |
4375 MULTIPATH_PREFERENCE_PERFORMANCE;
4376
4377 /** @hide */
4378 @Retention(RetentionPolicy.SOURCE)
4379 @IntDef(flag = true, value = {
4380 MULTIPATH_PREFERENCE_HANDOVER,
4381 MULTIPATH_PREFERENCE_RELIABILITY,
4382 MULTIPATH_PREFERENCE_PERFORMANCE,
4383 })
4384 public @interface MultipathPreference {
4385 }
4386
4387 /**
4388 * Provides a hint to the calling application on whether it is desirable to use the
4389 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4390 * for multipath data transfer on this network when it is not the system default network.
4391 * Applications desiring to use multipath network protocols should call this method before
4392 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004393 *
4394 * @param network The network on which the application desires to use multipath data.
4395 * If {@code null}, this method will return the a preference that will generally
4396 * apply to metered networks.
4397 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4398 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004399 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004400 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004401 try {
4402 return mService.getMultipathPreference(network);
4403 } catch (RemoteException e) {
4404 throw e.rethrowFromSystemServer();
4405 }
4406 }
4407
4408 /**
Stuart Scott984dc852015-03-30 13:17:11 -07004409 * Resets all connectivity manager settings back to factory defaults.
4410 * @hide
4411 */
paulhua6af6b62019-08-12 16:25:11 +08004412 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
Stuart Scott984dc852015-03-30 13:17:11 -07004413 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07004414 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07004415 mService.factoryReset();
Automerger Merge Worker6112c822020-03-06 00:38:43 +00004416 mTetheringManager.stopAllTethering();
Stuart Scott984dc852015-03-30 13:17:11 -07004417 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004418 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07004419 }
4420 }
4421
4422 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004423 * Binds the current process to {@code network}. All Sockets created in the future
4424 * (and not explicitly bound via a bound SocketFactory from
4425 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4426 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4427 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4428 * work and all host name resolutions will fail. This is by design so an application doesn't
4429 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4430 * To clear binding pass {@code null} for {@code network}. Using individually bound
4431 * Sockets created by Network.getSocketFactory().createSocket() and
4432 * performing network-specific host name resolutions via
4433 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04004434 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004435 *
4436 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4437 * the current binding.
4438 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4439 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004440 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09004441 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04004442 // instantiated.
4443 return setProcessDefaultNetwork(network);
4444 }
4445
4446 /**
4447 * Binds the current process to {@code network}. All Sockets created in the future
4448 * (and not explicitly bound via a bound SocketFactory from
4449 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4450 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4451 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4452 * work and all host name resolutions will fail. This is by design so an application doesn't
4453 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4454 * To clear binding pass {@code null} for {@code network}. Using individually bound
4455 * Sockets created by Network.getSocketFactory().createSocket() and
4456 * performing network-specific host name resolutions via
4457 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4458 * {@code setProcessDefaultNetwork}.
4459 *
4460 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4461 * the current binding.
4462 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4463 * @deprecated This function can throw {@link IllegalStateException}. Use
4464 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4465 * is a direct replacement.
4466 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004467 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004468 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04004469 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004470 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4471
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09004472 if (netId != NETID_UNSET) {
4473 netId = network.getNetIdForResolv();
Paul Jensenc91b5342014-08-27 12:38:45 -04004474 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004475
4476 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4477 return false;
4478 }
4479
4480 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05004481 // Set HTTP proxy system properties to match network.
4482 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09004483 try {
4484 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4485 } catch (SecurityException e) {
4486 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4487 Log.e(TAG, "Can't set proxy properties", e);
4488 }
Paul Jensenc91b5342014-08-27 12:38:45 -04004489 // Must flush DNS cache as new network may have different DNS resolutions.
4490 InetAddress.clearDnsCache();
4491 // Must flush socket pool as idle sockets will be bound to previous network and may
4492 // cause subsequent fetches to be performed on old network.
4493 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04004494 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004495
4496 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004497 }
4498
4499 /**
4500 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004501 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004502 *
4503 * @return {@code Network} to which this process is bound, or {@code null}.
4504 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004505 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004506 public Network getBoundNetworkForProcess() {
4507 // Forcing callers to call thru non-static function ensures ConnectivityManager
4508 // instantiated.
4509 return getProcessDefaultNetwork();
4510 }
4511
4512 /**
4513 * Returns the {@link Network} currently bound to this process via
4514 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4515 *
4516 * @return {@code Network} to which this process is bound, or {@code null}.
4517 * @deprecated Using this function can lead to other functions throwing
4518 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4519 * {@code getBoundNetworkForProcess} is a direct replacement.
4520 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004521 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004522 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004523 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004524 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004525 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004526 return new Network(netId);
4527 }
4528
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004529 private void unsupportedStartingFrom(int version) {
4530 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004531 // The getApplicationInfo() call we make below is not supported in system context. Let
4532 // the call through here, and rely on the fact that ConnectivityService will refuse to
4533 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004534 return;
4535 }
4536
4537 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4538 throw new UnsupportedOperationException(
4539 "This method is not supported in target SDK version " + version + " and above");
4540 }
4541 }
4542
4543 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4544 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004545 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004546 // remove these exemptions. Note that this check is not secure, and apps can still access these
4547 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4548 // so is unsupported and may break in the future. http://b/22728205
4549 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004550 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004551 }
4552
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004553 /**
4554 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004555 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004556 *
4557 * @param network The {@link Network} to bind host resolutions from the current process to, or
4558 * {@code null} to clear the current binding.
4559 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4560 * @hide
4561 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4562 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004563 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004564 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004565 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004566 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004567 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004568 }
Felipe Leme1b103232016-01-22 09:44:57 -08004569
4570 /**
4571 * Device is not restricting metered network activity while application is running on
4572 * background.
4573 */
4574 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4575
4576 /**
4577 * Device is restricting metered network activity while application is running on background,
4578 * but application is allowed to bypass it.
4579 * <p>
4580 * In this state, application should take action to mitigate metered network access.
4581 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4582 */
4583 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4584
4585 /**
4586 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004587 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004588 * In this state, application should not try to use the network while running on background,
4589 * because it would be denied.
4590 */
4591 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4592
Felipe Leme9778f762016-01-27 14:46:39 -08004593 /**
4594 * A change in the background metered network activity restriction has occurred.
4595 * <p>
4596 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4597 * applies to them.
4598 * <p>
4599 * This is only sent to registered receivers, not manifest receivers.
4600 */
4601 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4602 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4603 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4604
Felipe Lemeecfccea2016-01-25 11:48:04 -08004605 /** @hide */
4606 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004607 @IntDef(flag = false, value = {
4608 RESTRICT_BACKGROUND_STATUS_DISABLED,
4609 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4610 RESTRICT_BACKGROUND_STATUS_ENABLED,
4611 })
Felipe Leme1b103232016-01-22 09:44:57 -08004612 public @interface RestrictBackgroundStatus {
4613 }
4614
4615 private INetworkPolicyManager getNetworkPolicyManager() {
4616 synchronized (this) {
4617 if (mNPManager != null) {
4618 return mNPManager;
4619 }
4620 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4621 .getService(Context.NETWORK_POLICY_SERVICE));
4622 return mNPManager;
4623 }
4624 }
4625
4626 /**
4627 * Determines if the calling application is subject to metered network restrictions while
4628 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004629 *
4630 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4631 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4632 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004633 */
4634 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4635 try {
4636 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4637 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004638 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004639 }
4640 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004641
4642 /**
4643 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004644 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4645 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004646 *
4647 * @return Hash of network watchlist config file. Null if config does not exist.
4648 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004649 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004650 public byte[] getNetworkWatchlistConfigHash() {
4651 try {
4652 return mService.getNetworkWatchlistConfigHash();
4653 } catch (RemoteException e) {
4654 Log.e(TAG, "Unable to get watchlist config hash");
4655 throw e.rethrowFromSystemServer();
4656 }
4657 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004658
4659 /**
4660 * Returns the {@code uid} of the owner of a network connection.
4661 *
Benedict Wong5d50ce82020-01-20 22:14:59 -08004662 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
4663 * IPPROTO_UDP} currently supported.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004664 * @param local The local {@link InetSocketAddress} of a connection.
4665 * @param remote The remote {@link InetSocketAddress} of a connection.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004666 * @return {@code uid} if the connection is found and the app has permission to observe it
Benedict Wong5d50ce82020-01-20 22:14:59 -08004667 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
4668 * android.os.Process#INVALID_UID} if the connection is not found.
4669 * @throws {@link SecurityException} if the caller is not the active VpnService for the current
4670 * user.
4671 * @throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004672 */
Benedict Wong5d50ce82020-01-20 22:14:59 -08004673 public int getConnectionOwnerUid(
4674 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004675 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4676 try {
4677 return mService.getConnectionOwnerUid(connectionInfo);
4678 } catch (RemoteException e) {
4679 throw e.rethrowFromSystemServer();
4680 }
4681 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004682
4683 private void printStackTrace() {
4684 if (DEBUG) {
4685 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4686 final StringBuffer sb = new StringBuffer();
4687 for (int i = 3; i < callStack.length; i++) {
4688 final String stackTrace = callStack[i].toString();
4689 if (stackTrace == null || stackTrace.contains("android.os")) {
4690 break;
4691 }
4692 sb.append(" [").append(stackTrace).append("]");
4693 }
4694 Log.d(TAG, "StackLog:" + sb.toString());
4695 }
4696 }
Automerger Merge Worker42f81352020-05-12 18:48:04 +00004697
4698 /**
4699 * Simulates a Data Stall for the specified Network.
4700 *
4701 * <p>The caller must be the owner of the specified Network.
4702 *
4703 * @param detectionMethod The detection method used to identify the Data Stall.
4704 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds.
4705 * @param network The Network for which a Data Stall is being simluated.
4706 * @param extras The PersistableBundle of extras included in the Data Stall notification.
4707 * @throws SecurityException if the caller is not the owner of the given network.
4708 * @hide
4709 */
4710 @TestApi
4711 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
4712 android.Manifest.permission.NETWORK_STACK})
4713 public void simulateDataStall(int detectionMethod, long timestampMillis,
4714 @NonNull Network network, @NonNull PersistableBundle extras) {
4715 try {
4716 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
4717 } catch (RemoteException e) {
4718 e.rethrowFromSystemServer();
4719 }
4720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004721}