blob: fb0821e735e9fe18696f6e41ecebb2a4a095ab0a [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;
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010030import android.annotation.UnsupportedAppUsage;
Robert Greenwalt9258c642014-03-26 16:47:06 -070031import android.app.PendingIntent;
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;
Robert Greenwalt42acef32009-08-12 16:08:25 -070036import android.os.Binder;
Mathew Inwood55418ea2018-12-20 15:30:45 +000037import android.os.Build;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070038import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080039import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070040import android.os.Handler;
41import android.os.HandlerThread;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080042import android.os.IBinder;
43import android.os.INetworkActivityListener;
44import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070045import android.os.Looper;
46import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070047import android.os.Messenger;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090048import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080050import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080051import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090052import android.os.ServiceSpecificException;
Jeff Sharkey961e3042011-08-29 16:02:57 -070053import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080054import android.telephony.SubscriptionManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080055import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070056import android.util.Log;
Erik Kline35bf06c2017-01-26 18:08:28 +090057import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058
markchien6ea34542019-02-27 14:56:11 +080059import com.android.internal.annotations.GuardedBy;
Robert Greenwaltafa05c02014-05-21 20:04:36 -070060import com.android.internal.telephony.ITelephony;
Robert Greenwalt562cc542014-05-15 18:07:26 -070061import com.android.internal.telephony.PhoneConstants;
Hugo Benichidafed3d2017-03-06 09:17:06 +090062import com.android.internal.util.Preconditions;
63import com.android.internal.util.Protocol;
Robert Greenwaltafa05c02014-05-21 20:04:36 -070064
Paul Jensenc91b5342014-08-27 12:38:45 -040065import libcore.net.event.NetworkEventDispatcher;
66
junyulai215b8772019-01-15 11:32:44 +080067import java.io.FileDescriptor;
Felipe Leme1b103232016-01-22 09:44:57 -080068import java.lang.annotation.Retention;
69import java.lang.annotation.RetentionPolicy;
Jeremy Kleind42209d2015-12-28 15:11:58 -080070import java.net.InetAddress;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070071import java.net.InetSocketAddress;
junyulai352dc2f2019-01-08 20:04:33 +080072import java.net.Socket;
Hugo Benichidafed3d2017-03-06 09:17:06 +090073import java.util.ArrayList;
Jeremy Kleind42209d2015-12-28 15:11:58 -080074import java.util.HashMap;
Hugo Benichidafed3d2017-03-06 09:17:06 +090075import java.util.List;
76import java.util.Map;
junyulai48eac1d42018-12-27 17:25:29 +080077import java.util.concurrent.Executor;
Jeremy Kleind42209d2015-12-28 15:11:58 -080078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079/**
80 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060081 * notifies applications when network connectivity changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 * <p>
83 * The primary responsibilities of this class are to:
84 * <ol>
85 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
86 * <li>Send broadcast intents when network connectivity changes</li>
87 * <li>Attempt to "fail over" to another network when connectivity to a network
88 * is lost</li>
89 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
90 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070091 * <li>Provide an API that allows applications to request and select networks for their data
92 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * </ol>
94 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060095@SystemService(Context.CONNECTIVITY_SERVICE)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070096public class ConnectivityManager {
97 private static final String TAG = "ConnectivityManager";
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +090098 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700101 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 * been established or lost. The NetworkInfo for the affected network is
103 * sent as an extra; it should be consulted to see what kind of
104 * connectivity event occurred.
105 * <p/>
Mark Lu33ec1062016-12-05 10:57:55 -0800106 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
107 * broadcast if they declare the broadcast receiver in their manifest. Apps
108 * will still receive broadcasts if they register their
109 * {@link android.content.BroadcastReceiver} with
110 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
111 * and that context is still valid.
112 * <p/>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 * If this is a connection that was the result of failing over from a
114 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
115 * set to true.
116 * <p/>
117 * For a loss of connectivity, if the connectivity manager is attempting
118 * to connect (or has already connected) to another network, the
119 * NetworkInfo for the new network is also passed as an extra. This lets
120 * any receivers of the broadcast know that they should not necessarily
121 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800122 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 * the failover attempt succeeded (and so there is still overall data
124 * connectivity), or that the failover attempt failed, meaning that all
125 * connectivity has been lost.
126 * <p/>
127 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
128 * is set to {@code true} if there are no connected networks at all.
Chalard Jean054cd162018-02-10 05:33:50 +0900129 *
130 * @deprecated apps should use the more versatile {@link #requestNetwork},
131 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
132 * functions instead for faster and more detailed updates about the network
133 * changes they care about.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800135 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean054cd162018-02-10 05:33:50 +0900136 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 /**
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700140 * A temporary hack until SUPL system can get off the legacy APIS.
141 * They do too many network requests and the long list of apps listening
Chalard Jean4d660112018-06-04 16:52:49 +0900142 * and waking due to the CONNECTIVITY_ACTION broadcast makes it expensive.
143 * Use this broadcast intent instead for SUPL requests.
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700144 * @hide
145 */
146 public static final String CONNECTIVITY_ACTION_SUPL =
147 "android.net.conn.CONNECTIVITY_CHANGE_SUPL";
148
149 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500150 * The device has connected to a network that has presented a captive
151 * portal, which is blocking Internet connectivity. The user was presented
152 * with a notification that network sign in is required,
153 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400154 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500155 * facilitate signing in to the network. This action includes a
156 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
157 * the network presenting the captive portal; all communication with the
158 * captive portal must be done using this {@code Network} object.
159 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400160 * This activity includes a {@link CaptivePortal} extra named
161 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
162 * outcomes of the captive portal sign in to the system:
163 * <ul>
164 * <li> When the app handling this action believes the user has signed in to
165 * the network and the captive portal has been dismissed, the app should
166 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
167 * reevaluate the network. If reevaluation finds the network no longer
168 * subject to a captive portal, the network may become the default active
Chalard Jean4d660112018-06-04 16:52:49 +0900169 * data network.</li>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400170 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500171 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400172 * {@link CaptivePortal#ignoreNetwork}. </li>
173 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500174 */
175 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
176 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
177
178 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 * The lookup key for a {@link NetworkInfo} object. Retrieve with
180 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700181 *
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900182 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
183 * can't accurately represent modern network characteristics.
184 * Please obtain information about networks from the {@link NetworkCapabilities}
185 * or {@link LinkProperties} objects instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700187 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700191 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700192 *
193 * @see android.content.Intent#getIntExtra(String, int)
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900194 * @deprecated The network type is not rich enough to represent the characteristics
195 * of modern networks. Please use {@link NetworkCapabilities} instead,
196 * in particular the transports.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700197 */
Chalard Jeaneb1ea882019-01-11 16:47:53 +0900198 @Deprecated
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700199 public static final String EXTRA_NETWORK_TYPE = "networkType";
200
201 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 * The lookup key for a boolean that indicates whether a connect event
203 * is for a network to which the connectivity manager was failing over
204 * following a disconnect on another network.
205 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
junyulai3822c8a2018-12-13 12:47:51 +0800206 *
207 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 */
junyulai3822c8a2018-12-13 12:47:51 +0800209 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 public static final String EXTRA_IS_FAILOVER = "isFailover";
211 /**
212 * The lookup key for a {@link NetworkInfo} object. This is supplied when
213 * there is another network that it may be possible to connect to. Retrieve with
214 * {@link android.content.Intent#getParcelableExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800215 *
216 * @deprecated See {@link NetworkInfo}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 */
junyulai3822c8a2018-12-13 12:47:51 +0800218 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
220 /**
221 * The lookup key for a boolean that indicates whether there is a
222 * complete lack of connectivity, i.e., no network is available.
223 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
224 */
225 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
226 /**
227 * The lookup key for a string that indicates why an attempt to connect
228 * to a network failed. The string has no particular structure. It is
229 * intended to be used in notifications presented to users. Retrieve
230 * it with {@link android.content.Intent#getStringExtra(String)}.
231 */
232 public static final String EXTRA_REASON = "reason";
233 /**
234 * The lookup key for a string that provides optionally supplied
235 * extra information about the network state. The information
236 * may be passed up from the lower networking layers, and its
237 * meaning may be specific to a particular network type. Retrieve
238 * it with {@link android.content.Intent#getStringExtra(String)}.
junyulai3822c8a2018-12-13 12:47:51 +0800239 *
240 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 */
junyulai3822c8a2018-12-13 12:47:51 +0800242 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700244 /**
245 * The lookup key for an int that provides information about
246 * our connection to the internet at large. 0 indicates no connection,
247 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700248 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700249 * {@hide}
250 */
251 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400253 * The lookup key for a {@link CaptivePortal} object included with the
254 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
255 * object can be used to either indicate to the system that the captive
256 * portal has been dismissed or that the user does not want to pursue
257 * signing in to captive portal. Retrieve it with
258 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500259 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400260 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700261
262 /**
263 * Key for passing a URL to the captive portal login activity.
264 */
265 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
266
Paul Jensen25a217c2015-02-27 22:55:47 -0500267 /**
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900268 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
269 * portal login activity.
270 * {@hide}
271 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900272 @SystemApi
273 @TestApi
Remi NGUYEN VAN8255c2d2018-05-22 10:01:53 +0900274 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
275 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
276
277 /**
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900278 * Key for passing a user agent string to the captive portal login activity.
279 * {@hide}
280 */
Remi NGUYEN VAN7731c5b2019-01-17 14:38:31 +0900281 @SystemApi
282 @TestApi
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900283 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
284 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
285
286 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700287 * Broadcast action to indicate the change of data activity status
288 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800289 * The network becomes active when data transmission is started, or
290 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700291 * {@hide}
292 */
293 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean4d660112018-06-04 16:52:49 +0900294 public static final String ACTION_DATA_ACTIVITY_CHANGE =
295 "android.net.conn.DATA_ACTIVITY_CHANGE";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700296 /**
297 * The lookup key for an enum that indicates the network device type on which this data activity
298 * change happens.
299 * {@hide}
300 */
301 public static final String EXTRA_DEVICE_TYPE = "deviceType";
302 /**
303 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
304 * it is actively sending or receiving data and {@code false} means it is idle.
305 * {@hide}
306 */
307 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700308 /**
309 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
310 * {@hide}
311 */
312 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700313
314 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 * Broadcast Action: The setting for background data usage has changed
316 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
317 * <p>
318 * If an application uses the network in the background, it should listen
319 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700320 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800321 * <p>
322 *
323 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
324 * of background data depends on several combined factors, and
325 * this broadcast is no longer sent. Instead, when background
326 * data is unavailable, {@link #getActiveNetworkInfo()} will now
327 * appear disconnected. During first boot after a platform
328 * upgrade, this broadcast will be sent once if
329 * {@link #getBackgroundDataSetting()} was {@code false} before
330 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 */
332 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800333 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
335 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
336
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700337 /**
338 * Broadcast Action: The network connection may not be good
339 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
340 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
341 * the network and it's condition.
342 * @hide
343 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800344 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100345 @UnsupportedAppUsage
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700346 public static final String INET_CONDITION_ACTION =
347 "android.net.conn.INET_CONDITION_ACTION";
348
Robert Greenwalt42acef32009-08-12 16:08:25 -0700349 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800350 * Broadcast Action: A tetherable connection has come or gone.
351 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline8351faa2017-04-17 16:47:23 +0900352 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
353 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800354 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
355 * the current state of tethering. Each include a list of
356 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800357 * @hide
358 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800359 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100360 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800361 public static final String ACTION_TETHER_STATE_CHANGED =
362 "android.net.conn.TETHER_STATE_CHANGED";
363
364 /**
365 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800366 * gives a String[] listing all the interfaces configured for
367 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800368 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100369 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800370 public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800371
372 /**
373 * @hide
Erik Kline8351faa2017-04-17 16:47:23 +0900374 * gives a String[] listing all the interfaces currently in local-only
375 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800376 */
Erik Kline8351faa2017-04-17 16:47:23 +0900377 public static final String EXTRA_ACTIVE_LOCAL_ONLY = "localOnlyArray";
378
379 /**
380 * @hide
381 * gives a String[] listing all the interfaces currently tethered
382 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
383 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100384 @UnsupportedAppUsage
Erik Kline8351faa2017-04-17 16:47:23 +0900385 public static final String EXTRA_ACTIVE_TETHER = "tetherArray";
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800386
387 /**
388 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800389 * gives a String[] listing all the interfaces we tried to tether and
390 * failed. Use {@link #getLastTetherError} to find the error code
391 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800392 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100393 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800394 public static final String EXTRA_ERRORED_TETHER = "erroredArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800395
396 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800397 * Broadcast Action: The captive portal tracker has finished its test.
398 * Sent only while running Setup Wizard, in lieu of showing a user
399 * notification.
400 * @hide
401 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800402 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800403 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
404 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
405 /**
406 * The lookup key for a boolean that indicates whether a captive portal was detected.
407 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
408 * @hide
409 */
410 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
411
412 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900413 * Action used to display a dialog that asks the user whether to connect to a network that is
414 * not validated. This intent is used to start the dialog in settings via startActivity.
415 *
416 * @hide
417 */
418 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
419
420 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900421 * Action used to display a dialog that asks the user whether to avoid a network that is no
422 * longer validated. This intent is used to start the dialog in settings via startActivity.
423 *
424 * @hide
425 */
426 public static final String ACTION_PROMPT_LOST_VALIDATION =
427 "android.net.conn.PROMPT_LOST_VALIDATION";
428
429 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800430 * Invalid tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900431 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800432 * @hide
433 */
434 public static final int TETHERING_INVALID = -1;
435
436 /**
437 * Wifi tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900438 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800439 * @hide
440 */
441 @SystemApi
442 public static final int TETHERING_WIFI = 0;
443
444 /**
445 * USB tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900446 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800447 * @hide
448 */
449 @SystemApi
450 public static final int TETHERING_USB = 1;
451
452 /**
453 * Bluetooth tethering type.
Chalard Jean4d660112018-06-04 16:52:49 +0900454 * @see #startTethering(int, boolean, OnStartTetheringCallback)
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800455 * @hide
456 */
457 @SystemApi
458 public static final int TETHERING_BLUETOOTH = 2;
459
460 /**
461 * Extra used for communicating with the TetherService. Includes the type of tethering to
462 * enable if any.
463 * @hide
464 */
465 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
466
467 /**
468 * Extra used for communicating with the TetherService. Includes the type of tethering for
469 * which to cancel provisioning.
470 * @hide
471 */
472 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
473
474 /**
475 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
476 * provisioning.
477 * @hide
478 */
479 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
480
481 /**
482 * Tells the TetherService to run a provision check now.
483 * @hide
484 */
485 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
486
487 /**
488 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
489 * which will receive provisioning results. Can be left empty.
490 * @hide
491 */
492 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
493
494 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800495 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700496 * @hide
497 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100498 @UnsupportedAppUsage
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700499 public static final int TYPE_NONE = -1;
500
501 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900502 * A Mobile data connection. Devices may support more than one.
503 *
504 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
505 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
506 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700507 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900508 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700509 public static final int TYPE_MOBILE = 0;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900510
Robert Greenwalt42acef32009-08-12 16:08:25 -0700511 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900512 * A WIFI data connection. Devices may support more than one.
513 *
514 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
515 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
516 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700517 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900518 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700519 public static final int TYPE_WIFI = 1;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900520
Robert Greenwalt42acef32009-08-12 16:08:25 -0700521 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800522 * An MMS-specific Mobile data connection. This network type may use the
523 * same network interface as {@link #TYPE_MOBILE} or it may use a different
524 * one. This is used by applications needing to talk to the carrier's
525 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900526 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900527 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900528 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900529 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700530 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700531 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700532 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900533
Robert Greenwalt42acef32009-08-12 16:08:25 -0700534 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800535 * A SUPL-specific Mobile data connection. This network type may use the
536 * same network interface as {@link #TYPE_MOBILE} or it may use a different
537 * one. This is used by applications needing to talk to the carrier's
538 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900539 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900540 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900541 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900542 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700543 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700544 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700545 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900546
Robert Greenwalt42acef32009-08-12 16:08:25 -0700547 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800548 * A DUN-specific Mobile data connection. This network type may use the
549 * same network interface as {@link #TYPE_MOBILE} or it may use a different
550 * one. This is sometimes by the system when setting up an upstream connection
551 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900552 *
553 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
554 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
555 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700556 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900557 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700558 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900559
Robert Greenwalt42acef32009-08-12 16:08:25 -0700560 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800561 * A High Priority Mobile data connection. This network type uses the
562 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900563 * is different.
564 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900565 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
566 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
567 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700568 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700569 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700570 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900571
jsh8214deb2010-03-11 15:04:43 -0800572 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900573 * A WiMAX data connection.
574 *
575 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
576 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
577 * appropriate network. {@see NetworkCapabilities} for supported transports.
jsh8214deb2010-03-11 15:04:43 -0800578 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900579 @Deprecated
jsh8214deb2010-03-11 15:04:43 -0800580 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800581
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800582 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900583 * A Bluetooth data connection.
584 *
585 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
586 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
587 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800588 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900589 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800590 public static final int TYPE_BLUETOOTH = 7;
591
Robert Greenwalt60810842011-04-22 15:28:18 -0700592 /**
593 * Dummy data connection. This should not be used on shipping devices.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900594 * @deprecated This is not used any more.
Robert Greenwalt60810842011-04-22 15:28:18 -0700595 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900596 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800597 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800598
Robert Greenwalt60810842011-04-22 15:28:18 -0700599 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900600 * An Ethernet data connection.
601 *
602 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
603 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
604 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt60810842011-04-22 15:28:18 -0700605 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900606 @Deprecated
Robert Greenwalte12aec92011-01-28 14:48:37 -0800607 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700608
Wink Saville9d7d6282011-03-12 14:52:01 -0800609 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800610 * Over the air Administration.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900611 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800612 * {@hide}
613 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900614 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100615 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800616 public static final int TYPE_MOBILE_FOTA = 10;
617
618 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800619 * IP Multimedia Subsystem.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900620 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800621 * {@hide}
622 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900623 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100624 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800625 public static final int TYPE_MOBILE_IMS = 11;
626
627 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800628 * Carrier Branded Services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900629 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800630 * {@hide}
631 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900632 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100633 @UnsupportedAppUsage
Wink Saville9d7d6282011-03-12 14:52:01 -0800634 public static final int TYPE_MOBILE_CBS = 12;
635
repo syncaea743a2011-07-29 23:55:49 -0700636 /**
637 * A Wi-Fi p2p connection. Only requesting processes will have access to
638 * the peers connected.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900639 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncaea743a2011-07-29 23:55:49 -0700640 * {@hide}
641 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900642 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100643 @UnsupportedAppUsage
repo syncaea743a2011-07-29 23:55:49 -0700644 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800645
Wink Saville5e56bc52013-07-29 15:00:57 -0700646 /**
647 * The network to use for initially attaching to the network
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900648 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville5e56bc52013-07-29 15:00:57 -0700649 * {@hide}
650 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900651 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100652 @UnsupportedAppUsage
Wink Saville5e56bc52013-07-29 15:00:57 -0700653 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700654
Lorenzo Colittie285b432015-04-23 15:32:42 +0900655 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700656 * Emergency PDN connection for emergency services. This
657 * may include IMS and MMS in emergency situations.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900658 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram3e0e3bc2014-06-26 11:03:44 -0700659 * {@hide}
660 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900661 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100662 @UnsupportedAppUsage
Ram3e0e3bc2014-06-26 11:03:44 -0700663 public static final int TYPE_MOBILE_EMERGENCY = 15;
664
Hui Lu1c5624a2014-01-15 11:05:36 -0500665 /**
666 * The network that uses proxy to achieve connectivity.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900667 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu1c5624a2014-01-15 11:05:36 -0500668 * {@hide}
669 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900670 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100671 @UnsupportedAppUsage
Hui Lu1c5624a2014-01-15 11:05:36 -0500672 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700673
Robert Greenwalt8283f882014-07-07 17:09:01 -0700674 /**
675 * A virtual network using one or more native bearers.
676 * It may or may not be providing security services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900677 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700678 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900679 @Deprecated
Robert Greenwalt8283f882014-07-07 17:09:01 -0700680 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500681
Benedict Wong89ce5e32018-11-14 17:40:55 -0800682 /**
683 * A network that is exclusively meant to be used for testing
684 *
685 * @deprecated Use {@link NetworkCapabilities} instead.
686 * @hide
687 */
688 @Deprecated
689 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700690
691 /** {@hide} */
Benedict Wong89ce5e32018-11-14 17:40:55 -0800692 public static final int MAX_RADIO_TYPE = TYPE_TEST;
693
694 /** {@hide} */
695 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696
Hugo Benichi16f0a942017-06-20 14:07:59 +0900697 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
698
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800699 /**
700 * If you want to set the default network preference,you can directly
701 * change the networkAttributes array in framework's config.xml.
702 *
703 * @deprecated Since we support so many more networks now, the single
704 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800705 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800706 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800707 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800708 * from an App.
709 */
710 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
712
Jeff Sharkey625239a2012-09-26 22:03:49 -0700713 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700714 * @hide
715 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900716 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700717
Paul Jensen5d59e782014-07-11 12:28:19 -0400718 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900719 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
720 * This allows to distinguish when unregistering NetworkCallbacks those that were never
Chalard Jean4d660112018-06-04 16:52:49 +0900721 * registered from those that were already unregistered.
Hugo Benichi31c176d2017-06-17 13:14:12 +0900722 * @hide
723 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900724 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900725 new NetworkRequest.Builder().clearCapabilities().build();
726
727 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400728 * A NetID indicating no Network is selected.
729 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
730 * @hide
731 */
732 public static final int NETID_UNSET = 0;
733
Erik Kline4d092232017-10-30 15:29:44 +0900734 /**
735 * Private DNS Mode values.
736 *
737 * The "private_dns_mode" global setting stores a String value which is
738 * expected to be one of the following.
739 */
740
741 /**
742 * @hide
743 */
744 public static final String PRIVATE_DNS_MODE_OFF = "off";
745 /**
746 * @hide
747 */
748 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
749 /**
750 * @hide
751 */
752 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
753 /**
754 * The default Private DNS mode.
755 *
756 * This may change from release to release or may become dependent upon
757 * the capabilities of the underlying platform.
758 *
759 * @hide
760 */
Erik Kline19841792018-05-16 16:41:57 +0900761 public static final String PRIVATE_DNS_DEFAULT_MODE_FALLBACK = PRIVATE_DNS_MODE_OPPORTUNISTIC;
Erik Kline4d092232017-10-30 15:29:44 +0900762
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100763 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700764 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500765 /**
766 * A kludge to facilitate static access where a Context pointer isn't available, like in the
767 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
768 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
769 * methods that take a Context argument.
770 */
771 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900773 private final Context mContext;
774
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800775 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800776 private INetworkPolicyManager mNPManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800777
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800778 /**
779 * Tests if a given integer represents a valid network type.
780 * @param networkType the type to be tested
781 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400782 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
783 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800784 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700785 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700786 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900787 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 }
789
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800790 /**
791 * Returns a non-localized string representing a given network type.
792 * ONLY used for debugging output.
793 * @param type the type needing naming
794 * @return a String for the given type, or a string version of the type ("87")
795 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900796 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800797 * {@hide}
798 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900799 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100800 @UnsupportedAppUsage
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700801 public static String getNetworkTypeName(int type) {
802 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900803 case TYPE_NONE:
804 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700805 case TYPE_MOBILE:
806 return "MOBILE";
807 case TYPE_WIFI:
808 return "WIFI";
809 case TYPE_MOBILE_MMS:
810 return "MOBILE_MMS";
811 case TYPE_MOBILE_SUPL:
812 return "MOBILE_SUPL";
813 case TYPE_MOBILE_DUN:
814 return "MOBILE_DUN";
815 case TYPE_MOBILE_HIPRI:
816 return "MOBILE_HIPRI";
817 case TYPE_WIMAX:
818 return "WIMAX";
819 case TYPE_BLUETOOTH:
820 return "BLUETOOTH";
821 case TYPE_DUMMY:
822 return "DUMMY";
823 case TYPE_ETHERNET:
824 return "ETHERNET";
825 case TYPE_MOBILE_FOTA:
826 return "MOBILE_FOTA";
827 case TYPE_MOBILE_IMS:
828 return "MOBILE_IMS";
829 case TYPE_MOBILE_CBS:
830 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700831 case TYPE_WIFI_P2P:
832 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700833 case TYPE_MOBILE_IA:
834 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700835 case TYPE_MOBILE_EMERGENCY:
836 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500837 case TYPE_PROXY:
838 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900839 case TYPE_VPN:
840 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700841 default:
842 return Integer.toString(type);
843 }
844 }
845
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800846 /**
847 * Checks if a given type uses the cellular data connection.
848 * This should be replaced in the future by a network property.
849 * @param networkType the type to check
850 * @return a boolean - {@code true} if uses cellular network, else {@code false}
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 boolean isNetworkTypeMobile(int networkType) {
857 switch (networkType) {
858 case TYPE_MOBILE:
859 case TYPE_MOBILE_MMS:
860 case TYPE_MOBILE_SUPL:
861 case TYPE_MOBILE_DUN:
862 case TYPE_MOBILE_HIPRI:
863 case TYPE_MOBILE_FOTA:
864 case TYPE_MOBILE_IMS:
865 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700866 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700867 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700868 return true;
869 default:
870 return false;
871 }
872 }
873
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800874 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700875 * Checks if the given network type is backed by a Wi-Fi radio.
876 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900877 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700878 * @hide
879 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900880 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700881 public static boolean isNetworkTypeWifi(int networkType) {
882 switch (networkType) {
883 case TYPE_WIFI:
884 case TYPE_WIFI_P2P:
885 return true;
886 default:
887 return false;
888 }
889 }
890
891 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800892 * Specifies the preferred network type. When the device has more
893 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800894 *
895 * @param preference the network type to prefer over all others. It is
896 * unspecified what happens to the old preferred network in the
897 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700898 * @deprecated Functionality has been removed as it no longer makes sense,
899 * with many more than two networks - we'd need an array to express
900 * preference. Instead we use dynamic network properties of
901 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800902 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700903 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 }
906
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800907 /**
908 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800909 *
910 * @return an integer representing the preferred network type
911 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700912 * @deprecated Functionality has been removed as it no longer makes sense,
913 * with many more than two networks - we'd need an array to express
914 * preference. Instead we use dynamic network properties of
915 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800916 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700917 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600918 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700920 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 }
922
Scott Main671644c2011-10-06 19:02:28 -0700923 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800924 * Returns details about the currently active default data network. When
925 * connected, this network is the default route for outgoing connections.
926 * You should always check {@link NetworkInfo#isConnected()} before initiating
927 * network traffic. This may return {@code null} when there is no default
928 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900929 * Note that if the default network is a VPN, this method will return the
930 * NetworkInfo for one of its underlying networks instead, or null if the
931 * VPN agent did not specify any. Apps interested in learning about VPNs
932 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800933 *
934 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500935 * or {@code null} if no default network is currently active
junyulai3822c8a2018-12-13 12:47:51 +0800936 * @deprecated See {@link NetworkInfo}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700937 */
junyulai3822c8a2018-12-13 12:47:51 +0800938 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600939 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900940 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 public NetworkInfo getActiveNetworkInfo() {
942 try {
943 return mService.getActiveNetworkInfo();
944 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700945 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 }
947 }
948
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800949 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500950 * Returns a {@link Network} object corresponding to the currently active
951 * default data network. In the event that the current active default data
952 * network disconnects, the returned {@code Network} object will no longer
953 * be usable. This will return {@code null} when there is no default
954 * network.
955 *
956 * @return a {@link Network} object for the current default network or
957 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500958 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600959 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900960 @Nullable
Paul Jensen31a94f42015-02-13 14:18:39 -0500961 public Network getActiveNetwork() {
962 try {
963 return mService.getActiveNetwork();
964 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700965 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500966 }
967 }
968
969 /**
Robin Leed2baf792016-03-24 12:07:00 +0000970 * Returns a {@link Network} object corresponding to the currently active
971 * default data network for a specific UID. In the event that the default data
972 * network disconnects, the returned {@code Network} object will no longer
973 * be usable. This will return {@code null} when there is no default
974 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +0000975 *
976 * @return a {@link Network} object for the current default network for the
977 * given UID or {@code null} if no default network is currently active
978 *
979 * @hide
980 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600981 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Chalard Jean50bea3d2019-01-07 19:26:34 +0900982 @Nullable
Robin Leed2baf792016-03-24 12:07:00 +0000983 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600984 return getActiveNetworkForUid(uid, false);
985 }
986
987 /** {@hide} */
988 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +0000989 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600990 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +0000991 } catch (RemoteException e) {
992 throw e.rethrowFromSystemServer();
993 }
994 }
995
996 /**
Charles He36738632017-05-15 17:07:18 +0100997 * Checks if a VPN app supports always-on mode.
998 *
999 * In order to support the always-on feature, an app has to
1000 * <ul>
1001 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +01001002 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
1003 * meta-data field.
Charles He36738632017-05-15 17:07:18 +01001004 * </ul>
1005 *
1006 * @param userId The identifier of the user for whom the VPN app is installed.
1007 * @param vpnPackage The canonical package name of the VPN app.
1008 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
1009 * @hide
1010 */
1011 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
1012 try {
1013 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
1014 } catch (RemoteException e) {
1015 throw e.rethrowFromSystemServer();
1016 }
1017 }
1018
1019 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001020 * Configures an always-on VPN connection through a specific application.
1021 * This connection is automatically granted and persisted after a reboot.
1022 *
1023 * <p>The designated package should declare a {@link VpnService} in its
1024 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
1025 * otherwise the call will fail.
1026 *
1027 * @param userId The identifier of the user to set an always-on VPN for.
1028 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
1029 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +01001030 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
1031 * {@code false} otherwise.
Pavel Grafova462bcb2019-01-25 08:50:06 +00001032 * @param lockdownWhitelist The list of packages that are allowed to access network directly
1033 * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
1034 * this method must be called when a package that should be whitelisted is installed or
1035 * uninstalled.
Robin Lee244ce8e2016-01-05 18:03:46 +00001036 * @return {@code true} if the package is set as always-on VPN controller;
1037 * {@code false} otherwise.
1038 * @hide
1039 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001040 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Leedc679712016-05-03 13:23:03 +01001041 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001042 boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001043 try {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001044 return mService.setAlwaysOnVpnPackage(
1045 userId, vpnPackage, lockdownEnabled, lockdownWhitelist);
Robin Lee244ce8e2016-01-05 18:03:46 +00001046 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001047 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001048 }
1049 }
1050
Pavel Grafova462bcb2019-01-25 08:50:06 +00001051 /**
Robin Lee244ce8e2016-01-05 18:03:46 +00001052 * Returns the package name of the currently set always-on VPN application.
1053 * If there is no always-on VPN set, or the VPN is provided by the system instead
1054 * of by an app, {@code null} will be returned.
1055 *
1056 * @return Package name of VPN controller responsible for always-on VPN,
1057 * or {@code null} if none is set.
1058 * @hide
1059 */
Pavel Grafova462bcb2019-01-25 08:50:06 +00001060 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
Robin Lee244ce8e2016-01-05 18:03:46 +00001061 public String getAlwaysOnVpnPackageForUser(int userId) {
1062 try {
1063 return mService.getAlwaysOnVpnPackage(userId);
1064 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001065 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +00001066 }
1067 }
1068
1069 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001070 * @return whether always-on VPN is in lockdown mode.
1071 *
1072 * @hide
1073 **/
1074 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1075 public boolean isVpnLockdownEnabled(int userId) {
1076 try {
1077 return mService.isVpnLockdownEnabled(userId);
1078 } catch (RemoteException e) {
1079 throw e.rethrowFromSystemServer();
1080 }
1081
1082 }
1083
1084 /**
1085 * @return the list of packages that are allowed to access network when always-on VPN is in
1086 * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
1087 *
1088 * @hide
1089 **/
1090 @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
1091 public List<String> getVpnLockdownWhitelist(int userId) {
1092 try {
1093 return mService.getVpnLockdownWhitelist(userId);
1094 } catch (RemoteException e) {
1095 throw e.rethrowFromSystemServer();
1096 }
1097 }
1098
1099 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001100 * Returns details about the currently active default data network
1101 * for a given uid. This is for internal use only to avoid spying
1102 * other apps.
1103 *
1104 * @return a {@link NetworkInfo} object for the current default network
1105 * for the given uid or {@code null} if no default network is
1106 * available for the specified uid.
1107 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001108 * {@hide}
1109 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001110 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001111 @UnsupportedAppUsage
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001112 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001113 return getActiveNetworkInfoForUid(uid, false);
1114 }
1115
1116 /** {@hide} */
1117 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001118 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001119 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001120 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001121 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001122 }
1123 }
1124
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001125 /**
1126 * Returns connection status information about a particular
1127 * network type.
1128 *
1129 * @param networkType integer specifying which networkType in
1130 * which you're interested.
1131 * @return a {@link NetworkInfo} object for the requested
1132 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001133 * supported by the device. If {@code networkType} is
1134 * TYPE_VPN and a VPN is active for the calling app,
1135 * then this method will try to return one of the
1136 * underlying networks for the VPN or null if the
1137 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001138 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001139 * @deprecated This method does not support multiple connected networks
1140 * of the same type. Use {@link #getAllNetworks} and
1141 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001142 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001143 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001144 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001145 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 public NetworkInfo getNetworkInfo(int networkType) {
1147 try {
1148 return mService.getNetworkInfo(networkType);
1149 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001150 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 }
1152 }
1153
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001154 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001155 * Returns connection status information about a particular
1156 * Network.
1157 *
1158 * @param network {@link Network} specifying which network
1159 * in which you're interested.
1160 * @return a {@link NetworkInfo} object for the requested
1161 * network or {@code null} if the {@code Network}
1162 * is not valid.
junyulai3822c8a2018-12-13 12:47:51 +08001163 * @deprecated See {@link NetworkInfo}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001164 */
junyulai3822c8a2018-12-13 12:47:51 +08001165 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001166 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001167 @Nullable
1168 public NetworkInfo getNetworkInfo(@Nullable Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001169 return getNetworkInfoForUid(network, Process.myUid(), false);
1170 }
1171
1172 /** {@hide} */
1173 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001174 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001175 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001176 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001177 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001178 }
1179 }
1180
1181 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001182 * Returns connection status information about all network
1183 * types supported by the device.
1184 *
1185 * @return an array of {@link NetworkInfo} objects. Check each
1186 * {@link NetworkInfo#getType} for which type each applies.
1187 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001188 * @deprecated This method does not support multiple connected networks
1189 * of the same type. Use {@link #getAllNetworks} and
1190 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001191 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001192 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001193 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001194 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 public NetworkInfo[] getAllNetworkInfo() {
1196 try {
1197 return mService.getAllNetworkInfo();
1198 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001199 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
1201 }
1202
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001203 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001204 * Returns the {@link Network} object currently serving a given type, or
1205 * null if the given type is not connected.
1206 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001207 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001208 * @deprecated This method does not support multiple connected networks
1209 * of the same type. Use {@link #getAllNetworks} and
1210 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001211 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001212 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001213 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001214 @UnsupportedAppUsage
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001215 public Network getNetworkForType(int networkType) {
1216 try {
1217 return mService.getNetworkForType(networkType);
1218 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001219 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001220 }
1221 }
1222
1223 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001224 * Returns an array of all {@link Network} currently tracked by the
1225 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001226 *
1227 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001229 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001230 @NonNull
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001231 public Network[] getAllNetworks() {
1232 try {
1233 return mService.getAllNetworks();
1234 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001235 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001236 }
1237 }
1238
1239 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001240 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001241 * the Networks that applications run by the given user will use by default.
1242 * @hide
1243 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001244 @UnsupportedAppUsage
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001245 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1246 try {
1247 return mService.getDefaultNetworkCapabilitiesForUser(userId);
1248 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001249 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001250 }
1251 }
1252
1253 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001254 * Returns the IP information for the current default network.
1255 *
1256 * @return a {@link LinkProperties} object describing the IP info
1257 * for the current default network, or {@code null} if there
1258 * is no current default network.
1259 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001260 * {@hide}
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001261 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1262 * value of {@link #getActiveNetwork()} instead. In particular,
1263 * this method will return non-null LinkProperties even if the
1264 * app is blocked by policy from using this network.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001265 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001266 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jeaneb1ea882019-01-11 16:47:53 +09001267 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001268 public LinkProperties getActiveLinkProperties() {
1269 try {
1270 return mService.getActiveLinkProperties();
1271 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001272 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001273 }
1274 }
1275
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001276 /**
1277 * Returns the IP information for a given network type.
1278 *
1279 * @param networkType the network type of interest.
1280 * @return a {@link LinkProperties} object describing the IP info
1281 * for the given networkType, or {@code null} if there is
1282 * no current default network.
1283 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001284 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001285 * @deprecated This method does not support multiple connected networks
1286 * of the same type. Use {@link #getAllNetworks},
1287 * {@link #getNetworkInfo(android.net.Network)}, and
1288 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001289 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001290 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001291 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001292 @UnsupportedAppUsage
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001293 public LinkProperties getLinkProperties(int networkType) {
1294 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001295 return mService.getLinkPropertiesForType(networkType);
1296 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001297 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001298 }
1299 }
1300
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001301 /**
1302 * Get the {@link LinkProperties} for the given {@link Network}. This
1303 * will return {@code null} if the network is unknown.
1304 *
1305 * @param network The {@link Network} object identifying the network in question.
1306 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001307 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001308 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001309 @Nullable
1310 public LinkProperties getLinkProperties(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001311 try {
1312 return mService.getLinkProperties(network);
1313 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001314 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001315 }
1316 }
1317
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001318 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001319 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001320 * will return {@code null} if the network is unknown.
1321 *
1322 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001323 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001324 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001325 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09001326 @Nullable
1327 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001328 try {
1329 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001330 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001331 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001332 }
1333 }
1334
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001335 /**
Udam Sainib7c24872016-01-04 12:16:14 -08001336 * Gets the URL that should be used for resolving whether a captive portal is present.
1337 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1338 * portal is present.
1339 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1340 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1341 *
1342 * @hide
1343 */
1344 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07001345 @RequiresPermission(android.Manifest.permission.LOCAL_MAC_ADDRESS)
Udam Sainib7c24872016-01-04 12:16:14 -08001346 public String getCaptivePortalServerUrl() {
1347 try {
1348 return mService.getCaptivePortalServerUrl();
1349 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001350 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001351 }
1352 }
1353
1354 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 * Tells the underlying networking system that the caller wants to
1356 * begin using the named feature. The interpretation of {@code feature}
1357 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001358 *
1359 * <p>This method requires the caller to hold either the
1360 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1361 * or the ability to modify system settings as determined by
1362 * {@link android.provider.Settings.System#canWrite}.</p>
1363 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 * @param networkType specifies which network the request pertains to
1365 * @param feature the name of the feature to be used
1366 * @return an integer value representing the outcome of the request.
1367 * The interpretation of this value is specific to each networking
1368 * implementation+feature combination, except that the value {@code -1}
1369 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001370 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001371 * @deprecated Deprecated in favor of the cleaner
1372 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001373 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001374 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001375 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001377 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001379 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001380 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1381 if (netCap == null) {
1382 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1383 feature);
1384 return PhoneConstants.APN_REQUEST_FAILED;
1385 }
1386
1387 NetworkRequest request = null;
1388 synchronized (sLegacyRequests) {
1389 LegacyRequest l = sLegacyRequests.get(netCap);
1390 if (l != null) {
1391 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1392 renewRequestLocked(l);
1393 if (l.currentNetwork != null) {
1394 return PhoneConstants.APN_ALREADY_ACTIVE;
1395 } else {
1396 return PhoneConstants.APN_REQUEST_STARTED;
1397 }
1398 }
1399
1400 request = requestNetworkForFeatureLocked(netCap);
1401 }
1402 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001403 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001404 return PhoneConstants.APN_REQUEST_STARTED;
1405 } else {
1406 Log.d(TAG, " request Failed");
1407 return PhoneConstants.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
1409 }
1410
1411 /**
1412 * Tells the underlying networking system that the caller is finished
1413 * using the named feature. The interpretation of {@code feature}
1414 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001415 *
1416 * <p>This method requires the caller to hold either the
1417 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1418 * or the ability to modify system settings as determined by
1419 * {@link android.provider.Settings.System#canWrite}.</p>
1420 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 * @param networkType specifies which network the request pertains to
1422 * @param feature the name of the feature that is no longer needed
1423 * @return an integer value representing the outcome of the request.
1424 * The interpretation of this value is specific to each networking
1425 * implementation+feature combination, except that the value {@code -1}
1426 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001427 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001428 * @deprecated Deprecated in favor of the cleaner
1429 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001430 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001431 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001432 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001434 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001436 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001437 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1438 if (netCap == null) {
1439 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1440 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 return -1;
1442 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001443
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001444 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001445 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001446 }
1447 return 1;
1448 }
1449
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001450 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001451 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1452 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001453 switch (feature) {
1454 case "enableCBS":
1455 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1456 case "enableDUN":
1457 case "enableDUNAlways":
1458 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1459 case "enableFOTA":
1460 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1461 case "enableHIPRI":
1462 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1463 case "enableIMS":
1464 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1465 case "enableMMS":
1466 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1467 case "enableSUPL":
1468 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1469 default:
1470 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001471 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001472 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1473 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001474 }
1475 return null;
1476 }
1477
Robert Greenwalt06314e42014-10-29 14:04:06 -07001478 /**
1479 * Guess what the network request was trying to say so that the resulting
1480 * network is accessible via the legacy (deprecated) API such as
1481 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001482 *
1483 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001484 * capability but ignore things such as networkSpecifier.
1485 * If the request has more than one transport or capability it doesn't
1486 * match the old legacy requests (they selected only single transport/capability)
1487 * so this function cannot map the request to a single legacy type and
1488 * the resulting network will not be available to the legacy APIs.
1489 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001490 * This code is only called from the requestNetwork API (L and above).
1491 *
1492 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1493 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1494 * do this for SUPL requests, which are the only ones that we know need it. If
1495 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1496 * compatibility we can send them:
1497 *
1498 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1499 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1500 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001501 * TODO - This should be removed when the legacy APIs are removed.
1502 */
Ye Wenb87875e2014-07-21 14:19:01 -07001503 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1504 if (netCap == null) {
1505 return TYPE_NONE;
1506 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001507
Ye Wenb87875e2014-07-21 14:19:01 -07001508 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1509 return TYPE_NONE;
1510 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001511
Lifu Tang30f95a72016-01-07 23:20:38 -08001512 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001513 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1514 // NOTE: if this causes app breakage, we should not just comment out this early return;
1515 // instead, we should make this early return conditional on the requesting app's target
1516 // SDK version, as described in the comment above.
1517 return TYPE_NONE;
1518 }
1519
Robert Greenwalt06314e42014-10-29 14:04:06 -07001520 String type = null;
1521 int result = TYPE_NONE;
1522
Ye Wenb87875e2014-07-21 14:19:01 -07001523 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001524 type = "enableCBS";
1525 result = TYPE_MOBILE_CBS;
1526 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1527 type = "enableIMS";
1528 result = TYPE_MOBILE_IMS;
1529 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1530 type = "enableFOTA";
1531 result = TYPE_MOBILE_FOTA;
1532 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1533 type = "enableDUN";
1534 result = TYPE_MOBILE_DUN;
1535 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001536 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001537 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001538 // back out this hack for mms as they no longer need this and it's causing
1539 // device slowdowns - b/23350688 (note, supl still needs this)
1540 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1541 // type = "enableMMS";
1542 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001543 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1544 type = "enableHIPRI";
1545 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001546 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001547 if (type != null) {
1548 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1549 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1550 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001551 }
1552 }
1553 return TYPE_NONE;
1554 }
1555
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001556 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001557 if (netCap == null) return TYPE_NONE;
1558 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1559 return TYPE_MOBILE_CBS;
1560 }
1561 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1562 return TYPE_MOBILE_IMS;
1563 }
1564 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1565 return TYPE_MOBILE_FOTA;
1566 }
1567 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1568 return TYPE_MOBILE_DUN;
1569 }
1570 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1571 return TYPE_MOBILE_SUPL;
1572 }
1573 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1574 return TYPE_MOBILE_MMS;
1575 }
1576 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1577 return TYPE_MOBILE_HIPRI;
1578 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001579 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1580 return TYPE_WIFI_P2P;
1581 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001582 return TYPE_NONE;
1583 }
1584
1585 private static class LegacyRequest {
1586 NetworkCapabilities networkCapabilities;
1587 NetworkRequest networkRequest;
1588 int expireSequenceNumber;
1589 Network currentNetwork;
1590 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001591
1592 private void clearDnsBinding() {
1593 if (currentNetwork != null) {
1594 currentNetwork = null;
1595 setProcessDefaultNetworkForHostResolution(null);
1596 }
1597 }
1598
Robert Greenwalt6078b502014-06-11 16:05:07 -07001599 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001600 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001601 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001602 currentNetwork = network;
1603 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001604 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001605 }
1606 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001607 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001608 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001609 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1610 }
1611 };
1612 }
1613
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001614 @UnsupportedAppUsage
Chalard Jean4d660112018-06-04 16:52:49 +09001615 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
1616 new HashMap<>();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001617
1618 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1619 synchronized (sLegacyRequests) {
1620 LegacyRequest l = sLegacyRequests.get(netCap);
1621 if (l != null) return l.networkRequest;
1622 }
1623 return null;
1624 }
1625
1626 private void renewRequestLocked(LegacyRequest l) {
1627 l.expireSequenceNumber++;
1628 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1629 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1630 }
1631
1632 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1633 int ourSeqNum = -1;
1634 synchronized (sLegacyRequests) {
1635 LegacyRequest l = sLegacyRequests.get(netCap);
1636 if (l == null) return;
1637 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001638 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001639 }
1640 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1641 }
1642
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001643 @UnsupportedAppUsage
Robert Greenwalt562cc542014-05-15 18:07:26 -07001644 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1645 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001646 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001647 try {
1648 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001649 } catch (RemoteException e) {
1650 throw e.rethrowFromSystemServer();
1651 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001652 LegacyRequest l = new LegacyRequest();
1653 l.networkCapabilities = netCap;
1654 l.delay = delay;
1655 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001656 l.networkRequest = sendRequestForNetwork(
1657 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001658 if (l.networkRequest == null) return null;
1659 sLegacyRequests.put(netCap, l);
1660 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1661 return l.networkRequest;
1662 }
1663
1664 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1665 if (delay >= 0) {
1666 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001667 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001668 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1669 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001670 }
1671 }
1672
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001673 @UnsupportedAppUsage
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001674 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1675 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001676 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001677 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001678 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001679 if (l == null) return false;
1680 unregisterNetworkCallback(l.networkCallback);
1681 l.clearDnsBinding();
1682 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 }
1684
Erik Kline35bf06c2017-01-26 18:08:28 +09001685 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1686 static {
1687 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1688 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1689 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1690 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1691 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1692 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1693 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1694 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1695 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1696 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1697 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1698 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1699 }
1700
1701 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1702 static {
1703 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1704 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1705 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1706 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1707 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1708 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1709 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1710 }
1711
1712 /**
1713 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1714 * instance suitable for registering a request or callback. Throws an
1715 * IllegalArgumentException if no mapping from the legacy type to
1716 * NetworkCapabilities is known.
1717 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001718 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1719 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001720 * @hide
1721 */
1722 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1723 final NetworkCapabilities nc = new NetworkCapabilities();
1724
1725 // Map from type to transports.
1726 final int NOT_FOUND = -1;
1727 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001728 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001729 nc.addTransportType(transport);
1730
1731 // Map from type to capabilities.
1732 nc.addCapability(sLegacyTypeToCapability.get(
1733 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1734 nc.maybeMarkCapabilitiesRestricted();
1735 return nc;
1736 }
1737
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001738 /** @hide */
1739 public static class PacketKeepaliveCallback {
1740 /** The requested keepalive was successfully started. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001741 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001742 public void onStarted() {}
1743 /** The keepalive was successfully stopped. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001744 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001745 public void onStopped() {}
1746 /** An error occurred. */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001747 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001748 public void onError(int error) {}
1749 }
1750
1751 /**
1752 * Allows applications to request that the system periodically send specific packets on their
1753 * behalf, using hardware offload to save battery power.
1754 *
1755 * To request that the system send keepalives, call one of the methods that return a
1756 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1757 * passing in a non-null callback. If the callback is successfully started, the callback's
1758 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1759 * specifying one of the {@code ERROR_*} constants in this class.
1760 *
Chalard Jean4d660112018-06-04 16:52:49 +09001761 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
1762 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
1763 * {@link PacketKeepaliveCallback#onError} if an error occurred.
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001764 *
junyulai48eac1d42018-12-27 17:25:29 +08001765 * @deprecated Use {@link SocketKeepalive} instead.
1766 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001767 * @hide
1768 */
1769 public class PacketKeepalive {
1770
1771 private static final String TAG = "PacketKeepalive";
1772
1773 /** @hide */
1774 public static final int SUCCESS = 0;
1775
1776 /** @hide */
1777 public static final int NO_KEEPALIVE = -1;
1778
1779 /** @hide */
1780 public static final int BINDER_DIED = -10;
1781
1782 /** The specified {@code Network} is not connected. */
1783 public static final int ERROR_INVALID_NETWORK = -20;
1784 /** The specified IP addresses are invalid. For example, the specified source IP address is
1785 * not configured on the specified {@code Network}. */
1786 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1787 /** The requested port is invalid. */
1788 public static final int ERROR_INVALID_PORT = -22;
1789 /** The packet length is invalid (e.g., too long). */
1790 public static final int ERROR_INVALID_LENGTH = -23;
1791 /** The packet transmission interval is invalid (e.g., too short). */
1792 public static final int ERROR_INVALID_INTERVAL = -24;
1793
1794 /** The hardware does not support this request. */
1795 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001796 /** The hardware returned an error. */
1797 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001798
Nathan Harold63dd8132018-02-14 13:09:45 -08001799 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001800 public static final int NATT_PORT = 4500;
1801
Nathan Harold63dd8132018-02-14 13:09:45 -08001802 /** The minimum interval in seconds between keepalive packet transmissions */
1803 public static final int MIN_INTERVAL = 10;
1804
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001805 private final Network mNetwork;
1806 private final PacketKeepaliveCallback mCallback;
1807 private final Looper mLooper;
1808 private final Messenger mMessenger;
1809
1810 private volatile Integer mSlot;
1811
1812 void stopLooper() {
1813 mLooper.quit();
1814 }
1815
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001816 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001817 public void stop() {
1818 try {
1819 mService.stopKeepalive(mNetwork, mSlot);
1820 } catch (RemoteException e) {
1821 Log.e(TAG, "Error stopping packet keepalive: ", e);
1822 stopLooper();
1823 }
1824 }
1825
1826 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001827 Preconditions.checkNotNull(network, "network cannot be null");
1828 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001829 mNetwork = network;
1830 mCallback = callback;
1831 HandlerThread thread = new HandlerThread(TAG);
1832 thread.start();
1833 mLooper = thread.getLooper();
1834 mMessenger = new Messenger(new Handler(mLooper) {
1835 @Override
1836 public void handleMessage(Message message) {
1837 switch (message.what) {
junyulaie4135282019-01-03 18:50:15 +08001838 case NetworkAgent.EVENT_SOCKET_KEEPALIVE:
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001839 int error = message.arg2;
1840 try {
1841 if (error == SUCCESS) {
1842 if (mSlot == null) {
1843 mSlot = message.arg1;
1844 mCallback.onStarted();
1845 } else {
1846 mSlot = null;
1847 stopLooper();
1848 mCallback.onStopped();
1849 }
1850 } else {
1851 stopLooper();
1852 mCallback.onError(error);
1853 }
1854 } catch (Exception e) {
1855 Log.e(TAG, "Exception in keepalive callback(" + error + ")", e);
1856 }
1857 break;
1858 default:
1859 Log.e(TAG, "Unhandled message " + Integer.toHexString(message.what));
1860 break;
1861 }
1862 }
1863 });
1864 }
1865 }
1866
1867 /**
1868 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1869 *
junyulai48eac1d42018-12-27 17:25:29 +08001870 * @deprecated Use {@link #createSocketKeepalive} instead.
1871 *
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001872 * @hide
1873 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001874 @UnsupportedAppUsage
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001875 public PacketKeepalive startNattKeepalive(
1876 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1877 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1878 final PacketKeepalive k = new PacketKeepalive(network, callback);
1879 try {
1880 mService.startNattKeepalive(network, intervalSeconds, k.mMessenger, new Binder(),
1881 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1882 } catch (RemoteException e) {
1883 Log.e(TAG, "Error starting packet keepalive: ", e);
1884 k.stopLooper();
1885 return null;
1886 }
1887 return k;
1888 }
1889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 /**
junyulai48eac1d42018-12-27 17:25:29 +08001891 * Request that keepalives be started on a IPsec NAT-T socket.
1892 *
1893 * @param network The {@link Network} the socket is on.
1894 * @param socket The socket that needs to be kept alive.
1895 * @param source The source address of the {@link UdpEncapsulationSocket}.
1896 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
1897 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1898 * must run callback sequentially, otherwise the order of callbacks cannot be
1899 * guaranteed.
1900 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1901 * changes. Must be extended by applications that use this API.
1902 *
junyulai352dc2f2019-01-08 20:04:33 +08001903 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1904 * given socket.
junyulai48eac1d42018-12-27 17:25:29 +08001905 **/
1906 public SocketKeepalive createSocketKeepalive(@NonNull Network network,
1907 @NonNull UdpEncapsulationSocket socket,
1908 @NonNull InetAddress source,
1909 @NonNull InetAddress destination,
1910 @NonNull @CallbackExecutor Executor executor,
1911 @NonNull Callback callback) {
junyulai215b8772019-01-15 11:32:44 +08001912 return new NattSocketKeepalive(mService, network, socket.getFileDescriptor(),
1913 socket.getResourceId(), source, destination, executor, callback);
1914 }
1915
1916 /**
1917 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
1918 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
1919 *
1920 * @param network The {@link Network} the socket is on.
1921 * @param fd The {@link FileDescriptor} that needs to be kept alive. The provided
1922 * {@link FileDescriptor} must be bound to a port and the keepalives will be sent from
1923 * that port.
1924 * @param source The source address of the {@link UdpEncapsulationSocket}.
1925 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
1926 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
1927 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
1928 * must run callback sequentially, otherwise the order of callbacks cannot be
1929 * guaranteed.
1930 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1931 * changes. Must be extended by applications that use this API.
1932 *
junyulai352dc2f2019-01-08 20:04:33 +08001933 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1934 * given socket.
junyulai215b8772019-01-15 11:32:44 +08001935 * @hide
1936 */
1937 @SystemApi
1938 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
1939 public SocketKeepalive createNattKeepalive(@NonNull Network network,
1940 @NonNull FileDescriptor fd,
1941 @NonNull InetAddress source,
1942 @NonNull InetAddress destination,
1943 @NonNull @CallbackExecutor Executor executor,
1944 @NonNull Callback callback) {
1945 return new NattSocketKeepalive(mService, network, fd, INVALID_RESOURCE_ID /* Unused */,
1946 source, destination, executor, callback);
junyulai48eac1d42018-12-27 17:25:29 +08001947 }
1948
1949 /**
junyulai352dc2f2019-01-08 20:04:33 +08001950 * Request that keepalives be started on a TCP socket.
1951 * The socket must be established.
1952 *
1953 * @param network The {@link Network} the socket is on.
1954 * @param socket The socket that needs to be kept alive.
1955 * @param executor The executor on which callback will be invoked. This implementation assumes
1956 * the provided {@link Executor} runs the callbacks in sequence with no
1957 * concurrency. Failing this, no guarantee of correctness can be made. It is
1958 * the responsibility of the caller to ensure the executor provides this
1959 * guarantee. A simple way of creating such an executor is with the standard
1960 * tool {@code Executors.newSingleThreadExecutor}.
1961 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
1962 * changes. Must be extended by applications that use this API.
1963 *
1964 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
1965 * given socket.
1966 * @hide
1967 */
1968 @SystemApi
1969 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
1970 public SocketKeepalive createSocketKeepalive(@NonNull Network network,
1971 @NonNull Socket socket,
1972 @NonNull Executor executor,
1973 @NonNull Callback callback) {
1974 return new TcpSocketKeepalive(mService, network, socket, executor, callback);
1975 }
1976
1977 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 * Ensure that a network route exists to deliver traffic to the specified
1979 * host via the specified network interface. An attempt to add a route that
1980 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001981 *
1982 * <p>This method requires the caller to hold either the
1983 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1984 * or the ability to modify system settings as determined by
1985 * {@link android.provider.Settings.System#canWrite}.</p>
1986 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 * @param networkType the type of the network over which traffic to the specified
1988 * host is to be routed
1989 * @param hostAddress the IP address of the host to which the route is desired
1990 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001991 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001992 * @deprecated Deprecated in favor of the
1993 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
1994 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001995 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001996 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001997 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001999 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002001 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002002 }
2003
2004 /**
2005 * Ensure that a network route exists to deliver traffic to the specified
2006 * host via the specified network interface. An attempt to add a route that
2007 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002008 *
2009 * <p>This method requires the caller to hold either the
2010 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2011 * or the ability to modify system settings as determined by
2012 * {@link android.provider.Settings.System#canWrite}.</p>
2013 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002014 * @param networkType the type of the network over which traffic to the specified
2015 * host is to be routed
2016 * @param hostAddress the IP address of the host to which the route is desired
2017 * @return {@code true} on success, {@code false} on failure
2018 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002019 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09002020 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002021 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002022 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002023 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07002024 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002025 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002027 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002029 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
2031 }
2032
2033 /**
2034 * Returns the value of the setting for background data usage. If false,
2035 * applications should not use the network if the application is not in the
2036 * foreground. Developers should respect this setting, and check the value
2037 * of this before performing any background data operations.
2038 * <p>
2039 * All applications that have background services that use the network
2040 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002041 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07002042 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002043 * background data depends on several combined factors, and this method will
2044 * always return {@code true}. Instead, when background data is unavailable,
2045 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07002046 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 * @return Whether background data usage is allowed.
2048 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002049 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002051 // assume that background data is allowed; final authority is
2052 // NetworkInfo which may be blocked.
2053 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 }
2055
2056 /**
2057 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002058 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 * @param allowBackgroundData Whether an application should use data while
2060 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002061 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2063 * @see #getBackgroundDataSetting()
2064 * @hide
2065 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002066 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002067 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002069 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002071
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002072 /** {@hide} */
2073 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002074 @UnsupportedAppUsage
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002075 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
2076 try {
2077 return mService.getActiveNetworkQuotaInfo();
2078 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002079 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002080 }
2081 }
2082
2083 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002084 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002085 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002086 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002087 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002088 @UnsupportedAppUsage
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002089 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002090 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
2091 if (b != null) {
2092 try {
2093 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08002094 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08002095 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
Malcolm Chenb455e722017-11-28 15:57:14 -08002096 boolean retVal = it.isUserDataEnabled(subId);
Wink Saville36ffb042014-12-05 11:10:30 -08002097 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2098 + " retVal=" + retVal);
2099 return retVal;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002100 } catch (RemoteException e) {
2101 throw e.rethrowFromSystemServer();
2102 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002103 }
Wink Saville36ffb042014-12-05 11:10:30 -08002104 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07002105 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08002106 }
2107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07002109 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002110 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002111 */
2112 public interface OnNetworkActiveListener {
2113 /**
2114 * Called on the main thread of the process to report that the current data network
2115 * has become active, and it is now a good time to perform any pending network
2116 * operations. Note that this listener only tells you when the network becomes
2117 * active; if at any other time you want to know whether it is active (and thus okay
2118 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07002119 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002120 */
Chalard Jean4d660112018-06-04 16:52:49 +09002121 void onNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002122 }
2123
2124 private INetworkManagementService getNetworkManagementService() {
2125 synchronized (this) {
2126 if (mNMService != null) {
2127 return mNMService;
2128 }
2129 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
2130 mNMService = INetworkManagementService.Stub.asInterface(b);
2131 return mNMService;
2132 }
2133 }
2134
2135 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
Chalard Jean4d660112018-06-04 16:52:49 +09002136 mNetworkActivityListeners = new ArrayMap<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002137
2138 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002139 * Start listening to reports when the system's default data network is active, meaning it is
2140 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2141 * to determine the current state of the system's default network after registering the
2142 * listener.
2143 * <p>
2144 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04002145 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07002146 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002147 *
2148 * @param l The listener to be told when the network is active.
2149 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07002150 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002151 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
2152 @Override
2153 public void onNetworkActive() throws RemoteException {
2154 l.onNetworkActive();
2155 }
2156 };
2157
2158 try {
2159 getNetworkManagementService().registerNetworkActivityListener(rl);
2160 mNetworkActivityListeners.put(l, rl);
2161 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002162 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002163 }
2164 }
2165
2166 /**
2167 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07002168 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002169 *
2170 * @param l Previously registered listener.
2171 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002172 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002173 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09002174 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002175 try {
2176 getNetworkManagementService().unregisterNetworkActivityListener(rl);
2177 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002178 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002179 }
2180 }
2181
2182 /**
2183 * Return whether the data network is currently active. An active network means that
2184 * it is currently in a high power state for performing data transmission. On some
2185 * types of networks, it may be expensive to move and stay in such a state, so it is
2186 * more power efficient to batch network traffic together when the radio is already in
2187 * this state. This method tells you whether right now is currently a good time to
2188 * initiate network traffic, as the network is already active.
2189 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002190 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002191 try {
2192 return getNetworkManagementService().isNetworkActive();
2193 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002194 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002195 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002196 }
2197
2198 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 * {@hide}
2200 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09002201 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002202 mContext = Preconditions.checkNotNull(context, "missing context");
2203 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05002204 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002206
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002207 /** {@hide} */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002208 @UnsupportedAppUsage
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002209 public static ConnectivityManager from(Context context) {
2210 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2211 }
2212
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002213 /** @hide */
2214 public NetworkRequest getDefaultRequest() {
2215 try {
2216 // This is not racy as the default request is final in ConnectivityService.
2217 return mService.getDefaultRequest();
2218 } catch (RemoteException e) {
2219 throw e.rethrowFromSystemServer();
2220 }
2221 }
2222
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09002223 /* TODO: These permissions checks don't belong in client-side code. Move them to
2224 * services.jar, possibly in com.android.server.net. */
2225
2226 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09002227 public static final void enforceChangePermission(Context context) {
2228 int uid = Binder.getCallingUid();
2229 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
2230 .getPackageNameForUid(context, uid), true /* throwException */);
2231 }
2232
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002233 /** {@hide} */
2234 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002235 Preconditions.checkNotNull(context, "Context cannot be null");
2236 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002237
Robert Greenwaltedb47662014-09-16 17:54:19 -07002238 if (context.getResources().getStringArray(
2239 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2240 // Have a provisioning app - must only let system apps (which check this app)
2241 // turn on tethering
2242 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002243 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002244 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002245 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002246 // If callingPkg's uid is not same as Binder.getCallingUid(),
2247 // AppOpsService throws SecurityException.
2248 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2249 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002250 }
2251 }
2252
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002253 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002254 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2255 * situations where a Context pointer is unavailable.
2256 * @hide
2257 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002258 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002259 static ConnectivityManager getInstanceOrNull() {
2260 return sInstance;
2261 }
2262
2263 /**
2264 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2265 * situations where a Context pointer is unavailable.
2266 * @hide
2267 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002268 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002269 @UnsupportedAppUsage
Paul Jensen72db88e2015-03-10 10:54:12 -04002270 private static ConnectivityManager getInstance() {
2271 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002272 throw new IllegalStateException("No ConnectivityManager yet constructed");
2273 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002274 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002275 }
2276
2277 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002278 * Get the set of tetherable, available interfaces. This list is limited by
2279 * device configuration and current interface existence.
2280 *
2281 * @return an array of 0 or more Strings of tetherable interface names.
2282 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002283 * {@hide}
2284 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002285 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002286 @UnsupportedAppUsage
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002287 public String[] getTetherableIfaces() {
2288 try {
2289 return mService.getTetherableIfaces();
2290 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002291 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002292 }
2293 }
2294
2295 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002296 * Get the set of tethered interfaces.
2297 *
2298 * @return an array of 0 or more String of currently tethered interface names.
2299 *
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
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002304 public String[] getTetheredIfaces() {
2305 try {
2306 return mService.getTetheredIfaces();
2307 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002308 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002309 }
2310 }
2311
2312 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002313 * Get the set of interface names which attempted to tether but
2314 * failed. Re-attempting to tether may cause them to reset to the Tethered
2315 * state. Alternatively, causing the interface to be destroyed and recreated
2316 * may cause them to reset to the available state.
2317 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2318 * information on the cause of the errors.
2319 *
2320 * @return an array of 0 or more String indicating the interface names
2321 * which failed to tether.
2322 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002323 * {@hide}
2324 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002325 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002326 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002327 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002328 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08002329 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002330 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002331 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002332 }
2333 }
2334
2335 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002336 * Get the set of tethered dhcp ranges.
2337 *
2338 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
2339 * {@hide}
2340 */
2341 public String[] getTetheredDhcpRanges() {
2342 try {
2343 return mService.getTetheredDhcpRanges();
2344 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002345 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002346 }
2347 }
2348
2349 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002350 * Attempt to tether the named interface. This will setup a dhcp server
2351 * on the interface, forward and NAT IP packets and forward DNS requests
2352 * to the best active upstream network interface. Note that if no upstream
2353 * IP network interface is available, dhcp will still run and traffic will be
2354 * allowed between the tethered devices and this device, though upstream net
2355 * access will of course fail until an upstream network interface becomes
2356 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002357 *
2358 * <p>This method requires the caller to hold either the
2359 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2360 * or the ability to modify system settings as determined by
2361 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002362 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002363 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2364 * and WifiStateMachine which need direct access. All other clients should use
2365 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2366 * logic.</p>
2367 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002368 * @param iface the interface name to tether.
2369 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2370 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002371 * {@hide}
2372 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002373 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002374 public int tether(String iface) {
2375 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002376 String pkgName = mContext.getOpPackageName();
2377 Log.i(TAG, "tether caller:" + pkgName);
2378 return mService.tether(iface, pkgName);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002379 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002380 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002381 }
2382 }
2383
2384 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002385 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002386 *
2387 * <p>This method requires the caller to hold either the
2388 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2389 * or the ability to modify system settings as determined by
2390 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002391 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002392 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2393 * and WifiStateMachine which need direct access. All other clients should use
2394 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2395 * logic.</p>
2396 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002397 * @param iface the interface name to untether.
2398 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2399 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002400 * {@hide}
2401 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002402 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002403 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002404 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002405 String pkgName = mContext.getOpPackageName();
2406 Log.i(TAG, "untether caller:" + pkgName);
2407 return mService.untether(iface, pkgName);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002408 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002409 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002410 }
2411 }
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 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002429 * {@hide}
2430 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002431 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002432 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2433 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002434 public boolean isTetheringSupported() {
Chalard Jean8f76fc32017-09-26 15:45:18 +09002435 String pkgName = mContext.getOpPackageName();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002436 try {
Udam Saini0e94c362017-06-07 12:06:28 -07002437 return mService.isTetheringSupported(pkgName);
Chalard Jean8f76fc32017-09-26 15:45:18 +09002438 } catch (SecurityException e) {
2439 // This API is not available to this caller, but for backward-compatibility
2440 // this will just return false instead of throwing.
2441 return false;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002442 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002443 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002444 }
2445 }
2446
2447 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002448 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2449 * @hide
2450 */
2451 @SystemApi
2452 public static abstract class OnStartTetheringCallback {
2453 /**
2454 * Called when tethering has been successfully started.
2455 */
Chalard Jean4d660112018-06-04 16:52:49 +09002456 public void onTetheringStarted() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002457
2458 /**
2459 * Called when starting tethering failed.
2460 */
Chalard Jean4d660112018-06-04 16:52:49 +09002461 public void onTetheringFailed() {}
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002462 }
2463
2464 /**
2465 * Convenient overload for
2466 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2467 * handler to run on the current thread's {@link Looper}.
2468 * @hide
2469 */
2470 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07002471 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002472 public void startTethering(int type, boolean showProvisioningUi,
2473 final OnStartTetheringCallback callback) {
2474 startTethering(type, showProvisioningUi, callback, null);
2475 }
2476
2477 /**
2478 * Runs tether provisioning for the given type if needed and then starts tethering if
2479 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2480 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2481 * schedules tether provisioning re-checks if appropriate.
2482 *
2483 * @param type The type of tethering to start. Must be one of
2484 * {@link ConnectivityManager.TETHERING_WIFI},
2485 * {@link ConnectivityManager.TETHERING_USB}, or
2486 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2487 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2488 * is one. This should be true the first time this function is called and also any time
2489 * the user can see this UI. It gives users information from their carrier about the
2490 * check failing and how they can sign up for tethering if possible.
2491 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2492 * of the result of trying to tether.
2493 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2494 * @hide
2495 */
2496 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002497 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002498 public void startTethering(int type, boolean showProvisioningUi,
2499 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002500 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002501
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002502 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2503 @Override
2504 protected void onReceiveResult(int resultCode, Bundle resultData) {
2505 if (resultCode == TETHER_ERROR_NO_ERROR) {
2506 callback.onTetheringStarted();
2507 } else {
2508 callback.onTetheringFailed();
2509 }
2510 }
2511 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002512
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002513 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002514 String pkgName = mContext.getOpPackageName();
2515 Log.i(TAG, "startTethering caller:" + pkgName);
2516 mService.startTethering(type, wrappedCallback, showProvisioningUi, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002517 } catch (RemoteException e) {
2518 Log.e(TAG, "Exception trying to start tethering.", e);
2519 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2520 }
2521 }
2522
2523 /**
2524 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2525 * applicable.
2526 *
2527 * @param type The type of tethering to stop. Must be one of
2528 * {@link ConnectivityManager.TETHERING_WIFI},
2529 * {@link ConnectivityManager.TETHERING_USB}, or
2530 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2531 * @hide
2532 */
2533 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002534 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002535 public void stopTethering(int type) {
2536 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002537 String pkgName = mContext.getOpPackageName();
2538 Log.i(TAG, "stopTethering caller:" + pkgName);
2539 mService.stopTethering(type, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002540 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002541 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002542 }
2543 }
2544
2545 /**
markchien6ea34542019-02-27 14:56:11 +08002546 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
2547 * upstream status.
2548 *
2549 *@hide
2550 */
2551 @SystemApi
2552 public abstract static class OnTetheringEventCallback {
2553
2554 /**
2555 * Called when tethering upstream changed. This can be called multiple times and can be
2556 * called any time.
2557 *
2558 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
2559 * have any upstream.
2560 */
2561 public void onUpstreamChanged(@Nullable Network network) {}
2562 }
2563
2564 @GuardedBy("mTetheringEventCallbacks")
2565 private final ArrayMap<OnTetheringEventCallback, ITetheringEventCallback>
2566 mTetheringEventCallbacks = new ArrayMap<>();
2567
2568 /**
2569 * Start listening to tethering change events. Any new added callback will receive the last
2570 * tethering status right away. If callback is registered when tethering loses its upstream or
2571 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
2572 * with a null argument. The same callback object cannot be registered twice.
2573 *
2574 * @param executor the executor on which callback will be invoked.
2575 * @param callback the callback to be called when tethering has change events.
2576 * @hide
2577 */
2578 @SystemApi
2579 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2580 public void registerTetheringEventCallback(
2581 @NonNull @CallbackExecutor Executor executor,
2582 @NonNull final OnTetheringEventCallback callback) {
2583 Preconditions.checkNotNull(callback, "OnTetheringEventCallback cannot be null.");
2584
2585 synchronized (mTetheringEventCallbacks) {
2586 Preconditions.checkArgument(!mTetheringEventCallbacks.containsKey(callback),
2587 "callback was already registered.");
2588 ITetheringEventCallback remoteCallback = new ITetheringEventCallback.Stub() {
2589 @Override
2590 public void onUpstreamChanged(Network network) throws RemoteException {
2591 Binder.withCleanCallingIdentity(() ->
2592 executor.execute(() -> {
2593 callback.onUpstreamChanged(network);
2594 }));
2595 }
2596 };
2597 try {
2598 String pkgName = mContext.getOpPackageName();
2599 Log.i(TAG, "registerTetheringUpstreamCallback:" + pkgName);
2600 mService.registerTetheringEventCallback(remoteCallback, pkgName);
2601 mTetheringEventCallbacks.put(callback, remoteCallback);
2602 } catch (RemoteException e) {
2603 throw e.rethrowFromSystemServer();
2604 }
2605 }
2606 }
2607
2608 /**
2609 * Remove tethering event callback previously registered with
2610 * {@link #registerTetheringEventCallback}.
2611 *
2612 * @param callback previously registered callback.
2613 * @hide
2614 */
2615 @SystemApi
2616 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
2617 public void unregisterTetheringEventCallback(
2618 @NonNull final OnTetheringEventCallback callback) {
2619 synchronized (mTetheringEventCallbacks) {
2620 ITetheringEventCallback remoteCallback = mTetheringEventCallbacks.remove(callback);
2621 Preconditions.checkNotNull(remoteCallback, "callback was not registered.");
2622 try {
2623 String pkgName = mContext.getOpPackageName();
2624 Log.i(TAG, "unregisterTetheringEventCallback:" + pkgName);
2625 mService.unregisterTetheringEventCallback(remoteCallback, pkgName);
2626 } catch (RemoteException e) {
2627 throw e.rethrowFromSystemServer();
2628 }
2629 }
2630 }
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 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002641 * {@hide}
2642 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002643 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002644 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002645 public String[] getTetherableUsbRegexs() {
2646 try {
2647 return mService.getTetherableUsbRegexs();
2648 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002649 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002650 }
2651 }
2652
2653 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002654 * Get the list of regular expressions that define any tetherable
2655 * Wifi network interfaces. If Wifi tethering is not supported by the
2656 * device, this list should be empty.
2657 *
2658 * @return an array of 0 or more regular expression Strings defining
2659 * what interfaces are considered tetherable wifi interfaces.
2660 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002661 * {@hide}
2662 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002663 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002664 @UnsupportedAppUsage
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002665 public String[] getTetherableWifiRegexs() {
2666 try {
2667 return mService.getTetherableWifiRegexs();
2668 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002669 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002670 }
2671 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002672
Danica Chang6fdd0c62010-08-11 14:54:43 -07002673 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002674 * Get the list of regular expressions that define any tetherable
2675 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2676 * device, this list should be empty.
2677 *
2678 * @return an array of 0 or more regular expression Strings defining
2679 * what interfaces are considered tetherable bluetooth interfaces.
2680 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002681 * {@hide}
2682 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002683 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002684 @UnsupportedAppUsage
Danica Chang6fdd0c62010-08-11 14:54:43 -07002685 public String[] getTetherableBluetoothRegexs() {
2686 try {
2687 return mService.getTetherableBluetoothRegexs();
2688 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002689 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002690 }
2691 }
2692
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002693 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002694 * Attempt to both alter the mode of USB and Tethering of USB. A
2695 * utility method to deal with some of the complexity of USB - will
2696 * attempt to switch to Rndis and subsequently tether the resulting
2697 * interface on {@code true} or turn off tethering and switch off
2698 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002699 *
2700 * <p>This method requires the caller to hold either the
2701 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2702 * or the ability to modify system settings as determined by
2703 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002704 *
2705 * @param enable a boolean - {@code true} to enable tethering
2706 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2707 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002708 * {@hide}
2709 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002710 @UnsupportedAppUsage
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002711 public int setUsbTethering(boolean enable) {
2712 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002713 String pkgName = mContext.getOpPackageName();
2714 Log.i(TAG, "setUsbTethering caller:" + pkgName);
2715 return mService.setUsbTethering(enable, pkgName);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002716 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002717 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002718 }
2719 }
2720
Robert Greenwalt5a735062010-03-02 17:25:02 -08002721 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002722 @SystemApi
Robert Greenwalt5a735062010-03-02 17:25:02 -08002723 public static final int TETHER_ERROR_NO_ERROR = 0;
2724 /** {@hide} */
2725 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2726 /** {@hide} */
2727 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2728 /** {@hide} */
2729 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2730 /** {@hide} */
2731 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2732 /** {@hide} */
2733 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2734 /** {@hide} */
2735 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2736 /** {@hide} */
2737 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2738 /** {@hide} */
2739 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2740 /** {@hide} */
2741 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2742 /** {@hide} */
2743 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002744 /** {@hide} */
markchienf2731272019-01-16 17:44:13 +08002745 @SystemApi
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002746 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +09002747 /** {@hide} */
2748 public static final int TETHER_ERROR_DHCPSERVER_ERROR = 12;
markchienf2731272019-01-16 17:44:13 +08002749 /** {@hide} */
2750 @SystemApi
2751 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002752
2753 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002754 * Get a more detailed error code after a Tethering or Untethering
2755 * request asynchronously failed.
2756 *
2757 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002758 * @return error The error code of the last error tethering or untethering the named
2759 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002760 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002761 * {@hide}
2762 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002763 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01002764 @UnsupportedAppUsage
Robert Greenwalt5a735062010-03-02 17:25:02 -08002765 public int getLastTetherError(String iface) {
2766 try {
2767 return mService.getLastTetherError(iface);
2768 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002769 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002770 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002771 }
2772
markchien9554abf2019-03-06 16:25:00 +08002773 /** @hide */
2774 @Retention(RetentionPolicy.SOURCE)
2775 @IntDef(value = {
2776 TETHER_ERROR_NO_ERROR,
2777 TETHER_ERROR_PROVISION_FAILED,
2778 TETHER_ERROR_ENTITLEMENT_UNKONWN,
2779 })
2780 public @interface EntitlementResultCode {
2781 }
2782
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002783 /**
markchien9554abf2019-03-06 16:25:00 +08002784 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
markchienf2731272019-01-16 17:44:13 +08002785 * entitlement succeeded.
2786 * @hide
2787 */
2788 @SystemApi
markchien9554abf2019-03-06 16:25:00 +08002789 public interface OnTetheringEntitlementResultListener {
2790 /**
2791 * Called to notify entitlement result.
2792 *
2793 * @param resultCode an int value of entitlement result. It may be one of
2794 * {@link #TETHER_ERROR_NO_ERROR},
2795 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2796 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2797 */
2798 void onEntitlementResult(@EntitlementResultCode int resultCode);
2799 }
2800
2801 /**
2802 * @removed
2803 * @deprecated This API would be removed when all of caller has been updated.
2804 * */
2805 @Deprecated
markchienf2731272019-01-16 17:44:13 +08002806 public abstract static class TetheringEntitlementValueListener {
2807 /**
2808 * Called to notify entitlement result.
2809 *
2810 * @param resultCode a int value of entitlement result. It may be one of
2811 * {@link #TETHER_ERROR_NO_ERROR},
2812 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
2813 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
2814 */
2815 public void onEntitlementResult(int resultCode) {}
2816 }
2817
2818 /**
2819 * Get the last value of the entitlement check on this downstream. If the cached value is
2820 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, it just return the
2821 * cached value. Otherwise, a UI-based entitlement check would be performed. It is not
2822 * guaranteed that the UI-based entitlement check will complete in any specific time period
2823 * and may in fact never complete. Any successful entitlement check the platform performs for
2824 * any reason will update the cached value.
2825 *
2826 * @param type the downstream type of tethering. Must be one of
2827 * {@link #TETHERING_WIFI},
2828 * {@link #TETHERING_USB}, or
2829 * {@link #TETHERING_BLUETOOTH}.
2830 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
markchien9554abf2019-03-06 16:25:00 +08002831 * @param executor the executor on which callback will be invoked.
2832 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
2833 * notify the caller of the result of entitlement check. The listener may be called zero
2834 * or one time.
markchienf2731272019-01-16 17:44:13 +08002835 * {@hide}
2836 */
2837 @SystemApi
2838 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
markchien9554abf2019-03-06 16:25:00 +08002839 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
2840 @NonNull @CallbackExecutor Executor executor,
2841 @NonNull final OnTetheringEntitlementResultListener listener) {
2842 Preconditions.checkNotNull(listener, "TetheringEntitlementResultListener cannot be null.");
2843 ResultReceiver wrappedListener = new ResultReceiver(null) {
2844 @Override
2845 protected void onReceiveResult(int resultCode, Bundle resultData) {
2846 Binder.withCleanCallingIdentity(() ->
2847 executor.execute(() -> {
2848 listener.onEntitlementResult(resultCode);
2849 }));
2850 }
2851 };
2852
2853 try {
2854 String pkgName = mContext.getOpPackageName();
2855 Log.i(TAG, "getLatestTetheringEntitlementResult:" + pkgName);
2856 mService.getLatestTetheringEntitlementResult(type, wrappedListener,
2857 showEntitlementUi, pkgName);
2858 } catch (RemoteException e) {
2859 throw e.rethrowFromSystemServer();
2860 }
2861 }
2862
2863 /**
2864 * @removed
2865 * @deprecated This API would be removed when all of caller has been updated.
2866 * */
2867 @Deprecated
markchienf2731272019-01-16 17:44:13 +08002868 public void getLatestTetheringEntitlementValue(int type, boolean showEntitlementUi,
2869 @NonNull final TetheringEntitlementValueListener listener, @Nullable Handler handler) {
2870 Preconditions.checkNotNull(listener, "TetheringEntitlementValueListener cannot be null.");
2871 ResultReceiver wrappedListener = new ResultReceiver(handler) {
2872 @Override
2873 protected void onReceiveResult(int resultCode, Bundle resultData) {
2874 listener.onEntitlementResult(resultCode);
2875 }
2876 };
2877
2878 try {
2879 String pkgName = mContext.getOpPackageName();
2880 Log.i(TAG, "getLatestTetheringEntitlementValue:" + pkgName);
markchien9554abf2019-03-06 16:25:00 +08002881 mService.getLatestTetheringEntitlementResult(type, wrappedListener,
markchienf2731272019-01-16 17:44:13 +08002882 showEntitlementUi, pkgName);
2883 } catch (RemoteException e) {
2884 throw e.rethrowFromSystemServer();
2885 }
2886 }
2887
2888 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002889 * Report network connectivity status. This is currently used only
2890 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002891 * <p>This method requires the caller to hold the permission
2892 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002893 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002894 * @param networkType The type of network you want to report on
2895 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002896 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002897 * {@hide}
2898 */
2899 public void reportInetCondition(int networkType, int percentage) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002900 printStackTrace();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002901 try {
2902 mService.reportInetCondition(networkType, percentage);
2903 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002904 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002905 }
2906 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002907
2908 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002909 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002910 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002911 * the framework to re-evaluate network connectivity and/or switch to another
2912 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002913 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002914 * @param network The {@link Network} the application was attempting to use
2915 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002916 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2917 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002918 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002919 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09002920 public void reportBadNetwork(@Nullable Network network) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002921 printStackTrace();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002922 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002923 // One of these will be ignored because it matches system's current state.
2924 // The other will trigger the necessary reevaluation.
2925 mService.reportNetworkConnectivity(network, true);
2926 mService.reportNetworkConnectivity(network, false);
2927 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002928 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002929 }
2930 }
2931
2932 /**
2933 * Report to the framework whether a network has working connectivity.
2934 * This provides a hint to the system that a particular network is providing
2935 * working connectivity or not. In response the framework may re-evaluate
2936 * the network's connectivity and might take further action thereafter.
2937 *
2938 * @param network The {@link Network} the application was attempting to use
2939 * or {@code null} to indicate the current default network.
2940 * @param hasConnectivity {@code true} if the application was able to successfully access the
2941 * Internet using {@code network} or {@code false} if not.
2942 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09002943 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09002944 printStackTrace();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002945 try {
2946 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002947 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002948 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002949 }
2950 }
2951
2952 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002953 * Set a network-independent global http proxy. This is not normally what you want
2954 * for typical HTTP proxies - they are general network dependent. However if you're
2955 * doing something unusual like general internal filtering this may be useful. On
2956 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002957 *
2958 * @param p A {@link ProxyInfo} object defining the new global
2959 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002960 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002961 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002962 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Jason Monk207900c2014-04-25 15:00:09 -04002963 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002964 try {
2965 mService.setGlobalProxy(p);
2966 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002967 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002968 }
2969 }
2970
2971 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002972 * Retrieve any network-independent global HTTP proxy.
2973 *
Jason Monk207900c2014-04-25 15:00:09 -04002974 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002975 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002976 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002977 */
Jason Monk207900c2014-04-25 15:00:09 -04002978 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002979 try {
2980 return mService.getGlobalProxy();
2981 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002982 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002983 }
2984 }
2985
2986 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002987 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2988 * network-specific HTTP proxy. If {@code network} is null, the
2989 * network-specific proxy returned is the proxy of the default active
2990 * network.
2991 *
2992 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2993 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2994 * or when {@code network} is {@code null},
2995 * the {@code ProxyInfo} for the default active network. Returns
2996 * {@code null} when no proxy applies or the caller doesn't have
2997 * permission to use {@code network}.
2998 * @hide
2999 */
3000 public ProxyInfo getProxyForNetwork(Network network) {
3001 try {
3002 return mService.getProxyForNetwork(network);
3003 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003004 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04003005 }
3006 }
3007
3008 /**
Paul Jensene0bef712014-12-10 15:12:18 -05003009 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3010 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04003011 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05003012 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003013 *
Jason Monk207900c2014-04-25 15:00:09 -04003014 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003015 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07003016 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003017 @Nullable
Paul Jensene0bef712014-12-10 15:12:18 -05003018 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04003019 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07003020 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003021
3022 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003023 * Returns true if the hardware supports the given network type
3024 * else it returns false. This doesn't indicate we have coverage
3025 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003026 * hardware supports it. For example a GSM phone without a SIM
3027 * should still return {@code true} for mobile data, but a wifi only
3028 * tablet would return {@code false}.
3029 *
3030 * @param networkType The network type we'd like to check
3031 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003032 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003033 * @hide
3034 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09003035 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003036 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003037 @UnsupportedAppUsage
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003038 public boolean isNetworkSupported(int networkType) {
3039 try {
3040 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003041 } catch (RemoteException e) {
3042 throw e.rethrowFromSystemServer();
3043 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07003044 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003045
3046 /**
3047 * Returns if the currently active data network is metered. A network is
3048 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003049 * that connection due to monetary costs, data limitations or
3050 * battery/performance issues. You should check this before doing large
3051 * data transfers, and warn the user or delay the operation until another
3052 * network is available.
3053 *
3054 * @return {@code true} if large transfers should be avoided, otherwise
3055 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003056 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003057 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003058 public boolean isActiveNetworkMetered() {
3059 try {
3060 return mService.isActiveNetworkMetered();
3061 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003062 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003063 }
3064 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003065
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003066 /**
3067 * If the LockdownVpn mechanism is enabled, updates the vpn
3068 * with a reload of its profile.
3069 *
3070 * @return a boolean with {@code} indicating success
3071 *
3072 * <p>This method can only be called by the system UID
3073 * {@hide}
3074 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003075 public boolean updateLockdownVpn() {
3076 try {
3077 return mService.updateLockdownVpn();
3078 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003079 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003080 }
3081 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07003082
3083 /**
Wink Saville948282b2013-08-29 08:55:16 -07003084 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07003085 *
Wink Savilleab9321d2013-06-29 21:10:57 -07003086 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07003087 *
3088 * @return time out that will be used, maybe less that suggestedTimeOutMs
3089 * -1 if an error.
3090 *
3091 * {@hide}
3092 */
Wink Saville948282b2013-08-29 08:55:16 -07003093 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003094 int timeOutMs = -1;
3095 try {
Wink Saville948282b2013-08-29 08:55:16 -07003096 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07003097 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003098 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07003099 }
3100 return timeOutMs;
3101 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003102
3103 /**
Wink Saville42d4f082013-07-20 20:31:59 -07003104 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003105 * {@hide}
3106 */
3107 public String getMobileProvisioningUrl() {
3108 try {
3109 return mService.getMobileProvisioningUrl();
3110 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003111 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003112 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003113 }
Wink Saville42d4f082013-07-20 20:31:59 -07003114
3115 /**
Wink Saville948282b2013-08-29 08:55:16 -07003116 * Set sign in error notification to visible or in visible
3117 *
Wink Saville948282b2013-08-29 08:55:16 -07003118 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04003119 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07003120 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003121 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07003122 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003123 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003124 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04003125 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07003126 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003127 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07003128 }
3129 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003130
3131 /**
3132 * Set the value for enabling/disabling airplane mode
3133 *
3134 * @param enable whether to enable airplane mode or not
3135 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003136 * @hide
3137 */
Lorenzo Colittif5845d12018-10-09 18:55:11 +09003138 @RequiresPermission(anyOf = {
3139 android.Manifest.permission.NETWORK_SETTINGS,
3140 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3141 android.Manifest.permission.NETWORK_STACK})
Lorenzo Colitti85eca482018-10-09 18:50:32 +09003142 @SystemApi
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003143 public void setAirplaneMode(boolean enable) {
3144 try {
3145 mService.setAirplaneMode(enable);
3146 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003147 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003148 }
3149 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003150
Chalard Jean08577fc2018-05-02 21:14:54 +09003151 /** {@hide} - returns the factory serial number */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01003152 @UnsupportedAppUsage
Chalard Jean08577fc2018-05-02 21:14:54 +09003153 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003154 try {
Chalard Jean08577fc2018-05-02 21:14:54 +09003155 return mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003156 } catch (RemoteException e) {
3157 throw e.rethrowFromSystemServer();
3158 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003159 }
3160
3161 /** {@hide} */
Mathew Inwood55418ea2018-12-20 15:30:45 +00003162 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Robert Greenwalta67be032014-05-16 15:49:14 -07003163 public void unregisterNetworkFactory(Messenger messenger) {
3164 try {
3165 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003166 } catch (RemoteException e) {
3167 throw e.rethrowFromSystemServer();
3168 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003169 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003170
Chalard Jean08577fc2018-05-02 21:14:54 +09003171 // TODO : remove this method. It is a stopgap measure to help sheperding a number
3172 // of dependent changes that would conflict throughout the automerger graph. Having this
3173 // temporarily helps with the process of going through with all these dependent changes across
3174 // the entire tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05003175 /**
3176 * @hide
3177 * Register a NetworkAgent with ConnectivityService.
3178 * @return NetID corresponding to NetworkAgent.
3179 */
3180 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003181 NetworkCapabilities nc, int score, NetworkMisc misc) {
Chalard Jean08577fc2018-05-02 21:14:54 +09003182 return registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3183 NetworkFactory.SerialNumber.NONE);
3184 }
3185
3186 /**
3187 * @hide
3188 * Register a NetworkAgent with ConnectivityService.
3189 * @return NetID corresponding to NetworkAgent.
3190 */
3191 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
3192 NetworkCapabilities nc, int score, NetworkMisc misc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003193 try {
Chalard Jean08577fc2018-05-02 21:14:54 +09003194 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc,
3195 factorySerialNumber);
Paul Jensen31a94f42015-02-13 14:18:39 -05003196 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003197 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05003198 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003199 }
3200
Robert Greenwalt9258c642014-03-26 16:47:06 -07003201 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003202 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3203 * changes. Should be extended by applications wanting notifications.
3204 *
3205 * A {@code NetworkCallback} is registered by calling
3206 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3207 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09003208 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09003209 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3210 * A {@code NetworkCallback} should be registered at most once at any time.
3211 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003212 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003213 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003214 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003215 * Called when the framework connects to a new network to evaluate whether it satisfies this
3216 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3217 * callback. There is no guarantee that this new network will satisfy any requests, or that
3218 * the network will stay connected for longer than the time necessary to evaluate it.
3219 * <p>
3220 * Most applications <b>should not</b> act on this callback, and should instead use
3221 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3222 * the framework in properly evaluating the network &mdash; for example, an application that
3223 * can automatically log in to a captive portal without user intervention.
3224 *
3225 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09003226 *
3227 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07003228 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003229 public void onPreCheck(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003230
3231 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09003232 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003233 * This callback may be called more than once if the {@link Network} that is
3234 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003235 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003236 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003237 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3238 * @param linkProperties The {@link LinkProperties} of the satisfying network.
junyulai05986c62018-08-07 19:50:45 +08003239 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003240 * @hide
3241 */
3242 public void onAvailable(Network network, NetworkCapabilities networkCapabilities,
junyulai05986c62018-08-07 19:50:45 +08003243 LinkProperties linkProperties, boolean blocked) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003244 // Internally only this method is called when a new network is available, and
3245 // it calls the callback in the same way and order that older versions used
3246 // to call so as not to change the behavior.
3247 onAvailable(network);
3248 if (!networkCapabilities.hasCapability(
3249 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3250 onNetworkSuspended(network);
3251 }
3252 onCapabilitiesChanged(network, networkCapabilities);
3253 onLinkPropertiesChanged(network, linkProperties);
junyulai05986c62018-08-07 19:50:45 +08003254 onBlockedStatusChanged(network, blocked);
Chalard Jean804b8fb2018-01-30 22:41:41 +09003255 }
3256
3257 /**
3258 * Called when the framework connects and has declared a new network ready for use.
3259 * This callback may be called more than once if the {@link Network} that is
3260 * satisfying the request changes. This will always immediately be followed by a
3261 * call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} then by a
junyulai05986c62018-08-07 19:50:45 +08003262 * call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call to
3263 * {@link #onBlockedStatusChanged(Network, boolean)}.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003264 *
3265 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003266 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003267 public void onAvailable(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003268
3269 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003270 * Called when the network is about to be disconnected. Often paired with an
Robert Greenwalt6078b502014-06-11 16:05:07 -07003271 * {@link NetworkCallback#onAvailable} call with the new replacement network
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003272 * for graceful handover. This may not be called if we have a hard loss
3273 * (loss without warning). This may be followed by either a
Robert Greenwalt6078b502014-06-11 16:05:07 -07003274 * {@link NetworkCallback#onLost} call or a
3275 * {@link NetworkCallback#onAvailable} call for this network depending
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003276 * on whether we lose or regain it.
3277 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003278 * @param network The {@link Network} that is about to be disconnected.
3279 * @param maxMsToLive The time in ms the framework will attempt to keep the
3280 * network connected. Note that the network may suffer a
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003281 * hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003282 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003283 public void onLosing(Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003284
3285 /**
3286 * Called when the framework has a hard loss of the network or when the
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003287 * graceful failure ends.
3288 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003289 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003290 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003291 public void onLost(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003292
3293 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003294 * Called if no network is found in the timeout time specified in
Etan Cohenae574a82019-01-08 12:09:18 -08003295 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
3296 * requested network request cannot be fulfilled (whether or not a timeout was
3297 * specified). When this callback is invoked the associated
Etan Cohenaebf17e2017-03-01 12:47:28 -08003298 * {@link NetworkRequest} will have already been removed and released, as if
3299 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003300 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003301 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003302
3303 /**
3304 * Called when the network the framework connected to for this request
3305 * changes capabilities but still satisfies the stated need.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003306 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003307 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09003308 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
3309 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003310 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003311 public void onCapabilitiesChanged(Network network,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003312 NetworkCapabilities networkCapabilities) {}
3313
3314 /**
3315 * Called when the network the framework connected to for this request
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003316 * changes {@link LinkProperties}.
3317 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003318 * @param network The {@link Network} whose link properties have changed.
3319 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003320 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003321 public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07003322
Robert Greenwalt8d482522015-06-24 13:23:42 -07003323 /**
3324 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003325 * goes into {@link NetworkInfo.State#SUSPENDED}.
Robert Greenwalt8d482522015-06-24 13:23:42 -07003326 * This generally means that while the TCP connections are still live,
3327 * temporarily network data fails to transfer. Specifically this is used
3328 * on cellular networks to mask temporary outages when driving through
3329 * a tunnel, etc.
3330 * @hide
3331 */
3332 public void onNetworkSuspended(Network network) {}
3333
3334 /**
3335 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09003336 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
3337 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Robert Greenwalt8d482522015-06-24 13:23:42 -07003338 * @hide
3339 */
3340 public void onNetworkResumed(Network network) {}
3341
junyulai05986c62018-08-07 19:50:45 +08003342 /**
3343 * Called when access to the specified network is blocked or unblocked.
3344 *
3345 * @param network The {@link Network} whose blocked status has changed.
3346 * @param blocked The blocked status of this {@link Network}.
3347 */
3348 public void onBlockedStatusChanged(Network network, boolean blocked) {}
3349
Robert Greenwalt6078b502014-06-11 16:05:07 -07003350 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003351 }
3352
Hugo Benichicb883232017-05-11 13:16:17 +09003353 /**
3354 * Constant error codes used by ConnectivityService to communicate about failures and errors
3355 * across a Binder boundary.
3356 * @hide
3357 */
3358 public interface Errors {
Chalard Jean4d660112018-06-04 16:52:49 +09003359 int TOO_MANY_REQUESTS = 1;
Hugo Benichicb883232017-05-11 13:16:17 +09003360 }
3361
3362 /** @hide */
3363 public static class TooManyRequestsException extends RuntimeException {}
3364
3365 private static RuntimeException convertServiceException(ServiceSpecificException e) {
3366 switch (e.errorCode) {
3367 case Errors.TOO_MANY_REQUESTS:
3368 return new TooManyRequestsException();
3369 default:
3370 Log.w(TAG, "Unknown service error code " + e.errorCode);
3371 return new RuntimeException(e);
3372 }
3373 }
3374
Robert Greenwalt9258c642014-03-26 16:47:06 -07003375 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003376 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07003377 public static final int CALLBACK_PRECHECK = BASE + 1;
3378 /** @hide */
3379 public static final int CALLBACK_AVAILABLE = BASE + 2;
3380 /** @hide arg1 = TTL */
3381 public static final int CALLBACK_LOSING = BASE + 3;
3382 /** @hide */
3383 public static final int CALLBACK_LOST = BASE + 4;
3384 /** @hide */
3385 public static final int CALLBACK_UNAVAIL = BASE + 5;
3386 /** @hide */
3387 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
3388 /** @hide */
3389 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07003390 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09003391 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003392 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003393 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07003394 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09003395 public static final int CALLBACK_RESUMED = BASE + 10;
junyulai05986c62018-08-07 19:50:45 +08003396 /** @hide */
3397 public static final int CALLBACK_BLK_CHANGED = BASE + 11;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003398
Erik Kline57faba92015-11-25 12:49:38 +09003399 /** @hide */
3400 public static String getCallbackName(int whichCallback) {
3401 switch (whichCallback) {
3402 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
3403 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
3404 case CALLBACK_LOSING: return "CALLBACK_LOSING";
3405 case CALLBACK_LOST: return "CALLBACK_LOST";
3406 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
3407 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
3408 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003409 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
3410 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
3411 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
junyulai05986c62018-08-07 19:50:45 +08003412 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09003413 default:
3414 return Integer.toString(whichCallback);
3415 }
3416 }
3417
Robert Greenwalt562cc542014-05-15 18:07:26 -07003418 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003419 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07003420 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003421
Hugo Benichid42650f2016-07-06 22:53:17 +09003422 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003423 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003424 }
3425
Hugo Benichi2583ef02017-02-02 17:02:36 +09003426 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003427 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003428 }
3429
Robert Greenwalt9258c642014-03-26 16:47:06 -07003430 @Override
3431 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09003432 if (message.what == EXPIRE_LEGACY_REQUEST) {
3433 expireRequest((NetworkCapabilities) message.obj, message.arg1);
3434 return;
3435 }
3436
3437 final NetworkRequest request = getObject(message, NetworkRequest.class);
3438 final Network network = getObject(message, Network.class);
3439 final NetworkCallback callback;
3440 synchronized (sCallbacks) {
3441 callback = sCallbacks.get(request);
3442 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003443 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09003444 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09003445 }
Hugo Benichi2c684522017-05-09 14:36:02 +09003446 if (callback == null) {
3447 Log.w(TAG, "callback not found for " + getCallbackName(message.what) + " message");
3448 return;
3449 }
3450
Robert Greenwalt9258c642014-03-26 16:47:06 -07003451 switch (message.what) {
3452 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003453 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003454 break;
3455 }
3456 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09003457 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3458 LinkProperties lp = getObject(message, LinkProperties.class);
junyulai05986c62018-08-07 19:50:45 +08003459 callback.onAvailable(network, cap, lp, message.arg1 != 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003460 break;
3461 }
3462 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003463 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003464 break;
3465 }
3466 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003467 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003468 break;
3469 }
3470 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003471 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003472 break;
3473 }
3474 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003475 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
3476 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003477 break;
3478 }
3479 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003480 LinkProperties lp = getObject(message, LinkProperties.class);
3481 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003482 break;
3483 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07003484 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003485 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07003486 break;
3487 }
3488 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09003489 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003490 break;
3491 }
junyulai05986c62018-08-07 19:50:45 +08003492 case CALLBACK_BLK_CHANGED: {
3493 boolean blocked = message.arg1 != 0;
3494 callback.onBlockedStatusChanged(network, blocked);
3495 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003496 }
3497 }
3498
Hugo Benichid42650f2016-07-06 22:53:17 +09003499 private <T> T getObject(Message msg, Class<T> c) {
3500 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003501 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003502 }
3503
Hugo Benichi2583ef02017-02-02 17:02:36 +09003504 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003505 synchronized (sCallbacks) {
3506 if (sCallbackHandler == null) {
3507 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003508 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003509 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003510 }
3511 }
3512
Hugo Benichi6f260f32017-02-03 14:18:44 +09003513 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3514 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003515
Hugo Benichi6f260f32017-02-03 14:18:44 +09003516 private static final int LISTEN = 1;
3517 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003518
Hugo Benichi6f260f32017-02-03 14:18:44 +09003519 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3520 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003521 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003522 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003523 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003524 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003525 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003526 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003527 if (callback.networkRequest != null
3528 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003529 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3530 // and requests (http://b/20701525).
3531 Log.e(TAG, "NetworkCallback was already registered");
3532 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003533 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003534 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003535 if (action == LISTEN) {
Hugo Benichid42650f2016-07-06 22:53:17 +09003536 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04003537 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003538 request = mService.requestNetwork(
3539 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04003540 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003541 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003542 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003543 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003544 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003545 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003546 } catch (RemoteException e) {
3547 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003548 } catch (ServiceSpecificException e) {
3549 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003550 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003551 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003552 }
3553
3554 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003555 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003556 *
3557 * This is temporarily public @hide so it can be called by system code that uses the
3558 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
3559 * instead network notifications.
3560 *
3561 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
3562 *
3563 * @hide
3564 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003565 public void requestNetwork(@NonNull NetworkRequest request,
3566 @NonNull NetworkCallback networkCallback, int timeoutMs, int legacyType,
3567 @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003568 CallbackHandler cbHandler = new CallbackHandler(handler);
3569 NetworkCapabilities nc = request.networkCapabilities;
3570 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003571 }
3572
3573 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003574 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003575 *
3576 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003577 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3578 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003579 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003580 * Status of the request can be followed by listening to the various
Robert Greenwalt6078b502014-06-11 16:05:07 -07003581 * callbacks described in {@link NetworkCallback}. The {@link Network}
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003582 * can be used to direct traffic to the network.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003583 * <p>It is presently unsupported to request a network with mutable
3584 * {@link NetworkCapabilities} such as
3585 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3586 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3587 * as these {@code NetworkCapabilities} represent states that a particular
3588 * network may never attain, and whether a network will attain these states
3589 * is unknown prior to bringing up the network so the framework does not
3590 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003591 *
3592 * <p>This method requires the caller to hold either the
3593 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3594 * or the ability to modify system settings as determined by
3595 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003596 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003597 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003598 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3599 * the callback must not be shared - it uniquely specifies this request.
3600 * The callback is invoked on the default internal Handler.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003601 * @throws IllegalArgumentException if {@code request} specifies any mutable
3602 * {@code NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003603 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003604 public void requestNetwork(@NonNull NetworkRequest request,
3605 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003606 requestNetwork(request, networkCallback, getDefaultHandler());
3607 }
3608
3609 /**
3610 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3611 *
3612 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003613 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3614 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003615 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003616 * Status of the request can be followed by listening to the various
3617 * callbacks described in {@link NetworkCallback}. The {@link Network}
3618 * can be used to direct traffic to the network.
3619 * <p>It is presently unsupported to request a network with mutable
3620 * {@link NetworkCapabilities} such as
3621 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3622 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3623 * as these {@code NetworkCapabilities} represent states that a particular
3624 * network may never attain, and whether a network will attain these states
3625 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003626 * know how to go about satisfying a request with these capabilities.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003627 *
3628 * <p>This method requires the caller to hold either the
3629 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3630 * or the ability to modify system settings as determined by
3631 * {@link android.provider.Settings.System#canWrite}.</p>
3632 *
3633 * @param request {@link NetworkRequest} describing this request.
3634 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3635 * the callback must not be shared - it uniquely specifies this request.
3636 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3637 * @throws IllegalArgumentException if {@code request} specifies any mutable
3638 * {@code NetworkCapabilities}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003639 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003640 public void requestNetwork(@NonNull NetworkRequest request,
3641 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003642 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3643 CallbackHandler cbHandler = new CallbackHandler(handler);
3644 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003645 }
3646
3647 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003648 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3649 * by a timeout.
3650 *
3651 * This function behaves identically to the non-timed-out version
3652 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3653 * is not found within the given time (in milliseconds) the
3654 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3655 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3656 * not have to be released if timed-out (it is automatically released). Unregistering a
3657 * request that timed out is not an error.
3658 *
3659 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3660 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3661 * for that purpose. Calling this method will attempt to bring up the requested network.
3662 *
3663 * <p>This method requires the caller to hold either the
3664 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3665 * or the ability to modify system settings as determined by
3666 * {@link android.provider.Settings.System#canWrite}.</p>
3667 *
3668 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003669 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3670 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003671 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3672 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3673 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003674 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003675 public void requestNetwork(@NonNull NetworkRequest request,
3676 @NonNull NetworkCallback networkCallback, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003677 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003678 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003679 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003680 }
3681
Hugo Benichi2583ef02017-02-02 17:02:36 +09003682 /**
3683 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3684 * by a timeout.
3685 *
Chalard Jean4d660112018-06-04 16:52:49 +09003686 * This function behaves identically to the version without timeout, but if a suitable
Hugo Benichi2583ef02017-02-02 17:02:36 +09003687 * network is not found within the given time (in milliseconds) the
Etan Cohenaebf17e2017-03-01 12:47:28 -08003688 * {@link NetworkCallback#onUnavailable} callback is called. The request can still be
3689 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3690 * not have to be released if timed-out (it is automatically released). Unregistering a
3691 * request that timed out is not an error.
3692 *
3693 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3694 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3695 * for that purpose. Calling this method will attempt to bring up the requested network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003696 *
3697 * <p>This method requires the caller to hold either the
3698 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3699 * or the ability to modify system settings as determined by
3700 * {@link android.provider.Settings.System#canWrite}.</p>
3701 *
3702 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003703 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3704 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003705 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003706 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3707 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003708 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003709 public void requestNetwork(@NonNull NetworkRequest request,
3710 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003711 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003712 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3713 CallbackHandler cbHandler = new CallbackHandler(handler);
3714 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003715 }
3716
3717 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003718 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003719 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003720 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003721 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003722 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3723 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003724 */
Erik Kline90e93072014-11-19 12:12:24 +09003725 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003726
3727 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003728 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003729 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003730 * {@link android.content.Intent#getParcelableExtra(String)}.
3731 */
Erik Kline90e93072014-11-19 12:12:24 +09003732 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003733
3734
3735 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003736 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003737 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003738 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003739 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003740 * the request may outlive the calling application and get called back when a suitable
3741 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003742 * <p>
3743 * The operation is an Intent broadcast that goes to a broadcast receiver that
3744 * you registered with {@link Context#registerReceiver} or through the
3745 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3746 * <p>
3747 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003748 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3749 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003750 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003751 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003752 * Intent to reserve the network or it will be released shortly after the Intent
3753 * is processed.
3754 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003755 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003756 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003757 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003758 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003759 * The request may be released normally by calling
3760 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003761 * <p>It is presently unsupported to request a network with either
3762 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3763 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3764 * as these {@code NetworkCapabilities} represent states that a particular
3765 * network may never attain, and whether a network will attain these states
3766 * is unknown prior to bringing up the network so the framework does not
Chalard Jean4d660112018-06-04 16:52:49 +09003767 * know how to go about satisfying a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003768 *
3769 * <p>This method requires the caller to hold either the
3770 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3771 * or the ability to modify system settings as determined by
3772 * {@link android.provider.Settings.System#canWrite}.</p>
3773 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003774 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003775 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003776 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003777 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003778 * @throws IllegalArgumentException if {@code request} contains either
3779 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3780 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003781 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003782 public void requestNetwork(@NonNull NetworkRequest request,
3783 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003784 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003785 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003786 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003787 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003788 } catch (RemoteException e) {
3789 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003790 } catch (ServiceSpecificException e) {
3791 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003792 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003793 }
3794
3795 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003796 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3797 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003798 * This method has the same behavior as
3799 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003800 * releasing network resources and disconnecting.
3801 *
3802 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3803 * PendingIntent passed to
3804 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3805 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3806 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003807 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003808 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003809 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003810 try {
3811 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003812 } catch (RemoteException e) {
3813 throw e.rethrowFromSystemServer();
3814 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003815 }
3816
Hugo Benichie7678512017-05-09 15:19:01 +09003817 private static void checkPendingIntentNotNull(PendingIntent intent) {
3818 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3819 }
3820
3821 private static void checkCallbackNotNull(NetworkCallback callback) {
3822 Preconditions.checkNotNull(callback, "null NetworkCallback");
3823 }
3824
3825 private static void checkTimeout(int timeoutMs) {
3826 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003827 }
3828
3829 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003830 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003831 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003832 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3833 * called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003834 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003835 * @param request {@link NetworkRequest} describing this request.
3836 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3837 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003838 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003839 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003840 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003841 public void registerNetworkCallback(@NonNull NetworkRequest request,
3842 @NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003843 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3844 }
3845
3846 /**
3847 * Registers to receive notifications about all networks which satisfy the given
3848 * {@link NetworkRequest}. The callbacks will continue to be called until
Chiachang Wang90882252019-02-27 17:14:50 +08003849 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
3850 * called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003851 *
3852 * @param request {@link NetworkRequest} describing this request.
3853 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3854 * networks change state.
3855 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003856 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003857 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003858 public void registerNetworkCallback(@NonNull NetworkRequest request,
3859 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003860 CallbackHandler cbHandler = new CallbackHandler(handler);
3861 NetworkCapabilities nc = request.networkCapabilities;
3862 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003863 }
3864
3865 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003866 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3867 * {@link NetworkRequest}.
3868 *
3869 * This function behaves identically to the version that takes a NetworkCallback, but instead
3870 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3871 * the request may outlive the calling application and get called back when a suitable
3872 * network is found.
3873 * <p>
3874 * The operation is an Intent broadcast that goes to a broadcast receiver that
3875 * you registered with {@link Context#registerReceiver} or through the
3876 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3877 * <p>
3878 * The operation Intent is delivered with two extras, a {@link Network} typed
3879 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3880 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3881 * the original requests parameters.
3882 * <p>
3883 * If there is already a request for this Intent registered (with the equality of
3884 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3885 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3886 * <p>
3887 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003888 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003889 * @param request {@link NetworkRequest} describing this request.
3890 * @param operation Action to perform when the network is available (corresponds
3891 * to the {@link NetworkCallback#onAvailable} call. Typically
3892 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3893 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003894 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003895 public void registerNetworkCallback(@NonNull NetworkRequest request,
3896 @NonNull PendingIntent operation) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003897 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003898 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04003899 try {
3900 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003901 } catch (RemoteException e) {
3902 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003903 } catch (ServiceSpecificException e) {
3904 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003905 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003906 }
3907
3908 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003909 * Registers to receive notifications about changes in the system default network. The callbacks
3910 * will continue to be called until either the application exits or
3911 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09003912 *
3913 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3914 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003915 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09003916 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003917 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003918 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003919 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
3920 }
3921
3922 /**
3923 * Registers to receive notifications about changes in the system default network. The callbacks
3924 * will continue to be called until either the application exits or
3925 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003926 *
3927 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3928 * system default network changes.
3929 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003930 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003931 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09003932 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
3933 @NonNull Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09003934 // This works because if the NetworkCapabilities are null,
3935 // ConnectivityService takes them from the default request.
3936 //
3937 // Since the capabilities are exactly the same as the default request's
3938 // capabilities, this request is guaranteed, at all times, to be
3939 // satisfied by the same network, if any, that satisfies the default
3940 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003941 CallbackHandler cbHandler = new CallbackHandler(handler);
Chalard Jean4d660112018-06-04 16:52:49 +09003942 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
3943 REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09003944 }
3945
3946 /**
fengludb571472015-04-21 17:12:05 -07003947 * Requests bandwidth update for a given {@link Network} and returns whether the update request
3948 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
3949 * network connection for updated bandwidth information. The caller will be notified via
3950 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003951 * method assumes that the caller has previously called
3952 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
3953 * changes.
fenglub15e72b2015-03-20 11:29:56 -07003954 *
fengluae519192015-04-27 14:28:04 -07003955 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07003956 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07003957 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003958 public boolean requestBandwidthUpdate(@NonNull Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003959 try {
fengludb571472015-04-21 17:12:05 -07003960 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07003961 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003962 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07003963 }
3964 }
3965
3966 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003967 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003968 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
3969 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
3970 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09003971 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
3972 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003973 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09003974 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
3975 * triggering it as soon as this call returns.
3976 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003977 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003978 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09003979 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09003980 printStackTrace();
Hugo Benichie7678512017-05-09 15:19:01 +09003981 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003982 final List<NetworkRequest> reqs = new ArrayList<>();
3983 // Find all requests associated to this callback and stop callback triggers immediately.
3984 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
3985 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003986 Preconditions.checkArgument(networkCallback.networkRequest != null,
3987 "NetworkCallback was not registered");
3988 Preconditions.checkArgument(networkCallback.networkRequest != ALREADY_UNREGISTERED,
3989 "NetworkCallback was already unregistered");
Hugo Benichidafed3d2017-03-06 09:17:06 +09003990 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
3991 if (e.getValue() == networkCallback) {
3992 reqs.add(e.getKey());
3993 }
3994 }
3995 // TODO: throw exception if callback was registered more than once (http://b/20701525).
3996 for (NetworkRequest r : reqs) {
3997 try {
3998 mService.releaseNetworkRequest(r);
3999 } catch (RemoteException e) {
4000 throw e.rethrowFromSystemServer();
4001 }
4002 // Only remove mapping if rpc was successful.
4003 sCallbacks.remove(r);
4004 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09004005 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004006 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004007 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004008
4009 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004010 * Unregisters a callback previously registered via
4011 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4012 *
4013 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4014 * PendingIntent passed to
4015 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
4016 * Cannot be null.
4017 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004018 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09004019 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04004020 releaseNetworkRequest(operation);
4021 }
4022
4023 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004024 * Informs the system whether it should switch to {@code network} regardless of whether it is
4025 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
4026 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
4027 * the system default network regardless of any other network that's currently connected. If
4028 * {@code always} is true, then the choice is remembered, so that the next time the user
4029 * connects to this network, the system will switch to it.
4030 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004031 * @param network The network to accept.
4032 * @param accept Whether to accept the network even if unvalidated.
4033 * @param always Whether to remember this choice in the future.
4034 *
4035 * @hide
4036 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004037 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004038 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4039 try {
4040 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004041 } catch (RemoteException e) {
4042 throw e.rethrowFromSystemServer();
4043 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004044 }
4045
4046 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004047 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
4048 * only meaningful if the system is configured not to penalize such networks, e.g., if the
4049 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
4050 * NETWORK_AVOID_BAD_WIFI setting is unset}.
4051 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004052 * @param network The network to accept.
4053 *
4054 * @hide
4055 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004056 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09004057 public void setAvoidUnvalidated(Network network) {
4058 try {
4059 mService.setAvoidUnvalidated(network);
4060 } catch (RemoteException e) {
4061 throw e.rethrowFromSystemServer();
4062 }
4063 }
4064
4065 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09004066 * Requests that the system open the captive portal app on the specified network.
4067 *
4068 * @param network The network to log into.
4069 *
4070 * @hide
4071 */
4072 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
4073 public void startCaptivePortalApp(Network network) {
4074 try {
4075 mService.startCaptivePortalApp(network);
4076 } catch (RemoteException e) {
4077 throw e.rethrowFromSystemServer();
4078 }
4079 }
4080
4081 /**
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004082 * Requests that the system open the captive portal app with the specified extras.
4083 *
4084 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
4085 * corresponding permission.
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09004086 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004087 * @param appExtras Extras to include in the app start intent.
4088 * @hide
4089 */
4090 @SystemApi
4091 @TestApi
4092 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09004093 public void startCaptivePortalApp(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004094 try {
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09004095 mService.startCaptivePortalAppInternal(network, appExtras);
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09004096 } catch (RemoteException e) {
4097 throw e.rethrowFromSystemServer();
4098 }
4099 }
4100
4101 /**
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09004102 * Determine whether the device is configured to avoid bad wifi.
4103 * @hide
4104 */
4105 @SystemApi
4106 public boolean getAvoidBadWifi() {
4107 try {
4108 return mService.getAvoidBadWifi();
4109 } catch (RemoteException e) {
4110 throw e.rethrowFromSystemServer();
4111 }
4112 }
4113
4114 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004115 * It is acceptable to briefly use multipath data to provide seamless connectivity for
4116 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09004117 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
4118 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004119 *
4120 * An example of such an operation might be a time-sensitive foreground activity, such as a
4121 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
4122 */
4123 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
4124
4125 /**
4126 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
4127 * a backup channel for traffic that is primarily going over another network.
4128 *
4129 * An example might be maintaining backup connections to peers or servers for the purpose of
4130 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
4131 * on backup paths should be negligible compared to the traffic on the main path.
4132 */
4133 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
4134
4135 /**
4136 * It is acceptable to use metered data to improve network latency and performance.
4137 */
4138 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
4139
4140 /**
4141 * Return value to use for unmetered networks. On such networks we currently set all the flags
4142 * to true.
4143 * @hide
4144 */
4145 public static final int MULTIPATH_PREFERENCE_UNMETERED =
4146 MULTIPATH_PREFERENCE_HANDOVER |
4147 MULTIPATH_PREFERENCE_RELIABILITY |
4148 MULTIPATH_PREFERENCE_PERFORMANCE;
4149
4150 /** @hide */
4151 @Retention(RetentionPolicy.SOURCE)
4152 @IntDef(flag = true, value = {
4153 MULTIPATH_PREFERENCE_HANDOVER,
4154 MULTIPATH_PREFERENCE_RELIABILITY,
4155 MULTIPATH_PREFERENCE_PERFORMANCE,
4156 })
4157 public @interface MultipathPreference {
4158 }
4159
4160 /**
4161 * Provides a hint to the calling application on whether it is desirable to use the
4162 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
4163 * for multipath data transfer on this network when it is not the system default network.
4164 * Applications desiring to use multipath network protocols should call this method before
4165 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004166 *
4167 * @param network The network on which the application desires to use multipath data.
4168 * If {@code null}, this method will return the a preference that will generally
4169 * apply to metered networks.
4170 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
4171 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06004172 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Chalard Jean50bea3d2019-01-07 19:26:34 +09004173 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09004174 try {
4175 return mService.getMultipathPreference(network);
4176 } catch (RemoteException e) {
4177 throw e.rethrowFromSystemServer();
4178 }
4179 }
4180
4181 /**
Stuart Scott984dc852015-03-30 13:17:11 -07004182 * Resets all connectivity manager settings back to factory defaults.
4183 * @hide
4184 */
4185 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07004186 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07004187 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07004188 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004189 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07004190 }
4191 }
4192
4193 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004194 * Binds the current process to {@code network}. All Sockets created in the future
4195 * (and not explicitly bound via a bound SocketFactory from
4196 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4197 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4198 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4199 * work and all host name resolutions will fail. This is by design so an application doesn't
4200 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4201 * To clear binding pass {@code null} for {@code network}. Using individually bound
4202 * Sockets created by Network.getSocketFactory().createSocket() and
4203 * performing network-specific host name resolutions via
4204 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04004205 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004206 *
4207 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4208 * the current binding.
4209 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4210 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004211 public boolean bindProcessToNetwork(@Nullable Network network) {
Chalard Jean4d660112018-06-04 16:52:49 +09004212 // Forcing callers to call through non-static function ensures ConnectivityManager
Paul Jensen72db88e2015-03-10 10:54:12 -04004213 // instantiated.
4214 return setProcessDefaultNetwork(network);
4215 }
4216
4217 /**
4218 * Binds the current process to {@code network}. All Sockets created in the future
4219 * (and not explicitly bound via a bound SocketFactory from
4220 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
4221 * {@code network}. All host name resolutions will be limited to {@code network} as well.
4222 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
4223 * work and all host name resolutions will fail. This is by design so an application doesn't
4224 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
4225 * To clear binding pass {@code null} for {@code network}. Using individually bound
4226 * Sockets created by Network.getSocketFactory().createSocket() and
4227 * performing network-specific host name resolutions via
4228 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
4229 * {@code setProcessDefaultNetwork}.
4230 *
4231 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
4232 * the current binding.
4233 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4234 * @deprecated This function can throw {@link IllegalStateException}. Use
4235 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
4236 * is a direct replacement.
4237 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004238 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004239 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04004240 int netId = (network == null) ? NETID_UNSET : network.netId;
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004241 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
4242
Lorenzo Colitti65ceeb42019-01-30 23:04:54 +09004243 if (netId != NETID_UNSET) {
4244 netId = network.getNetIdForResolv();
Paul Jensenc91b5342014-08-27 12:38:45 -04004245 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004246
4247 if (!NetworkUtils.bindProcessToNetwork(netId)) {
4248 return false;
4249 }
4250
4251 if (!isSameNetId) {
Paul Jensene0bef712014-12-10 15:12:18 -05004252 // Set HTTP proxy system properties to match network.
4253 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09004254 try {
4255 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
4256 } catch (SecurityException e) {
4257 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
4258 Log.e(TAG, "Can't set proxy properties", e);
4259 }
Paul Jensenc91b5342014-08-27 12:38:45 -04004260 // Must flush DNS cache as new network may have different DNS resolutions.
4261 InetAddress.clearDnsCache();
4262 // Must flush socket pool as idle sockets will be bound to previous network and may
4263 // cause subsequent fetches to be performed on old network.
4264 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Paul Jensenc91b5342014-08-27 12:38:45 -04004265 }
Lorenzo Colittie5ca1162019-01-31 13:08:24 +09004266
4267 return true;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004268 }
4269
4270 /**
4271 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04004272 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004273 *
4274 * @return {@code Network} to which this process is bound, or {@code null}.
4275 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004276 @Nullable
Paul Jensen72db88e2015-03-10 10:54:12 -04004277 public Network getBoundNetworkForProcess() {
4278 // Forcing callers to call thru non-static function ensures ConnectivityManager
4279 // instantiated.
4280 return getProcessDefaultNetwork();
4281 }
4282
4283 /**
4284 * Returns the {@link Network} currently bound to this process via
4285 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
4286 *
4287 * @return {@code Network} to which this process is bound, or {@code null}.
4288 * @deprecated Using this function can lead to other functions throwing
4289 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
4290 * {@code getBoundNetworkForProcess} is a direct replacement.
4291 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004292 @Deprecated
Chalard Jean50bea3d2019-01-07 19:26:34 +09004293 @Nullable
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004294 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04004295 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04004296 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004297 return new Network(netId);
4298 }
4299
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004300 private void unsupportedStartingFrom(int version) {
4301 if (Process.myUid() == Process.SYSTEM_UID) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09004302 // The getApplicationInfo() call we make below is not supported in system context. Let
4303 // the call through here, and rely on the fact that ConnectivityService will refuse to
4304 // allow the system to use these APIs anyway.
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004305 return;
4306 }
4307
4308 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
4309 throw new UnsupportedOperationException(
4310 "This method is not supported in target SDK version " + version + " and above");
4311 }
4312 }
4313
4314 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
4315 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08004316 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004317 // remove these exemptions. Note that this check is not secure, and apps can still access these
4318 // functions by accessing ConnectivityService directly. However, it should be clear that doing
4319 // so is unsupported and may break in the future. http://b/22728205
4320 private void checkLegacyRoutingApiAccess() {
Dianne Hackborn692a2442015-07-31 10:35:34 -07004321 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09004322 }
4323
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004324 /**
4325 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04004326 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004327 *
4328 * @param network The {@link Network} to bind host resolutions from the current process to, or
4329 * {@code null} to clear the current binding.
4330 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
4331 * @hide
4332 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
4333 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07004334 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01004335 @UnsupportedAppUsage
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004336 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04004337 return NetworkUtils.bindProcessToNetworkForHostResolution(
Erik Klinef4fa9822018-04-27 22:48:33 +09004338 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04004339 }
Felipe Leme1b103232016-01-22 09:44:57 -08004340
4341 /**
4342 * Device is not restricting metered network activity while application is running on
4343 * background.
4344 */
4345 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
4346
4347 /**
4348 * Device is restricting metered network activity while application is running on background,
4349 * but application is allowed to bypass it.
4350 * <p>
4351 * In this state, application should take action to mitigate metered network access.
4352 * For example, a music streaming application should switch to a low-bandwidth bitrate.
4353 */
4354 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
4355
4356 /**
4357 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08004358 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08004359 * In this state, application should not try to use the network while running on background,
4360 * because it would be denied.
4361 */
4362 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
4363
Felipe Leme9778f762016-01-27 14:46:39 -08004364 /**
4365 * A change in the background metered network activity restriction has occurred.
4366 * <p>
4367 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
4368 * applies to them.
4369 * <p>
4370 * This is only sent to registered receivers, not manifest receivers.
4371 */
4372 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4373 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
4374 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
4375
Felipe Lemeecfccea2016-01-25 11:48:04 -08004376 /** @hide */
4377 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08004378 @IntDef(flag = false, value = {
4379 RESTRICT_BACKGROUND_STATUS_DISABLED,
4380 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
4381 RESTRICT_BACKGROUND_STATUS_ENABLED,
4382 })
Felipe Leme1b103232016-01-22 09:44:57 -08004383 public @interface RestrictBackgroundStatus {
4384 }
4385
4386 private INetworkPolicyManager getNetworkPolicyManager() {
4387 synchronized (this) {
4388 if (mNPManager != null) {
4389 return mNPManager;
4390 }
4391 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
4392 .getService(Context.NETWORK_POLICY_SERVICE));
4393 return mNPManager;
4394 }
4395 }
4396
4397 /**
4398 * Determines if the calling application is subject to metered network restrictions while
4399 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07004400 *
4401 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
4402 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
4403 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08004404 */
4405 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
4406 try {
4407 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
4408 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07004409 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08004410 }
4411 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00004412
4413 /**
4414 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00004415 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
4416 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00004417 *
4418 * @return Hash of network watchlist config file. Null if config does not exist.
4419 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004420 @Nullable
Ricky Wai44dcbde2018-01-23 04:09:45 +00004421 public byte[] getNetworkWatchlistConfigHash() {
4422 try {
4423 return mService.getNetworkWatchlistConfigHash();
4424 } catch (RemoteException e) {
4425 Log.e(TAG, "Unable to get watchlist config hash");
4426 throw e.rethrowFromSystemServer();
4427 }
4428 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004429
4430 /**
4431 * Returns the {@code uid} of the owner of a network connection.
4432 *
4433 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and
4434 * {@code IPPROTO_UDP} currently supported.
4435 * @param local The local {@link InetSocketAddress} of a connection.
4436 * @param remote The remote {@link InetSocketAddress} of a connection.
4437 *
4438 * @return {@code uid} if the connection is found and the app has permission to observe it
4439 * (e.g., if it is associated with the calling VPN app's tunnel) or
4440 * {@link android.os.Process#INVALID_UID} if the connection is not found.
Jeff Vander Stoepb58d3fe2019-02-27 13:31:22 -08004441 * Throws {@link SecurityException} if the caller is not the active VPN for the current user.
4442 * Throws {@link IllegalArgumentException} if an unsupported protocol is requested.
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004443 */
Chalard Jean50bea3d2019-01-07 19:26:34 +09004444 public int getConnectionOwnerUid(int protocol, @NonNull InetSocketAddress local,
4445 @NonNull InetSocketAddress remote) {
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07004446 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
4447 try {
4448 return mService.getConnectionOwnerUid(connectionInfo);
4449 } catch (RemoteException e) {
4450 throw e.rethrowFromSystemServer();
4451 }
4452 }
Soi, Yoshinaridee2aa42015-11-12 12:09:02 +09004453
4454 private void printStackTrace() {
4455 if (DEBUG) {
4456 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
4457 final StringBuffer sb = new StringBuffer();
4458 for (int i = 3; i < callStack.length; i++) {
4459 final String stackTrace = callStack[i].toString();
4460 if (stackTrace == null || stackTrace.contains("android.os")) {
4461 break;
4462 }
4463 sb.append(" [").append(stackTrace).append("]");
4464 }
4465 Log.d(TAG, "StackLog:" + sb.toString());
4466 }
4467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468}